本文介绍了如何计算一个numpy数组的成对的行之间的欧几里得距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个numpy
数组,例如:
import numpy as np
a = np.array([[1,0,1,0],
[1,1,0,0],
[1,0,1,0],
[0,0,1,1]])
我想计算每对行之间的euclidian distance
.
I would like to calculate euclidian distance
between each pair of rows.
from scipy.spatial import distance
for i in range(0,a.shape[0]):
d = [np.sqrt(np.sum((a[i]-a[j])**2)) for j in range(i+1,a.shape[0])]
print(d)
[1.4142135623730951,2.0]
[1.4142135623730951, 2.0]
[1.4142135623730951]
[1.4142135623730951]
[]
由于我必须在巨大的numpy
数组上运行此代码,有没有更好的pythonic方法?
Is there any better pythonic way to do this since i have to run this code on a huge numpy
array?
推荐答案
出于完整性考虑,einsum通常用于距离计算.
And for completeness, einsum is often referenced for distance calculations.
a = np.array([[1,0,1,0],
[1,1,0,0],
[1,0,1,0],
[0,0,1,1]])
b = a.reshape(a.shape[0], 1, a.shape[1])
np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b))
array([[ 0. , 1.41421356, 0. , 1.41421356],
[ 1.41421356, 0. , 1.41421356, 2. ],
[ 0. , 1.41421356, 0. , 1.41421356],
[ 1.41421356, 2. , 1.41421356, 0. ]])
这篇关于如何计算一个numpy数组的成对的行之间的欧几里得距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!