2016-11-26 123 views
-1

我想创建一个对称的numpy数组,其值范围在0.4-1与20000 * 20000行和列之间。但是,当我创建这个大数组时,我遇到了内存错误。 请在下面找到我的代码。创建一个大的Numpy阵列

进口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) 
+0

回溯在哪里? – hpaulj

+0

@hpaulj:内存错误 – Praveen

+0

由(20000 * 20000)/ 2个浮点数*组成的数组实际上是一个非常大的对象,大小为千兆字节 – Rojan

回答

1

我复制你的函数,并取消了打印和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阵列,一路上索引使用过多的内存。我不知道有什么办法解决这个问题,但至少我们现在知道在哪里搜索。

+1

如果没有足够的内存,那么它必须按照传统的方式完成,循环(可能通过快速加速块)并设置索引。 – sirfz