numpy广播以执行欧式距离矢量化 [英] Numpy Broadcast to perform euclidean distance vectorized

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

问题描述

我有2 x 4和3 x 4的矩阵.我想找到各行之间的欧几里得距离,并在最后得到2 x 3的矩阵.这是一个带for循环的代码,它针对所有b行向量计算a中每个行向量的欧几里得距离.不使用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广播以执行欧式距离矢量化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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