我有一个大型数据集,statistic
,其中 statistic.shape = (1E10,)
,我想有效地将其(总和)合并到一个零数组中, out = np.zeros(1E10)
。 statistic
中的每个条目都有一个相应的索引 idx
,它告诉我它属于哪个 out
bin。索引不是唯一的,因此我无法使用 out += statistic[idx]
因为这只会在第一次遇到特定索引时进行计数。因此我使用np.add.at(out, idx, statistic)
。我的问题是,对于非常大的数组,np.add.at() 返回错误的答案。
下面是显示此行为的示例脚本。函数 check_add()
应返回 1。
import numpy as np
def check_add(N):
N = int(N)
out = np.zeros(N)
np.add.at(out, np.arange(N), np.ones(N))
return np.sum(out)/N
n_arr = [1E3, 1E5, 1E8, 1E10]
for n in n_arr:
print('N = {} (log(N) = {}); output ratio is {}'.format(n, np.log10(n), check_add(n)))
这个例子返回给我:
N = 1000.0 (log(N) = 3.0); output ratio is 1.0
N = 100000.0 (log(N) = 5.0); output ratio is 1.0
N = 100000000.0 (log(N) = 8.0); output ratio is 1.0
N = 10000000000.0 (log(N) = 10.0); output ratio is 0.1410065408
有人可以向我解释一下为什么 N=1E10
的函数会失败吗?
最佳答案
这是一个老错误,NumPy issue 13286 。 ufunc.at
使用的循环计数器变量太小。它得到了fixed不久前,所以更新你的 NumPy。 (此修复程序存在于 1.16.3 及更高版本中。)
关于python - 为什么 np.add.at() 对于大型数组返回错误的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64803546/