numpy中大型数组的点积
我有一个很大的数组,我想用一个小数组来计算点积。但是我遇到了“数组太大”的问题。有没有什么解决办法?
import numpy as np
eMatrix = np.random.random_integers(low=0,high=100,size=(20000000,50))
pMatrix = np.random.random_integers(low=0,high=10,size=(50,50))
a = np.dot(eMatrix,pMatrix)
Error:
/Library/Python/2.7/site-packages/numpy/random/mtrand.so in mtrand.RandomState.random_integers (numpy/random/mtrand/mtrand.c:9385)()
/Library/Python/2.7/site-packages/numpy/random/mtrand.so in mtrand.RandomState.randint (numpy/random/mtrand/mtrand.c:7051)()
ValueError: array is too big.
3 个回答
0
我觉得问题的原因可能是你的电脑内存不够,还有可能是你在用32位的Python版本。可以说明一下你用的是什么操作系统吗?很多操作系统都可以同时运行32位和64位的程序。
0
我觉得唯一“简单”的解决办法就是增加内存。
我在我的MacBook上用了15GB的内存,但还是能做到这一点。
In [1]: import numpy
In [2]: e = numpy.random.random_integers(low=0, high=100, size=(20000000, 50))
In [3]: p = numpy.random.random_integers(low=0, high=10, size=(50, 50))
In [4]: a = numpy.dot(e, p)
In [5]: a[0]
Out[5]:
array([14753, 12720, 15324, 13588, 16667, 16055, 14144, 15239, 15166,
14293, 16786, 12358, 14880, 13846, 11950, 13836, 13393, 14679,
15292, 15472, 15734, 12095, 14264, 12242, 12684, 11596, 15987,
15275, 13572, 14534, 16472, 14818, 13374, 14115, 13171, 11927,
14226, 13312, 16070, 13524, 16591, 16533, 15466, 15440, 15595,
13164, 14278, 13692, 12415, 13314])
一个可能的解决方案是使用稀疏矩阵和稀疏矩阵的点乘操作。
比如,在我的电脑上,构建一个叫e
的密集矩阵就用了8GB的内存。而构建一个类似的稀疏矩阵eprime
:
In [1]: from scipy.sparse import rand
In [2]: eprime = rand(20000000, 50)
在内存占用上几乎没有成本。
3
这个错误是在计算数组的总大小时出现的,如果这个大小超过了本地整数类型的限制,就会发生这种情况,具体的代码位置可以查看这里。
要出现这种情况,不管你的机器是64位的,你很可能在使用32位版本的Python(和NumPy)。你可以通过以下方式检查是否是这种情况:
>>> import sys
>>> sys.maxsize
2147483647 # <--- 2**31 - 1, on a 64 bit version you would get 2**63 - 1
不过,你的数组“仅仅是” 20000000 * 50 = 1000000000
,这稍微低于 2**30
。如果我在32位的NumPy上尝试复现你的结果,我会得到一个 MemoryError
:
>>> np.random.random_integers(low=0,high=100,size=(20000000,50))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mtrand.pyx", line 1420, in mtrand.RandomState.random_integers (numpy\random\mtrand\mtrand.c:12943)
File "mtrand.pyx", line 938, in mtrand.RandomState.randint (numpy\random\mtrand\mtrand.c:10338)
MemoryError
除非我把大小增加到超过神奇的 2**31 - 1
的阈值
>>> np.random.random_integers(low=0,high=100,size=(2**30, 2))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mtrand.pyx", line 1420, in mtrand.RandomState.random_integers (numpy\random\mtrand\mtrand.c:12943)
File "mtrand.pyx", line 938, in mtrand.RandomState.randint (numpy\random\mtrand\mtrand.c:10338)
ValueError: array is too big.
根据你错误信息中的行号和我的不同,我怀疑你使用的是旧版本。你系统上运行这个命令会输出什么:
>>> np.__version__
'1.10.0.dev-9c50f98'