用numpy计算欧几里得距离 [英] Calculate euclidean distance with numpy

查看:100
本文介绍了用numpy计算欧几里得距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个点集,我将其坐标存储在三个不同的数组(xa,ya,za)中.现在,我要计算该点集(xa [0],ya [0],za [0]等)的每个点与另一个点集(xb,yb,zb)的所有点之间的欧式距离),并且每次都将最小距离存储在新数组中.

I have a point set which I have stored its coordinates in three different arrays (xa, ya, za). Now, I want to calculate the euclidean distance between each point of this point set (xa[0], ya[0], za[0] and so on) with all the points of an another point set (xb, yb, zb) and every time store the minimum distance in a new array.

假设xa.shape =(11,),ya.shape =(11,),za.shape =(11,). xb.shape =(13,),yb.shape =(13,),zb.shape =(13,).我想做的是每次取一个xa [],ya [],za [],并用xb,yb,zb的所有元素计算其距离,最后将最小值存储到xfinal中. shape =(11,)数组.

Let's say that xa.shape = (11,), ya.shape = (11,), za.shape= (11,). Respectively, xb.shape = (13,), yb.shape = (13,), zb.shape = (13,). What I want to do is to take each time one xa[],ya[],za[], and calculate its distance with all the elements of xb, yb, zb, and at the end store the minimum value into an xfinal.shape = (11,) array.

您认为使用numpy可以实现吗?

Do you think that this would be possible with numpy?

推荐答案

另一种解决方案是使用scipy中的空间模块,尤其是KDTree.

A different solution would be to use the spatial module from scipy, the KDTree in particular.

该类可以从一组数据中学习,并且可以在给定新数据集的情况下进行查询:

This class learn from a set of data and can be interrogated given a new dataset:

from scipy.spatial import KDTree
# create some fake data
x = arange(20)
y = rand(20)
z = x**2
# put them togheter, should have a form [n_points, n_dimension]
data = np.vstack([x, y, z]).T
# create the KDTree
kd = KDTree(data)

现在,如果您有一个点,只需执行以下操作即可询问壁橱点(或N个最近的点)的距离和索引:

now if you have a point you can ask the distance and the index of the closet point (or the N closest points) simply by doing:

kd.query([1, 2, 3])
# (1.8650720813822905, 2)
# your may differs

或者给定位置数组:

#bogus position
x2 = rand(20)*20
y2 = rand(20)*20
z2 = rand(20)*20
# join them togheter as the input
data2 = np.vstack([x2, y2, z2]).T
#query them
kd.query(data2)

#(array([ 14.96118553,   9.15924813,  16.08269197,  21.50037074,
#    18.14665096,  13.81840533,  17.464429  ,  13.29368755,
#    20.22427196,   9.95286671,   5.326888  ,  17.00112683,
#     3.66931946,  20.370496  ,  13.4808055 ,  11.92078034,
#     5.58668204,  20.20004206,   5.41354322,   4.25145521]),
#array([4, 3, 2, 4, 2, 2, 4, 2, 3, 3, 2, 3, 4, 4, 3, 3, 3, 4, 4, 4]))

这篇关于用numpy计算欧几里得距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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