The Hamming distance between two vectors is just the sum of corresponding components that fluctuate between the vectors.
For instance, assume we now have please see two vectors:
x = [1, 2, 3, 4] y = [1, 2, 5, 7]
The Hamming distance between the 2 vectors could be 2, since that is the whole collection of corresponding components that experience other values.
To calculate the Hamming distance between two arrays in Python we will be able to significance the hamming() serve as from the scipy.spatial.distance library, which makes use of please see syntax:
scipy.spatial.distance.hamming(array1, array2)
Observe that this serve as returns theĀ proportion of corresponding components that fluctuate between the 2 arrays.
Thus, to procure the Hamming distance we will be able to merely multiply through the range of one of the vital arrays:
scipy.spatial.distance.hamming(array1, array2) * len(array1)
This instructional supplies a number of examples of the way to significance this serve as in follow.
Instance 1: Hamming Distance Between Binary Arrays
Please see code displays the way to calculate the Hamming distance between two arrays that every include handiest two imaginable values:
from scipy.spatial.distance import hamming #outline arrays x = [0, 1, 1, 1, 0, 1] y = [0, 0, 1, 1, 0, 0] #calculate Hamming distance between the 2 arrays hamming(x, y) * len(x) 2.0
The Hamming distance between the 2 arrays is 2.
Instance 2: Hamming Distance Between Numerical Arrays
Please see code displays the way to calculate the Hamming distance between two arrays that every include a number of numerical values:
from scipy.spatial.distance import hamming #outline arrays x = [7, 12, 14, 19, 22] y = [7, 12, 16, 26, 27] #calculate Hamming distance between the 2 arrays hamming(x, y) * len(x) 3.0
The Hamming distance between the 2 arrays is 3.
Instance 3: Hamming Distance Between Fibre Arrays
Please see code displays the way to calculate the Hamming distance between two arrays that every include a number of persona values:
from scipy.spatial.distance import hamming #outline arrays x = ['a', 'b', 'c', 'd'] y = ['a', 'b', 'c', 'r'] #calculate Hamming distance between the 2 arrays hamming(x, y) * len(x) 1.0
The Hamming distance between the 2 arrays is 1.
Spare Assets
The right way to Calculate Euclidean Distance in Python
The right way to Calculate Mahalanobis Distance in Python
The right way to Calculate Jaccard Similarity in Python