我正在尝试计算两个大小分别为 (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 位的计算机上使用 Python 3.4.2(64 位)和 Numpy 1.9.1,该计算机具有运行 Ubuntu 14.10 的 16GB 内存。
您收到内存错误的原因可能是因为 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。通常,只要内存中所有内容都适合,较大的块大小就会更快。
我认为问题从矩阵 A 本身开始,因为如果每个元素都是双精度浮点数,则 16225 * 10000 大小的矩阵已经占用了大约 12GB 的内存。这与numpy如何创建临时副本以执行点操作一起将导致错误。额外的副本是因为 numpy 对点使用底层 BLAS 操作,这需要矩阵以连续的 C 顺序存储
如果您想了解更多有关提高点性能的讨论,请查看这些链接
http://wiki.scipy.org/PerformanceTips
加速 numpy.dot
https://github.com/numpy/numpy/pull/2730