Distance computation between (M,N) and (N,) arrays

Viewed 63

I am calculating Euclidean distances in python. I want to learn how to calculate it without using a for loop. 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? thanks.

2 Answers

Approach #1 : Most straight-forward one with np.linalg.norm using its axis param and also leveraging broadcasting would be -

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

Approach #2 : With einsum -

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

Approach #3 : Using (a-b)^2 = a^2 + b^2 - 2ab formula to leverage matrix-multiplication with np.dot and np.inner -

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

You can calculate the Frobenius Norm explicitly:

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

This is the default for 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])
Related