2013-07-26 21 views
4

這是一個小代碼,它演示了我得到的錯誤。numpy缺少屬性取決於數組大小

import numpy as np 

r=4.0 
L=20.0 
ratio = 4*np.pi/3.0 * (r/L)**3 

for i in range(5, 16): 
    n = 10**i 
    m = int(ratio * n) 
    print i,n,m 

    ip = np.random.random_integers(100, size=(n,3))  
    jp = np.random.random_integers(100, size=(m,3)) 

    a = np.expand_dims(ip, -1) == jp.T 
    b = np.where(a.all(axis=1).any(axis=1))[0] 

我得到以下輸出:

5 100000 3351 
6 1000000 33510 
Traceback (most recent call last): 
    File "example.py", line 16, in <module> 
    b = np.where(a.all(axis=1).any(axis=1))[0] 
AttributeError: 'bool' object has no attribute 'all' 

任何人都知道是怎麼回事?

另外,一個合理的快速方式索引ip中元素的位置也可以。我可能會從第二個解決方案here

+1

其中'i == 5'數組'a'的大小已經在10億個元素的數量級上,其中'i == 6'是它的1000億個元素(如果是'bool',100 GB的數據)。這些非常大的陣列是故意的嗎? – Daniel

+0

大小是有意的,他們是一個相當密集的計算網格。在'i == 6'' np.expand_dims(ip,-1).nbytes == 24000000'這應該是合理的,不是? – user1984528

+0

是的,這是合理的,但是你用'jp.T'來廣播這個大小來表示'a'的大小。以GB爲單位打印a.nbytes/1E9'。 – Daniel

回答

0

您正在廣播ip針對jp創建非常大的數組。當i==6你有一個100GB的陣列。

一種解決方案是循環陣列之上:

for i in range(2,6): 
    t=time.time() 
    n = 10**i+1 
    m = int(ratio * n) 
    print i,n,m 

    ip = np.random.random_integers(10, size=(n,3)) 
    jp = np.random.random_integers(10, size=(m,3)) 

    chunksize=10000 
    if chunksize>ip.shape[0]: 
     chunksize=ip.shape[0] 
    span=ip.shape[0]/chunksize 
    remainder=(ip.shape[0]-span*chunksize) 

    out=[] 
    start=0 
    for n in xrange(span): 
     end=start+chunksize 
     a = np.expand_dims(ip[start:end], -1) == jp.T 
     b = np.where(a.all(axis=1).any(axis=1))[0] 
     out.append(b+start) 
     start+=chunksize 

    if remainder!=0: 
     a = np.expand_dims(ip[-remainder:], -1) == jp.T 
     b = np.where(a.all(axis=1).any(axis=1))[0] 
     out.append(b+end) 

    end=np.sort(np.concatenate(out)) 
    print time.time()-t,end.shape 

時間爲約10秒i==6所以i==7將需要約20分鐘。