对于memmap,numpy mean大于max

sia*_*mii 6 python numpy numpy-memmap

我有一个时间戳数组,对于矩阵X的第二列中的每一行都会增加.我计算时间戳的平均值,它大于最大值.我正在使用numpy memmap进行存储.为什么会这样?

>>> self.X[:,1]
memmap([  1.45160858e+09,   1.45160858e+09,   1.45160858e+09, ...,
     1.45997146e+09,   1.45997683e+09,   1.45997939e+09], dtype=float32)
>>> np.mean(self.X[:,1])
1.4642646e+09
>>> np.max(self.X[:,1])
memmap(1459979392.0, dtype=float32)
>>> np.average(self.X[:,1])
1.4642646e+09
>>> self.X[:,1].shape
(873608,)
>>> np.sum(self.X[:,1])
memmap(1279193195216896.0, dtype=float32)
>>> np.sum(self.X[:,1]) / self.X[:,1].shape[0]
memmap(1464264515.9120522)
Run Code Online (Sandbox Code Playgroud)

编辑:我在这里上传了memmap文件.http://www.filedropper.com/x_2这是我加载它的方式.

filepath = ...
shape = (875422, 23)
X = np.memmap(filepath, dtype="float32", mode="r", shape=shape)

# I preprocess X by removing rows with all 0s
# note this step doesn't affect the problem
to_remove = np.where(np.all(X == 0, axis=1))[0]
X = np.delete(X, to_remove, axis=0)
Run Code Online (Sandbox Code Playgroud)

Vas*_*nth 6

这不是一个numpy或memmap问题.float32确切地说,问题在于浮点数.您可以在其他语言(如C++)中看到相同的错误.

float32随着越来越多的数字被添加到使用的累加器变得不精确.

In [26]: a = np.ones((1024,1024), dtype=np.float32)*4567

In [27]: a.min()
Out[27]: 4567.0

In [28]: a.max()
Out[28]: 4567.0

In [29]: a.mean()
Out[29]: 4596.5264
Run Code Online (Sandbox Code Playgroud)

这不会发生在np.float64类型中(给一些更多的喘息空间).

In [30]: a = np.ones((1024,1024), dtype=np.float64)*4567

In [31]: a.min()
Out[31]: 4567.0

In [32]: a.mean()
Out[32]: 4567.0
Run Code Online (Sandbox Code Playgroud)

您可以通过显式指定缓冲区mean()来使用float64缓冲区.

In [12]: a = np.ones((1024,1024), dtype=np.float32)*4567

In [13]: a.mean(dtype=np.float64)
Out[13]: 4567.0
Run Code Online (Sandbox Code Playgroud)