Python 2.7 numpy 2D矩阵-在这种情况下如何提高性能?
我开始知道,对于一个非常大的矩阵,numpy对于单个元素的访问速度很慢。代码的以下部分运行大约需要7-8分钟。矩阵的大小约为3000*3000Python 2.7 numpy 2D矩阵-在这种情况下如何提高性能?,python-2.7,numpy,Python 2.7,Numpy,我开始知道,对于一个非常大的矩阵,numpy对于单个元素的访问速度很慢。代码的以下部分运行大约需要7-8分钟。矩阵的大小约为3000*3000 import numpy as np ................ ................ ArrayLength=len(Coordinates) AdjMatrix=np.zeros((len(Angles),len(Angles))) for x in range(0, Arraylength): for y in range
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
顺便说一下,我把坐标作为元组传递。。如p[0]=x坐标和p[1]=y坐标 您可以发布
Distance()
函数吗?如果是公共函数,scipy.space.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. ]]
[[ 0. 2.23606798 1.11803399 0. ]
[ 2.23606798 0. 2.5 2.1023796 ]
[ 1.11803399 2.5 0. 0. ]
[ 0. 2.1023796 0. 0. ]]
如果要屏蔽某些数据,请执行以下操作:
dist[dist > 3.0] = 0
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. ]]
[[ 0. 2.23606798 1.11803399 0. ]
[ 2.23606798 0. 2.5 2.1023796 ]
[ 1.11803399 2.5 0. 0. ]
[ 0. 2.1023796 0. 0. ]]
您可以将其与
AdjMatrix[AdjMatrix>=radius]=0组合,以复制上述代码,而不使用Python循环。我已编辑了我的问题。请查看@请你详细说明一下好吗?我很抱歉。。我对python不太熟悉