如何计算一个numpy数组的成对的行之间的欧几里得距离 [英] How to calculate euclidean distance between pair of rows of a numpy array

查看:89
本文介绍了如何计算一个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,0.0,1.4142135623730951]

[1.4142135623730951, 0.0, 1.4142135623730951]

[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数组的成对的行之间的欧几里得距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆