Numpy Broadcast 执行矢量化欧氏距离 [英] Numpy Broadcast to perform euclidean distance vectorized

查看:39
本文介绍了Numpy Broadcast 执行矢量化欧氏距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 x 4 和 3 x 4 的矩阵.我想找到跨行的欧几里得距离,最后得到一个 2 x 3 的矩阵.这是带有一个 for 循环的代码,用于计算 a 中每个行向量与所有 b 行向量的欧几里德距离.如何在不使用 for 循环的情况下执行相同操作?

I have matrices that are 2 x 4 and 3 x 4. I want to find the euclidean distance across rows, and get a 2 x 3 matrix at the end. Here is the code with one for loop that computes the euclidean distance for every row vector in a against all b row vectors. How do I do the same without using for loops?

 import numpy as np
a = np.array([[1,1,1,1],[2,2,2,2]])
b = np.array([[1,2,3,4],[1,1,1,1],[1,2,1,9]])
dists = np.zeros((2, 3))
for i in range(2):
      dists[i] = np.sqrt(np.sum(np.square(a[i] - b), axis=1))

推荐答案

只需在正确的位置使用 np.newaxis:

Simply use np.newaxis at the right place:

 np.sqrt((np.square(a[:,np.newaxis]-b).sum(axis=2)))

这篇关于Numpy Broadcast 执行矢量化欧氏距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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