Calculating the Minkowski distance using SciPy


The Minkowski distance, a generalized form of Euclidean and Manhattan distance, is the distance between two points. It is mostly used for distance similarity of vectors. Below is the generalized formula to calculate Minkowski distance in n-dimensional space −

$$\mathrm{D= \big[\sum_{i=1}^{n}|r_i-s_i|^p\big]^{1/p}}$$

Here,

si and ri are data points.

n denotes the n-space.

p represents the order of the norm

SciPy provides us with a function named minkowski that returns the Minkowski Distance between two points. Let’s see how we can calculate the Minkowski distance between two points using SciPy library −

Example

# Importing the SciPy library
from scipy.spatial import distance
# Defining the points
A = (1, 2, 3, 4, 5, 6)
B = (7, 8, 9, 10, 11, 12)
A, B
# Computing the Minkowski distance
minkowski_distance = distance.minkowski(A, B, p=3)
print('Minkowski Distance b/w', A, 'and', B, 'is: ', minkowski_distance)

Output

((1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12))

Minkowski Distance b/w (1, 2, 3, 4, 5, 6) and (7, 8, 9, 10, 11, 12) is: 10
.902723556992836

We have calculated the Minkowski distance with order(p) = 3. But when the order is 2, it will represent the Euclidean distance whereas when the order is 1, it will represent the Manhattan distance. Let’s understand it with the below given example −

Example

# Importing the SciPy library
from scipy.spatial import distance
# Defining the points
A = (1, 2, 3, 4, 5, 6)
B = (7, 8, 9, 10, 11, 12)
A, B

# minkowski and manhattan distance
minkowski_distance_with_order1 = distance.minkowski(A, B, p=1)
print('Minkowski Distance of order(P)1:',minkowski_distance_with_order1,'
Manhattan Distance: ',manhattan_distance) # minkowski and euclidean distance minkowski_distance_with_order2 = distance.minkowski(A, B, p=2) print('Minkowski Distance of order(P)2:',minkowski_distance_order_2, '
Euclidean Distance: ',euclidean_distance)

Output

((1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12))
Minkowski Distance of order(P)1: 36.0
Manhattan Distance: 36

Minkowski Distance of order(P)2: 14.696938456699069
Euclidean Distance: 14.696938456699069

Updated on: 14-Dec-2021

444 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements