Output: ] Use the torch Module to Calculate the Cosine Similarity Between Two Lists in Python from import cosine_similarity,cosine_distances A=np.array() B=np.array() result=cosine_similarity(A.reshape(1,-1),B.reshape(1,-1)) print(result) In the sklearn module, there is an in-built function called cosine_similarity() to calculate the cosine similarity. Output: Use the sklearn Module to Calculate the Cosine Similarity Between Two Lists in Python import numpy as np List1 =np.array(, ]) List2=np.array() similarity_scores = List1.dot(List2)/ (np.linalg.norm(List1, axis=1) * np.linalg.norm(List2)) print(similarity_scores) If there are multiple or a list of vectors and a query vector to calculate cosine similarities, we can use the following code. We can use these functions with the correct formula to calculate the cosine similarity.įor example, from numpy import dot from numpy.linalg import norm List1 = List2 = result = dot(List1, List2)/(norm(List1)*norm(List2)) print(result) The numpy.norm() function returns the vector norm. Output: 0.9720951480078084 Use the NumPy Module to Calculate the Cosine Similarity Between Two Lists in PythonĬalculates the dot product of the two vectors passed as parameters. The () function from the scipy module calculates the distance instead of the cosine similarity, but to achieve that, we can subtract the value of the distance from 1.įor example, from scipy import spatial List1 = List2 = result = 1 - (List1, List2) print(result) Use the scipy Module to Calculate the Cosine Similarity Between Two Lists in Python In this article, we will calculate the cosine similarity between two lists of equal sizes. This means for two overlapping vectors, the value of cosine will be maximum and minimum for two precisely opposite vectors. If you consider the cosine function, its value at 0 degrees is 1 and -1 at 180 degrees. The cosine similarity measures the similarity between vector lists by calculating the cosine angle between the two vector lists.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |