3
我點的numpy的數組:歐幾里得距離
points = rand(dim, n_points)
我需要:
- 計算所有L2範數(歐幾里得距離)的某個點和所有其他之間分數
- 計算所有成對距離。
並且最好是所有的numpy和no的。如何做到這一點?
我點的numpy的數組:歐幾里得距離
points = rand(dim, n_points)
我需要:
並且最好是所有的numpy和no的。如何做到這一點?
如果你願意使用SciPy的,在scipy.spatial.distance
模塊(功能cdist
和/或pdist
)你想要什麼,所有的在C.循環做,你可以用廣播做到這一點,但有一些額外的內存開銷。
這可能與第二部分幫助:
import numpy as np
from numpy import *
p=rand(3,4) # this is column-wise so each vector has length 3
sqrt(sum((p[:,np.newaxis,:]-p[:,:,np.newaxis])**2 ,axis=0))
這給
array([[ 0. , 0.37355868, 0.64896708, 1.14974483],
[ 0.37355868, 0. , 0.6277216 , 1.19625254],
[ 0.64896708, 0.6277216 , 0. , 0.77465192],
[ 1.14974483, 1.19625254, 0.77465192, 0. ]])
如果p是
array([[ 0.46193242, 0.11934744, 0.3836483 , 0.84897951],
[ 0.19102709, 0.33050367, 0.36382587, 0.96880535],
[ 0.84963349, 0.79740414, 0.22901247, 0.09652746]])
並且你可以通過
檢查中的一個條目sqrt(sum ((p[:,0]-p[:,2])**2))
0.64896708223796884
訣竅是把newaxis,然後做廣播。
祝你好運!