创建一个大型 Numpy 数组

Create a Large Numpy Array

我正在尝试创建一个对称的 numpy 数组,其值介于 0.4-1 之间,具有 20000*20000 行和列。但是,当我创建这个大数组时出现内存错误。 请在下面找到我的代码。

将 numpy 导入为 np

def random_symmetric_matrix(n):
    _R = np.random.uniform(0.4,1,n*(n-1)/2)
    P = np.zeros((n,n))
    P[np.triu_indices(n, 1)] = _R
    P[np.tril_indices(n, -1)] = P.T[np.tril_indices(n, -1)]
    print P
    np.savetxt("b.txt",P, delimiter=' ')
    return P

random_symmetric_matrix(6000)

我复制了你的函数,删除了 print 和 savetxt:

In [574]: def random_symmetric_matrix(n):
     ...:     _R = np.random.uniform(0.4,1,n*(n-1)//2)
     ...:     P = np.zeros((n,n))
     ...:     print('...')
     ...:     P[np.triu_indices(n, 1)] = _R
     ...:     print(',,,')
     ...:     P[np.tril_indices(n, -1)] = P.T[np.tril_indices(n, -1)]
     ...:     return P

在一台旧的小型机器上,它开始陷入 n=4000 的困境。

这是我的第一个记忆错误:

In [573]: random_symmetric_matrix(14000).shape
...
---------------------------------------------------------------------------
MemoryError                               Traceback (most recent call last)
<ipython-input-573-32a007267a79> in <module>()
----> 1 random_symmetric_matrix(14000).shape

<ipython-input-565-9f171b601d49> in random_symmetric_matrix(n)
      3     P = np.zeros((n,n))
      4     print('...')
----> 5     P[np.triu_indices(n, 1)] = _R
      6     print(',,,')
      7     P[np.tril_indices(n, -1)] = P.T[np.tril_indices(n, -1)]

/usr/lib/python3/dist-packages/numpy/lib/twodim_base.py in triu_indices(n, k, m)
    973 
    974     """
--> 975     return where(~tri(n, m, k=k-1, dtype=bool))
    976 
    977 

MemoryError: 

关注问题陈述:

In [576]: np.triu_indices(4,1)
Out[576]: 
(array([0, 0, 0, 1, 1, 2], dtype=int32),
 array([1, 2, 3, 2, 3, 3], dtype=int32))
In [577]: np.triu_indices(4,1)[0].shape
Out[577]: (6,)
In [578]: np.triu_indices(400,1)[0].shape
Out[578]: (79800,)
In [579]: np.triu_indices(4000,1)[0].shape
Out[579]: (7998000,)

构建tri没有问题;但是收集 where 索引会破坏内存。

In [593]: T=np.tri(10000, 10000, k=-1, dtype=bool)
In [594]: T.shape
Out[594]: (10000, 10000)
In [595]: np.where(T)
---------------------------------------------------------------------------
MemoryError                               Traceback (most recent call last)
<ipython-input-595-33094d2967ea> in <module>()
----> 1 np.where(T)

MemoryError: 

因此,虽然 P 数组似乎有足够的内存,但沿途进行索引会占用太多内存。当然,我不知道如何解决这个问题,但至少我们现在知道去哪里搜索了。