2

我有两个变量,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。

4

2 回答 2

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 广播规则的一个有点不直观的应用。您的结果实际上将是869250 x 869250,在可能默认的np.float64.

您更有可能需要向量和。如果您想保留x为 a matrix(这通常令人困惑,但是...),您可以执行类似x + y.reshape(-1, 1).

于 2012-09-12T21:13:33.513 回答
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
于 2012-09-12T21:11:28.230 回答