Similarity and Cosine Distance

Updated · 5 min read
mediumPython 3.13aiembeddingscosine-similaritynumpymath

Cosine similarity is a measure of how closely two vectors point in the same direction. It is used to compare embeddings: the smaller the angle between two vectors, the more similar their meanings. It ranges from 1 (same direction) through 0 (at right angles, unrelated) to -1 (opposite directions). Cosine distance is simply 1 minus the similarity, so a smaller distance means more similar.

Angles Between Arrows

Picture each vector as an arrow starting from the same point. Cosine similarity ignores how long the arrows are and looks only at the angle between them.

Only the angle matters, not the length

Syntax

PartDescription
np.dot(a, b)It is used to multiply matching numbers and add them up (the dot product)
np.linalg.norm(a)It is used to measure a vector's length
dot / (norm(a) * norm(b))It is used to compute cosine similarity
1 - similarityIt is used to compute cosine distance

Example 1: Arrows by Hand

Python
import numpy as np
 
def cosine(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
 
arrow = np.array([3, 4])
others = {"same direction": [6, 8], "close": [4, 3], "at right angles": [4, -3], "opposite": [-3, -4]}
for name, other in others.items():
    print(f"{name:16} {cosine(arrow, np.array(other)):5.2f}")
Output
same direction    1.00
close             0.96
at right angles   0.00
opposite         -1.00

Explanation: For [3, 4] and [4, 3], the dot product is 3 × 4 + 4 × 3 = 24, and each arrow has length 5, so the similarity is 24 ÷ 25 = 0.96. [6, 8] is twice as long as [3, 4] but points the same way, so it scores exactly 1: length doesn't matter, only direction.

Example 2: Sentences

The same formula works on 384-number sentence embeddings:

Python
import numpy as np
from sentence_transformers import SentenceTransformer
 
def cosine(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
 
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
question = model.encode("How much do chemistry experiments cost?")
for answer in ["The science lab fee is $45 a year and is due by September 30.",
               "Spring term starts on January 12 and ends on May 29."]:
    print(f"{cosine(question, model.encode(answer)):.2f}  {answer}")
Output
0.58  The science lab fee is $45 a year and is due by September 30.
-0.01  Spring term starts on January 12 and ends on May 29.

Explanation: The question shares no words with the lab fee answer, yet scores 0.58, because the model places "chemistry experiments" near "science lab". The term dates score about zero: unrelated. Real sentence scores rarely reach 1; what matters is which answers score higher than the others.

Common Mistakes

Expecting scores near 1 for good matches. Compare scores with each other; 0.58 can be the clear winner.

Using a fixed cut-off from another model. Each model's scores spread differently; pick thresholds by testing.

Confusing similarity and distance. Higher similarity means closer; higher distance means further apart.

Interview Corner

What does cosine similarity measure?

The angle between two vectors: 1 means the same direction, 0 means unrelated, -1 means opposite. It ignores vector length, which suits embeddings, where direction carries the meaning.

What is the relationship between cosine similarity and the dot product?

For vectors of length 1, they are equal. That's why search systems normalize embeddings and then use the faster dot product.

Practice

Exercise: rank three answers. Embed the question "What time does school start?" and three FAQ answers of your choice. Rank them by cosine similarity. Does the order match what a person would choose?

Check your understanding:

  1. What does a similarity of 0 mean?
  2. Why did [6, 8] score 1.00 with [3, 4]?
  3. How do you turn similarity into distance?

Quick check: cosine similarity

4 questions
1What does cosine similarity measure?
2What is the cosine similarity of two arrows at right angles?
3Why did [6, 8] and [3, 4] score 1.00?
4The lab fee answer scored 0.58. What does that tell you?

Key Takeaways

Quick reference

NeedCode
Similaritynp.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
Distance1 - similarity
Normalized vectorsa @ b

Was this tutorial helpful?

Lesson 91 of 186