Skip to main content

How to Measure the Cosine Similarity of Two Tensors in PyTorch

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Cosine similarity measures how closely two vectors point in the same direction, whatever their length: 1 when they point the same way, 0 when they're at a right angle, and -1 when they point in opposite directions. It's how embeddings, the vectors models use for meaning, are compared. PyTorch computes it with cosine_similarity. This guide measures it on three tiny vectors in PyTorch 2.15.0.

Syntax​

Syntax
from torch.nn.functional import cosine_similarity

similarity = cosine_similarity(<x1>, <x2>, dim=1)
PartWhat it means
<x1>, <x2>The two tensors to compare, of the same shape or shapes that broadcast to one
dimOptional. The dimension that holds each vector's numbers; 1 if you leave it out. The result has one number for each vector along the other dimensions

PyTorch's reference says it "Returns cosine similarity between x1 and x2, computed along dim." It divides the dot product of the two vectors by the product of their lengths.

The Example​

Three vectors of two numbers each, written as one-row tables of shape [1, 2]: a points right, b points right and up at 45 degrees, c points left. The script compares a with itself, with b and with c, then compares two flat vectors of shape [2] with dim=0.

Prerequisites​

  • A uv project with PyTorch and NumPy. uv add torch numpy adds both; without NumPy, PyTorch 2.15.0 prints a warning each time it starts. This guide uses PyTorch 2.15.0 and NumPy 2.5.5 on Python 3.15.2, with uv 0.13.10, on an Apple M1 Pro.

Step 1: Write the Script​

cosine.py
import torch
from torch.nn.functional import cosine_similarity

a = torch.tensor([[1.0, 0.0]])
b = torch.tensor([[1.0, 1.0]])
c = torch.tensor([[-1.0, 0.0]])

print(cosine_similarity(a, a))
print(cosine_similarity(a, b))
print(cosine_similarity(a, c))
print(cosine_similarity(torch.tensor([1.0, 0.0]), torch.tensor([1.0, 1.0]), dim=0))

The cosine.py script in a macOS-style code window: three one-row tensors a, b and c, prints of the cosine similarity of a with a, a with b and a with c, and a last print comparing two flat tensors with dim=0.

Step 2: Run It​

Terminal
uv run python cosine.py
Output
tensor([1.])
tensor([0.7071])
tensor([-1.])
tensor(0.7071)

The terminal after uv run python cosine.py: tensor([1.]), tensor([0.7071]), tensor([-1.]) and tensor(0.7071).

  • a with itself: 1, the same direction.
  • a with b: 0.7071, the cosine of 45 degrees. The vectors point partly the same way.
  • a with c: -1, opposite directions.
  • The flat vectors with dim=0: 0.7071 again, as a single number, since there was only one pair to compare.

The one-row inputs gave a result with one number per row, shape [1]: the function compares the vectors row by row along dim=1 and removes that dimension. The command works unchanged in PowerShell.

Compare Many Pairs at Once​

With tables of several rows, cosine_similarity compares row 1 with row 1, row 2 with row 2, and so on, and returns one number per row: two tables of 100 random vectors of shape [100, 384] gave a result of shape [100]. To compare one vector against many, make it a single row and PyTorch's broadcasting compares it with every row of the other tensor: a from the script against a table holding a, b and c printed tensor([ 1.0000, 0.7071, -1.0000]).

Common Mistakes​

MistakeWhat happensDo this instead
Comparing two flat vectors without dim=0IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1): see the fixPass dim=0, or make each vector a row of shape [1, n]
Using tensors of whole numbers, such as torch.tensor([[1, 0]])RuntimeError: expected common dtype to be floating point, yet common dtype is Long: see the fixWrite the numbers with .0, or convert with .float()
Reading 0.7071 as "70% the same"It's the cosine of an angle, not a percentageCompare scores with each other: higher is more similar

FAQ​

Is cosine similarity the same as distance?​

No. Distance depends on the vectors' lengths, cosine similarity only on their directions. For [1, 0] and [5, 0], cosine_similarity printed tensor([1.]) while torch.dist, the distance between them, printed tensor(4.).

What does a similarity of 0 mean?​

The vectors are at a right angle: neither points towards nor away from the other. For embeddings, it usually means unrelated.

Conclusion​

cosine_similarity gave 1 for a vector with itself, 0.7071 for vectors 45 degrees apart and -1 for opposite vectors, row by row along dim=1, and dim=0 compared two flat vectors directly.

Additional Resources​