我有一个时间戳数组,矩阵 X 的第 2 列中的每一行都递增。我计算了时间戳的平均值,它大于最大值。我正在使用 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)
编辑: 我已经在这里上传了 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)
最佳答案
这不是 numpy 或 memmap 问题。问题在于 float ,准确地说是 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
这不会发生在 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
您可以通过明确指定 mean()
使用 float64
缓冲区。
In [12]: a = np.ones((1024,1024), dtype=np.float32)*4567
In [13]: a.mean(dtype=np.float64)
Out[13]: 4567.0
关于python - numpy 的平均值大于 memmap 的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36522791/