python-scipyHow can I calculate cosine similarity using Python and SciPy?
Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them. It is defined as the dot product of two vectors divided by the product of their magnitudes.
Using SciPy, cosine similarity can be calculated with the following code:
from scipy import spatial
# Define the vectors
a = [1, 2, 3]
b = [4, 5, 6]
# Calculate the cosine similarity
result = 1 - spatial.distance.cosine(a, b)
print(result)
Output example
0.974631846197076
The code above consists of the following parts:
- Import the
spatialmodule from the SciPy library. - Define the two vectors.
- Calculate the cosine similarity with the
distance.cosine()method, passing in the two vectors as arguments. - Print the result.
Helpful links
More of Python Scipy
- How can I use Python and SciPy to find the zeros of a function?
- How can I check if a certain version of Python is compatible with SciPy?
- How do I use Scipy zeros in Python?
- How do I create a 2D array of zeros using Python and NumPy?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How can I use Python Numpy to select elements from an array based on multiple conditions?
- How do I use Python Scipy to perform a Z test?
- How can I use Python and Numpy to zip files?
- How can I use Python and Numpy to parse XML data?
- How do I upgrade my Python Scipy package?
See more codes...