Answers for "how to compute cosine similarity"

6

python cosine similarity

# Example function using numpy:
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
# Note, the dot product is only defined for lists of equal length. You
#	can use your_list.extend() to add elements to the shorter list

# Example usage with identical lists/vectors:
your_list_1 = [1, 1, 1]
your_list_2 = [1, 1, 1]
cosine_similarity(your_list_1, your_list_2)
--> 1.0 # 1 = maximally similar lists/vectors

# Example usage with opposite lists/vectors:
your_list_1 = [1, 1, 1]
your_list_2 = [-1, -1, -1]
cosine_similarity(your_list_1, your_list_2)
--> -1.0 # -1 = maximally dissimilar lists/vectors
Posted by: Guest on November-11-2020
2

cosine similarity python

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
Posted by: Guest on February-18-2021

Python Answers by Framework

Browse Popular Code Answers by Language