我试图计算两个大小分别为(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)我怎样才能规避/解决这个问题?
我使用Python3.4.2(64位)和Numpy 1.9.1在一台配备了16 of内存的计算机上运行Ubuntu14.10。
发布于 2014-12-27 15:29:16
我认为这个问题从矩阵A本身开始,因为一个16225 * 10000大小的矩阵已经占用了大约12 is的内存,如果每个元素都是一个双精度浮点数。再加上numpy如何创建临时副本来执行点操作,就会导致错误。额外的副本是因为numpy对点使用底层BLAS操作,它需要以连续的C顺序存储矩阵。
如果您想要更多地讨论如何提高点性能,请查看这些链接。
http://wiki.scipy.org/PerformanceTips
发布于 2014-12-27 18:22:17
获得内存错误的原因可能是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。通常情况下,只要所有东西都在内存中,更大的块大小就会更快。
https://stackoverflow.com/questions/27668462
复制相似问题