【发布时间】:2011-01-29 19:10:18
【问题描述】:
我在 numpy 中有一个点数组:
points = rand(dim, n_points)
我想:
- 计算某个点与所有其他点之间的所有 l2 范数(欧几里得距离)
- 计算所有成对距离。
最好是所有 numpy 并且没有 for's。怎么可能?
【问题讨论】:
标签: python numpy euclidean-distance
我在 numpy 中有一个点数组:
points = rand(dim, n_points)
我想:
最好是所有 numpy 并且没有 for's。怎么可能?
【问题讨论】:
标签: python numpy euclidean-distance
如果您愿意使用 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,然后做广播。
祝你好运!
【讨论】: