Wednesday, October 2, 2019

Distance and Similarity between 2 number lists using cosine function


Sometimes we want to find the distance or the similarity between 2 number lists or vectors.
We can use the spatial.distance.cosine() function for that.
The cosine similarity is between 0 and 1.

from scipy import spatial

v1 = [1, 2, 3, 4, 5]
v2 = [1, 2, 3, 4, 5]
distance = spatial.distance.cosine(v1, v2)
similarity = 1 - distance;
print(distance)
print(similarity)
# output:0.0
# output:1.0
v3 = [2, 4, 6, 8, 10]
distance = spatial.distance.cosine(v1, v3)
similarity = 1 - distance;
print(distance)
print(similarity)
# output:0.0
# output:1.0
v4 = [15, 7, 6, 4, 1]
distance = spatial.distance.cosine(v1, v4)
similarity = 1 - distance;
print(distance)
print(similarity)
# output:0.4929466088203224
# output:0.5070533911796776

No comments:

Post a Comment