我正在尝试计算两个大小分别为 (162225, 10000) 和 (10000, 100) 的 numpy 数组的点积。但是,如果我调用 numpy.dot(A, B) 则会发生 MemoryError 。
然后,我尝试编写我的实现:
def slower_dot (A, B):
"""Low-memory implementation of dot product"""
#Assuming A and B are of the right type and size
R = np.empty([A.shape[0], B.shape[1]])
for i in range(A.shape[0]):
for j in range(B.shape[1]):
R[i,j] = np.dot(A[i,:], B[:,j])
return R
它工作得很好,但当然很慢。您知道 1)此行为背后的原因是什么以及 2)我如何规避/解决该问题吗?
我在一台配备 64 位、16GB 内存、运行 Ubuntu 14.10 的计算机上使用 Python 3.4.2(64 位)和 Numpy 1.9.1。
您收到内存错误的原因可能是因为 numpy 试图在调用中复制一个或两个数组dot
。对于中小型数组,这通常是最有效的选择,但对于大型数组,您需要对 numpy 进行微观管理以避免内存错误。你的slower_dot
函数很慢主要是因为 python 函数调用开销,您会遭受 162225 x 100 次。当您想要平衡内存和性能限制时,这是处理这种情况的一种常见方法。
import numpy as np
def chunking_dot(big_matrix, small_matrix, chunk_size=100):
# Make a copy if the array is not already contiguous
small_matrix = np.ascontiguousarray(small_matrix)
R = np.empty((big_matrix.shape[0], small_matrix.shape[1]))
for i in range(0, R.shape[0], chunk_size):
end = i + chunk_size
R[i:end] = np.dot(big_matrix[i:end], small_matrix)
return R
您需要选择最适合您的特定数组大小的 chunk_size 。通常,只要所有内容都适合内存,较大的块大小会更快。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)