"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

March 09, 2023

Recommendation - Distance Measures

 




Ref - Link
#cosine similarity example python
#importing libraries
from sklearn.metrics.pairwise import cosine_similarity
from scipy import spatial
#creating two vectors
vector_a = [1,1,0,0]
vector_b = [1,1,1,0]
vector_c = [1,0,1,0]
#calculating cosine similarity
cos_sim = cosine_similarity([vector_a], [vector_b])[0][0]
#printing cosine similarity and cosine distance
print('Cosine similarity: A - B ', cos_sim)
#calculating cosine similarity
cos_sim = cosine_similarity([vector_a], [vector_c])[0][0]
#printing cosine similarity and cosine distance
print('Cosine similarity: A - C ', cos_sim)
#Euclidean similarity example
#importing the necessary libraries
from scipy.spatial import distance
#calculating the euclidean distance
euclidean_distance = distance.euclidean(vector_a, vector_b)
#calculating the euclidean similarity
euclidean_similarity = 1/(1 + euclidean_distance)
#printing the euclidean similarity
print(euclidean_similarity)
#calculating the euclidean distance
euclidean_distance = distance.euclidean(vector_a, vector_c)
#calculating the euclidean similarity
euclidean_similarity = 1/(1 + euclidean_distance)
#printing the euclidean similarity
print(euclidean_similarity)
#manhattan similarity example
# Calculate Manhattan similarity between two vectors
import numpy as np
def manhattan_similarity(vec1, vec2):
return np.sum(np.abs(vec1 - vec2))
print(manhattan_similarity(np.array(vector_a), np.array(vector_b)))
print(manhattan_similarity(np.array(vector_a), np.array(vector_c)))

Keep Exploring!!!

No comments: