JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Cosine Similarity in Python

Author:JIYIK Last Updated:2025/05/05 Views:

Cosine similarity measures the similarity between two lists of vectors by calculating the cosine angle between them. If you consider the cosine function, it has a value of 1 at 0 degrees and -1 at 180 degrees. This means that for two overlapping vectors, for two completely opposite vectors, the cosine value will be the maximum and minimum.

In this article, we will calculate the cosine similarity between two lists of equal size.


scipyCalculate the cosine similarity between two lists in Python using the module

The function from scipythe module spatial.cosine.distance()calculates distance instead of cosine similarity, but to implement this we can subtract the distance value from 1.

For example,

from scipy import spatial

List1 = [4, 47, 8, 3]
List2 = [3, 52, 12, 16]
result = 1 - spatial.distance.cosine(List1, List2)
print(result)

Output:

0.9720951480078084

NumPyCalculate the cosine similarity between two lists in Python using the module

numpy.dot()The function calculates the dot product of two vectors passed as parameters. numpy.norm()The function returns the vector norm.

We can use these functions and the correct formula to calculate cosine similarity.

For example,

from numpy import dot
from numpy.linalg import norm

List1 = [4, 47, 8, 3]
List2 = [3, 52, 12, 16]
result = dot(List1, List2) / (norm(List1) * norm(List2))
print(result)

Output:

0.9720951480078084

If we have multiple or a set of vectors and a query vector to calculate cosine similarity, we can use the following code.

import numpy as np

List1 = np.array([[4, 45, 8, 4], [2, 23, 6, 4]])

List2 = np.array([2, 54, 13, 15])

similarity_scores = List1.dot(List2) / (
    np.linalg.norm(List1, axis=1) * np.linalg.norm(List2)
)

print(similarity_scores)

Output:

[0.98143311 0.99398975]

sklearnCalculate the cosine similarity between two lists in Python using the module

In sklearnthe module, there is a cosine_similarity()built-in function called to calculate cosine similarity.

Please refer to the code below.

from sklearn.metrics.pairwise import cosine_similarity, cosine_distances

A = np.array([10, 3])
B = np.array([8, 7])
result = cosine_similarity(A.reshape(1, -1), B.reshape(1, -1))
print(result)

Output:

[[0.91005765]]

torchCalculate the cosine similarity between two lists in Python using the module

When we are dealing with an N-dimensional tensor with shape (m,n) , we can use the function torchfrom the module consine_similarity()to find the cosine similarity.

For example,

import torch
import torch.nn.functional as F

t1 = [3, 45, 6, 8]
a = torch.FloatTensor(t1)

t2 = [4, 54, 3, 7]
b = torch.FloatTensor(t2)
result = F.cosine_similarity(a, b, dim=0)

print(result)

Output:

tensor(0.9960)

Use torch.FloatTensor()the module to convert lists into tensors.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Read the first line of a file in Python

Publish Date:2025/05/05 Views:192 Category:Python

In Python, we have built-in functions to handle different file operations. A text file contains a sequence of strings where each line \n is terminated by a newline character. In this tutorial, we will learn how to read the first line of a t

Exponential and Logarithmic Curve Fitting in Python

Publish Date:2025/05/05 Views:79 Category:Python

Curve fitting is a very effective tool that is widely used in analysis. Curve fitting method studies the relationship between independent variables (also called predictor variables) and dependent variable (called response variable). This me

Calculating Slope in Python

Publish Date:2025/05/05 Views:60 Category:Python

In mathematics, the slope of a given line is the value at which its steepness is calculated. It also helps to characterize the direction of a given line. The extent of a line can also be calculated using Python programming language. This ar

How to Randomly Select Elements from a List in Python

Publish Date:2025/05/05 Views:68 Category:Python

This tutorial showed you how to randomly select an element from a list in Python. There are multiple simple ways to achieve this goal, all of which involve importing Python modules. This tutorial will cover solutions that require the random

How to Replace an Element in a Python List

Publish Date:2025/05/05 Views:109 Category:Python

We can replace elements in Python lists in many ways. We can use Python list element indexing, for loops, map functions, and list comprehensions. This article will discuss the above methods to find and replace elements in Python lists. Sear

Convert Tensor to NumPy array in Python

Publish Date:2025/05/03 Views:86 Category:Python

This tutorial will show you how to convert a Tensor to a NumPy array in Python. Use the function in Python Tensor.numpy() to convert a tensor to a NumPy array Eager Execution of TensorFlow library can be used to convert tensor to NumPy arra

Saving NumPy arrays as images in Python

Publish Date:2025/05/03 Views:194 Category:Python

In Python, numpy module is used to manipulate arrays. There are many modules available in Python that allow us to read and store images. An image can be thought of as an array of different pixels stored at specific locations with correspond

Transposing a 1D array in NumPy

Publish Date:2025/05/03 Views:98 Category:Python

Arrays and matrices form the core of this Python library. The transpose of these arrays and matrices plays a vital role in certain topics such as machine learning. In NumPy, it is easy to calculate the transpose of an array or a matrix. Tra

Find the first index of an element in a NumPy array

Publish Date:2025/05/03 Views:59 Category:Python

In this tutorial, we will discuss how to find the first index of an element in a numpy array. Use where() the function to find the first index of an element in a NumPy array The function in the numpy module where() is used to return an arra

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial