cosine similarity score python code example
Example 1: cosine similarity python numpy
from scipy import spatial
dataSetI = [3, 45, 7, 2]
dataSetII = [2, 54, 13, 15]
result = 1 - spatial.distance.cosine(dataSetI, dataSetII)
Example 2: python cosine similarity
from numpy import dot
from numpy.linalg import norm
def cosine_similarity(list_1, list_2):
cos_sim = dot(list_1, list_2) / (norm(list_1) * norm(list_2))
return cos_sim
your_list_1 = [1, 1, 1]
your_list_2 = [1, 1, 1]
cosine_similarity(your_list_1, your_list_2)
--> 1.0
your_list_1 = [1, 1, 1]
your_list_2 = [-1, -1, -1]
cosine_similarity(your_list_1, your_list_2)
--> -1.0