Similarity and Cosine Distance
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.
Syntax
| Part | Description |
|---|---|
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 - similarity | It is used to compute cosine distance |
Example 1: Arrows by Hand
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}")same direction 1.00
close 0.96
at right angles 0.00
opposite -1.00Explanation: 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:
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}")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:
- What does a similarity of 0 mean?
- Why did
[6, 8]score 1.00 with[3, 4]? - How do you turn similarity into distance?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Similarity | np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) |
| Distance | 1 - similarity |
| Normalized vectors | a @ b |
Was this tutorial helpful?