python numpy行向量矩阵之间的欧式距离计算 [英] python numpy euclidean distance calculation between matrices of row vectors

查看:1942
本文介绍了python numpy行向量矩阵之间的欧式距离计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Numpy的新手,我想问你如何计算向量中存储的点之间的欧式距离.

I am new to Numpy and I would like to ask you how to calculate euclidean distance between points stored in a vector.

让我们假设我们有一个numpy.array,每一行都是一个向量,还有一个numpy.array.我想知道是否有可能计算所有点与该单点之间的欧几里得距离并将它们存储在一个numpy.array中.

Let's assume that we have a numpy.array each row is a vector and a single numpy.array. I would like to know if it is possible to calculate the euclidean distance between all the points and this single point and store them in one numpy.array.

这是一个界面:

points #2d list of row-vectors
singlePoint #one row-vector

listOfDistances= procedure( points,singlePoint)

我们可以有这样的东西吗? 还是可以使用一个命令将单个点作为其他点的列表,最后得到距离矩阵?

Can we have something like this? Or is it possible to have one command to have the single point as a list of other points and at the end we get a matrix of distances?

谢谢

推荐答案

虽然您可以使用向量化,但使用numpy数组时@Karl的方法会相当慢.

While you can use vectorize, @Karl's approach will be rather slow with numpy arrays.

更简单的方法是只执行np.hypot(*(points - single_point).T). (转置假定点是Nx2数组,而不是2xN.如果是2xN,则不需要.T.

The easier approach is to just do np.hypot(*(points - single_point).T). (The transpose assumes that points is a Nx2 array, rather than a 2xN. If it's 2xN, you don't need the .T.

但是这有点难以理解,因此您可以像这样(用一些罐头示例数据...)更明确地写出来:

However this is a bit unreadable, so you write it out more explictly like this (using some canned example data...):

import numpy as np
single_point = [3, 4]
points = np.arange(20).reshape((10,2))

dist = (points - single_point)**2
dist = np.sum(dist, axis=1)
dist = np.sqrt(dist)

这篇关于python numpy行向量矩阵之间的欧式距离计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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