2013-04-05 111 views
1

我開始知道numpy對於一個非常大的矩陣來說是單個元素訪問緩慢的。代碼的以下部分需要大約7-8分鐘才能運行。矩陣的大小大約是3000 * 3000numpy 2D矩陣 - 在這種情況下如何提高性能?

import numpy as np 
................ 
................ 
ArrayLength=len(Coordinates) 
AdjMatrix=np.zeros((len(Angles),len(Angles))) 
for x in range(0, Arraylength): 
    for y in range(x+1, Arraylength-x): 
     distance=Distance(Coordinates[x],Coordinates[y) 
      if(distance<=radius) 
       AdjMatrix[x][y]=distance 
       AdjMatrix[y][x]=distance 

我基本上是試圖構建一個鄰接矩陣爲一個由約3000節點的圖。有人可以幫助我做這種顛簸的方式嗎?或者任何替代品?

編輯:這裏是距離()函數

Def Distance(p1,p2): 
    distance=np.sqrt(np.square(p1[0]-p2[0])+np.square(p1[1]-p2[1])) 
    return distance 

通過我傳遞座標元組的方式。作爲在P [0] = x座標和P [1] = y座標。

回答

3

你能發佈Distance()函數嗎?如果它是常見的功能,scipy.spatial.distance.cdist可以非常快速地計算距離矩陣:

http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist

編輯

您可以使用pdist的確,這裏有一個例子:

from scipy.spatial.distance import pdist, squareform 
coordinates = [(0.0, 0), (1.0, 2.0), (-1.0, 0.5), (3.1, 2.1)] 
dist = squareform(pdist(coordinates)) 
print dist 

輸出:

[[ 0.   2.23606798 1.11803399 3.74432905] 
[ 2.23606798 0.   2.5   2.1023796 ] 
[ 1.11803399 2.5   0.   4.40113622] 
[ 3.74432905 2.1023796 4.40113622 0.  ]] 

如果你想掩蓋一些數據:

dist[dist > 3.0] = 0 
print dist 

輸出:

[[ 0.   2.23606798 1.11803399 0.  ] 
[ 2.23606798 0.   2.5   2.1023796 ] 
[ 1.11803399 2.5   0.   0.  ] 
[ 0.   2.1023796 0.   0.  ]] 
+1

你可以用'AdjMatrix [AdjMatrix> =半徑] = 0'結合這重複上面的代碼,沒有Python循環。 – mtrw 2013-04-05 11:01:12

+0

我已編輯我的問題。請看看。 @mtrw請你詳細說明一下嗎?我很抱歉..我不太熟悉python – 2013-04-05 11:22:07