Numpy内存不足

时间:2012-09-12 21:00:49

标签: python memory numpy

我有两个变量,x和y。 x是

type(x) = <class 'numpy.matrixlib.defmatrix.matrix'>

type(y) = <type 'numpy.ndarray'>

x.shape = (869250, 1)

y.shape = (869250,)

x + y给出了一个MemoryError,尽管事实上我有大约5 GB的空闲时间。这似乎很奇怪 - 有没有人知道可能会发生什么?

这是64位Linux上的numpy 1.5.1,python 2.7。

2 个答案:

答案 0 :(得分:5)

你确定你正在做你想做的事吗?

In [2]: x = np.random.normal(size=(500,1))

In [3]: y = np.random.normal(size=(500,))

In [4]: (x + y).shape
Out[4]: (500, 500)

numpy's broadcasting rules这是一个有点不直观的应用。您的结果实际上是869250 x 869250,在可能默认的np.float64中总共有5.5 TB的存储空间。

你更有可能想要矢量和。如果您想将x保留为matrix(这通常令人困惑,但......),您可以执行x + y.reshape(-1, 1)之类的操作。

答案 1 :(得分:0)

您是否尝试过检查每个阵列需要多少内存? 以及......编辑以包含评论:

In [14]: b = np.random.random((2,3))

In [16]: b.itemsize*b.size
Out[16]: 48


In [17]: b = np.random.random((200,3))

In [18]: b.itemsize*b.size
Out[18]: 4800

现在想象结果还需要一个可以保存的地方......

你没有在你的numpy数组中写出什么样的数据,但如果每个项目都是8字节,那么,你的第一个项目(x)已经很胖了:

In [19]: 869250*8/1024 # the output is the size in KB ...
Out[19]: 6791
相关问题