How to compute the Euclidean distance between two arrays in numpy
The numpy library in Python allows us to compute Euclidean distance between two arrays.
Euclidean distance
Euclidean distance is defined in mathematics as the magnitude or length of the line segment between two points.
Formula
Method 1
In this method, we first initialize two numpy arrays. Then, we use linalg.norm() of numpy to compute the Euclidean distance directly.
The details of the function can be found here.
#importing numpyimport numpy as np#initializing two arraysarray1 = np.array([1,2,3,4,5])array2 = np.array([7,6,5,4,3])#computing the Euclidan distancetemp = array1 - array2distance = np.linalg.norm(temp)print("Euclidean Distance: ", distance)
Method 2
In this method, we first initialize two numpy arrays. Then, we take the difference of the two arrays, compute the dot product of the result, and transpose of the result. Then we take the square root of the answer. This is another way to implement Euclidean distance.
#importing numpyimport numpy as np#initializing two arraysarray1 = np.array([1,2,3,4,5])array2 = np.array([7,6,5,4,3])#computing the Euclidan distancetemp = array1 - array2distance = np.sqrt(np.dot(temp.T, temp))print("Euclidean Distance: ", distance)
Method 3
In this method, we first initialize two numpy arrays. Then, we compute the difference of these arrays and take their square. We take the sum of the squared elements, and after that, we take the square root in the end. This is another way to implement Euclidean distance.
#importing numpyimport numpy as np#initializing two arraysarray1 = np.array([1,2,3,4,5])array2 = np.array([7,6,5,4,3])#computing the Euclidan distancetemp = array1 - array2distance = np.sqrt(np.sum(np.square(temp)))print("Euclidean Distance: ", distance)