计算numpy中2个点列表的距离 [英] calculate distance of 2 list of points in numpy

查看:307
本文介绍了计算numpy中2个点列表的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个点列表作为numpy.ndarray,每行是一个点的坐标,例如:

I have 2 lists of points as numpy.ndarray, each row is the coordinate of a point, like:

a = np.array([[1,0,0],[0,1,0],[0,0,1]])
b = np.array([[1,1,0],[0,1,1],[1,0,1]])

在这里,我想计算2个列表中所有对点之间的欧几里得距离,对于a中的每个点p_a,我想计算它与b中每个点p_b之间的距离.结果是

Here I want to calculate the euclidean distance between all pairs of points in the 2 lists, for each point p_a in a, I want to calculate the distance between it and every point p_b in b. So the result is

d = np.array([[1,sqrt(3),1],[1,1,sqrt(3)],[sqrt(3),1,1]])

如何在numpy中使用矩阵乘法来计算距离矩阵?

How to use matrix multiplication in numpy to compute the distance matrix?

推荐答案

使用直接的numpy广播,您可以这样做:

Using direct numpy broadcasting, you can do this:

dist = np.sqrt(((a[:, None] - b[:, :, None]) ** 2).sum(0))

或者,scipy有一个例程,该例程会稍微提高效率(特别是对于大型矩阵)

Alternatively, scipy has a routine that will compute this slightly more efficiently (particularly for large matrices)

from scipy.spatial.distance import cdist
dist = cdist(a, b)

我将避免依赖于分解出矩阵乘积(形式为A ^ 2 + B ^ 2-2AB)的解决方案,因为由于浮点舍入误差,它们在数值上可能是不稳定的.

I would avoid solutions that depend on factoring-out matrix products (of the form A^2 + B^2 - 2AB), because they can be numerically unstable due to floating point roundoff errors.

这篇关于计算numpy中2个点列表的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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