Skip to main content

How to Measure How Similar Two Sentences Are with Hugging Face Embeddings

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

"A man is playing a guitar" and "Someone is making music" share only the word "is", yet they mean nearly the same thing. Comparing their embeddings, the lists of numbers a model gives each sentence, captures that: the closer the meanings, the closer the numbers. This guide scores one sentence against three others with a Hugging Face feature-extraction pipeline and cosine similarity, with Transformers 5.26.0 on Python 3.14.

Syntax​

Syntax
from torch.nn.functional import cosine_similarity

similarity = cosine_similarity(<embedding_a>, <embedding_b>)
PartWhat it means
<embedding_a>, <embedding_b>The two sentences' embeddings, each a tensor of shape [1, vector size] from the same model
cosine_similarity(…)Compares the directions of the two vectors: close to 1 when they point the same way, around 0 when they're unrelated, below 0 when they point apart
similarityA tensor with one number; similarity.item() turns it into a Python float

The embeddings come from a feature-extraction pipeline, averaged over the tokens, as How to Turn a Sentence into an Embedding with a Hugging Face Feature-Extraction Pipeline explains. How to Measure the Cosine Similarity of Two Tensors in PyTorch shows what the function computes, with two-number vectors.

The Example​

One sentence, "A man is playing a guitar.", compared with three others: one close in meaning, one about a different everyday activity, one about something else entirely. The model is sentence-transformers/all-MiniLM-L6-v2, a small model trained so that sentences with similar meanings get similar embeddings. It's Apache-2.0 licensed.

Prerequisites​

  • uv. This guide uses uv 0.13.10. The project uses Python 3.14, which uv downloads if needed.
  • About 91 MB for the model, downloaded on the first run.

Step 1: Create the Project​

Terminal
uv init --python 3.14 similarity-demo
cd similarity-demo
uv add transformers torch

That's a project with Transformers 5.26.0 and PyTorch 2.15.0.

Step 2: Write the Script​

similarity.py
from torch.nn.functional import cosine_similarity
from transformers import pipeline

extractor = pipeline(
"feature-extraction",
model="sentence-transformers/all-MiniLM-L6-v2",
revision="1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
)


def embed(text):
return extractor(text, return_tensors=True).mean(dim=1)


anchor = embed("A man is playing a guitar.")
for other in [
"Someone is making music.",
"A woman is slicing an onion.",
"The stock market fell today.",
]:
similarity = cosine_similarity(anchor, embed(other))
print(f"{similarity.item():.3f} {other}")

The similarity.py script in a macOS-style code window: a feature-extraction pipeline with the all-MiniLM-L6-v2 model, an embed function that averages the token vectors, the embedding of A man is playing a guitar, and a loop that prints its cosine similarity with three other sentences.

embed turns a text into one vector of 384 numbers. The first sentence is embedded once, as anchor; the loop embeds each other sentence and prints its similarity with the anchor, rounded to three decimals.

Step 3: Run It​

Terminal
uv run python similarity.py
Output
Loading weights: 100%|██████████████████████████████████████████| 103/103 [00:00<00:00, 9415.95it/s]
0.579 Someone is making music.
0.089 A woman is slicing an onion.
-0.050 The stock market fell today.

The terminal after uv run python similarity.py: 0.579 for Someone is making music, 0.089 for A woman is slicing an onion and -0.050 for The stock market fell today.

The scores follow the meanings:

  • 0.579 for "Someone is making music.", the same scene in other words.
  • 0.089 for "A woman is slicing an onion.", a person doing something else.
  • -0.050 for "The stock market fell today.", nothing in common at all.

The numbers mean little on their own: what counts is their order. To find the closest sentence, compare against many and take the highest. On the first run, download progress bars for the model's files come before these lines. The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Comparing embeddings from two different modelsThe numbers mean different things, so the score is meaninglessEmbed every sentence with the same model
Comparing the token tensors directlySentences of different lengths give different shapes, such as [1, 9, 384] and [1, 7, 384] here, which can't be compared one-to-oneAverage each into [1, 384] first
Using a model not trained for embeddingsEvery pair can score high, so the scores can't tell sentences apartUse a model made for sentence embeddings
Expecting a fixed threshold to mean "same meaning"Scores vary by model and by kind of textChoose a threshold from examples of your own texts

FAQ​

Why cosine similarity and not plain distance?​

Cosine similarity compares directions and ignores length, which suits embeddings: the meaning is in which way the vector points. It's also what this model was trained with: its card says that during training "we compute the cosine similarity from each possible sentence pairs from the batch."

How do I compare many sentences at once?​

Embed them all, then compare: cosine_similarity works on a whole batch of vectors at once, row by row. For large collections, a vector database does it for you.

Is this what semantic search does?​

Yes, at its core: embed the documents once, embed each query, and return the documents with the highest similarity to it.

Conclusion​

Embedding each sentence with all-MiniLM-L6-v2 and comparing them with cosine_similarity scored "Someone is making music." at 0.579 against "A man is playing a guitar.", far above the onion (0.089) and the stock market (-0.050): the order of the scores matches the order of the meanings.

Additional Resources​