简体   繁体   English

(M,N)和(N,)数组之间的距离计算

[英]Distance computation between (M,N) and (N,) arrays

I am calculating Euclidean distances in python. 我正在计算python中的欧几里德距离。 I want to learn how to calculate it without using a for loop. 我想学习如何在不使用for循环的情况下计算它。 Here is my code, 这是我的代码,

import numpy as np
import random
A = np.random.randint(5, size=(10, 5))
B = [1, 3, 5, 2, 4]
for i in range(10):
    dist = np.linalg.norm(A[i]-B)
    print("Distances: ", dist)

Is there anyway in which I can use advanced indexing or any other techniques to calculate the distances without using a for loop? 无论如何,我可以使用高级索引或任何其他技术来计算距离而不使用for循环? thanks. 谢谢。

Approach #1 : Most straight-forward one with np.linalg.norm using its axis param and also leveraging broadcasting would be - 方法#1:大多数直截了当的np.linalg.norm使用其axis参数并利用broadcasting将是 -

np.linalg.norm(A-B,axis=1)

Approach #2 : With einsum - 方法#2:使用einsum -

subs = A - B
out = np.sqrt(np.einsum('ij,ij->i',subs,subs))

Approach #3 : Using (ab)^2 = a^2 + b^2 - 2ab formula to leverage matrix-multiplication with np.dot and np.inner - 方法#3:使用(ab)^2 = a^2 + b^2 - 2ab公式利用与np.dotnp.inner matrix-multiplication -

np.sqrt(np.einsum('ij,ij->i',A, A) + np.inner(B,B) - 2*A.dot(B))

You can calculate the Frobenius Norm explicitly: 您可以明确地计算Frobenius规范

res = (np.abs(A - B)**2).sum(1)**0.5

This is the default for np.linalg.norm . 这是np.linalg.norm的默认值。 Here's a demo: 这是一个演示:

np.random.seed(0)
A = np.random.randint(5, size=(10, 5))
B = [1, 3, 5, 2, 4]

res = (np.abs(A - B)**2).sum(1)**0.5

array([4.89897949, 5.38516481, 5.29150262, 5.47722558, 5.        ,
       5.56776436, 6.244998  , 2.23606798, 5.56776436, 4.47213595])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM