Python Using numpy.linalg.norm() to Find Distance Matrix --> How Calculated?

Viewed 999

I have a vector below called vector:

[0.465344 0.519904]

I also have the following matrix called matrix_b:

[[-0.701366  0.261183]
 [-0.295642 -1.41441 ]]

I use the following code to calculate the distance matrix.

dist_matrix = np.linalg.norm(vector - matrix_b, ord=2, axis=1)

I then print out dist_matrix to see the output which is:

print (dist_matrix )

[1.19505179 2.07862222]

I don't understand how mathematically the norm distance (i.e. dist_matrix) was calculated from the inputs. Can someone enlighten me please?

1 Answers
>>> vector = np.array([0.465344, 0.519904])
>>> matrix_b = np.array([[-0.701366,  0.261183],[-0.295642, -1.41441 ]])
>>> vector - matrix_b
array([[1.16671 , 0.258721],
       [0.760986, 1.934314]])

For subtraction, vector is broadcasted to the shape of matrix_b. The elements of the result are thus

vector[0] - matrix_b[0,0]    vector[1] - matrix_b[0,1]
vector[0] - matrix_b[1,0]    vector[1] - matrix_b[1,1]

Then,

>>> dist_matrix = np.linalg.norm(vector - matrix_b, ord=2, axis=1)
>>> dist_matrix
array([1.19505179, 2.07862222])

Referring to the documentation of numpy.linalg.norm, you can see that the axis argument specifies the axis for computing vector norms. So here, axis=1 means that the vector norm would be computed per row in the matrix.

Then, ord=2 for vector norms means that for a vector x, the result is sum(abs(x)**2)**(1./2) (which is also the formula for the Euclidean distance).

So, we have, mathematically:

dist_matrix[0] == (abs(vector[0] - matrix_b[0,0])**2 + abs(vector[1] - matrix_b[0,1])**2)**(1./2)
dist_matrix[1] == (abs(vector[0] - matrix_b[1,0])**2 + abs(vector[1] - matrix_b[1,1])**2)**(1./2)
Related