python - 内存映射 ndarray 上的 numpy.std 因 MemoryError 失败

标签 python python-3.x numpy out-of-memory

我有一个巨大的(30GB)ndarray内存映射:

arr = numpy.memmap(afile, dtype=numpy.float32, mode="w+", shape=(n, n,))

在填写一些值后(这非常好 - 最大内存使用量低于 1GB),我想计算标准偏差:

print('stdev: {0:4.4f}\n'.format(numpy.std(arr)))

此行因 MemoryError 严重失败。

我不确定为什么会失败。我将不胜感激如何以内存有效的方式计算这些提示?

环境:venv + Python3.6.2 + NumPy 1.13.1

最佳答案

事实上,numpy 的 stdmean 实现制作了数组的完整副本,并且内存效率非常低。这是一个更好的实现:

# Memory overhead is BLOCKSIZE * itemsize. Should be at least ~1MB 
# for efficient HDD access.
BLOCKSIZE = 1024**2
# For numerical stability. The closer this is to mean(arr), the better.
PIVOT = arr[0]

n = len(arr)
sum_ = 0.
sum_sq = 0.
for block_start in xrange(0, n, BLOCKSIZE):
     block_data = arr[block_start:block_start + BLOCKSIZE]
     block_data -= PIVOT
     sum_ += np.sum(block_data)
     sum_sq += np.sum(block_data**2)
stdev = np.sqrt(sum_sq / n - (sum_ / n)**2)

关于python - 内存映射 ndarray 上的 numpy.std 因 MemoryError 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46099857/

相关文章:

python - 将两个系列合并/压缩到 ndarray 的 ndarray

python - 获取组名称作为图形 matplotlib 中的轴

python - 删除字符串之间的空格

python - 如何针对复杂问题适本地使用位置参数

python -\b 正则表达式包括句点作为单词

python - 对数组中所有小于当前值的值求和

python - Flask-SQLAlchemy 查询计数

python - B 和 C 不工作(Python3)

python-3.x - clear()不会使用selenium和python和firefox清除文本框

python - 使用spreadsheets.batchUpdate发送多个请求会导致错误