close

How to cosine similarity in python

Hello guys. How are you all? I hope you all fine. In this tutorial we will learn about how to cosine similarity in python. It calculate the cosine angle between the two vector lists. so without wasting time lets learn about of this.

How to cosine similarity in python

  1. cosine similarity in python

    to cosine similarity in python just Use numpy.By using numpy you can cosine similarity in python. Lets learn about of this by given below example:
    from numpy import dot from numpy.linalg import norm List1 = [8,54,6,9] List2 = [9,8,7,5] result = dot(List1, List2)/(norm(List1)*norm(List2)) print(result) Output : 0.717620473957404

  2. How to cosine similarity in python

    to cosine similarity in python just Use numpy.norm().By using numpy.norm() you can cosine similarity in python. Lets learn about of this by given below example:
    import numpy as np List1 =np.array([[8,54,6,9], [9,8,7,5]]) List2=np.array([ 42, 4, 3, 5]) result = List1.dot(List2)/ (np.linalg.norm(List1, axis=1) * np.linalg.norm(List2)) print(result) Output : [0.25946924 0.72347603]

  3. python cosine similarity

    to cosine similarity in python just Use numpy.norm().By using numpy.norm() you can cosine similarity in python. Lets learn about of this by given below example:
    import numpy as np List1 =np.array([[8,54,6,9], [9,8,7,5]]) List2=np.array([ 42, 4, 3, 5]) result = List1.dot(List2)/ (np.linalg.norm(List1, axis=1) * np.linalg.norm(List2)) print(result) Output : [0.25946924 0.72347603]

Method 1: Use numpy

Just Use numpy. Lets learn about of this by given below example:

from numpy import dot
from numpy.linalg import norm
List1 = [8,54,6,9]
List2 = [9,8,7,5]
result = dot(List1, List2)/(norm(List1)*norm(List2))
print(result)

Output :

0.717620473957404

Method 2: Use numpy.norm()

By using numpy.norm() you can cosine similarity. Lets learn about of this by given below example:

import numpy as np
List1 =np.array([[8,54,6,9],
       [9,8,7,5]])
List2=np.array([ 42, 4, 3, 5])
result = List1.dot(List2)/ (np.linalg.norm(List1, axis=1) * np.linalg.norm(List2))
print(result)

Output :

[0.25946924 0.72347603]

Conclusion

It’s all About this Tutorial. Hope all methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you?

Also, Read

Leave a Comment