1from scipy import spatial
2
3dataSetI = [3, 45, 7, 2]
4dataSetII = [2, 54, 13, 15]
5result = 1 - spatial.distance.cosine(dataSetI, dataSetII)
1# Example function using numpy:
2from numpy import dot
3from numpy.linalg import norm
4
5def cosine_similarity(list_1, list_2):
6 cos_sim = dot(list_1, list_2) / (norm(list_1) * norm(list_2))
7 return cos_sim
8# Note, the dot product is only defined for lists of equal length. You
9# can use your_list.extend() to add elements to the shorter list
10
11# Example usage with identical lists/vectors:
12your_list_1 = [1, 1, 1]
13your_list_2 = [1, 1, 1]
14cosine_similarity(your_list_1, your_list_2)
15--> 1.0 # 1 = maximally similar lists/vectors
16
17# Example usage with opposite lists/vectors:
18your_list_1 = [1, 1, 1]
19your_list_2 = [-1, -1, -1]
20cosine_similarity(your_list_1, your_list_2)
21--> -1.0 # -1 = maximally dissimilar lists/vectors
1from scipy.spatial import distance
2
3distance.cosine([1, 0, 0], [0, 1, 0])
4>>> 1.0
5
6distance.cosine([100, 0, 0], [0, 1, 0])
7>>> 1.0
8
9distance.cosine([1, 1, 0], [0, 1, 0])
10>>> 0.29289321881345254