LESSON 30 Β· EMBEDDINGS

Cosine Similarity

Learn how cosine similarity compares embedding vectors by looking at the angle between them. You will understand the formula, dot product, vector magnitude, Python implementation, ranking, edge cases, and how cosine similarity supports semantic search and RAG.

30 min readβ€’Beginnerβ€’Generative AI

By the end of this lesson, you will be able to:

  • Explain cosine similarity in simple terms.
  • Understand the dot-product and magnitude parts of the formula.
  • Explain why the angle between vectors matters.
  • Calculate cosine similarity with Python and NumPy.
  • Use cosine similarity to rank embedding candidates.
  • Handle zero vectors and interpret scores carefully.
  • Connect cosine similarity to semantic search and RAG.
1

What Is Cosine Similarity?

Cosine similarity is a metric used to compare two vectors. Instead of primarily asking how far apart the vectors are, it asks how closely their directions align.

VECTOR APoints in one direction
COMPARE THE ANGLE
VECTOR BPoints in another direction
Key idea:For embeddings, cosine similarity is useful because related meanings often produce vectors with similar directions in the embedding space.
2

The Core Formula

For two vectors A and B, cosine similarity divides their dot product by the product of their magnitudes.

cosine similarity(A, B) = (A Β· B) / (||A|| Γ— ||B||)Dot product Γ· product of vector magnitudes
A Β· BMeasures how the vector components interact.
||A||The magnitude or length of vector A.
||B||The magnitude or length of vector B.
Shortcut:Think β€œdirection first.” Cosine similarity normalizes away vector length and focuses on angular alignment.
3

Why the Angle Matters

Imagine vectors as arrows starting at the same origin. If two arrows point in nearly the same direction, the angle between them is small and cosine similarity is high.

A
B
ΞΈ
Small angleVectors point in similar directions β†’ high cosine similarity.
90Β° angleVectors are perpendicular β†’ cosine similarity is around zero.
Opposite directionVectors point against each other β†’ cosine similarity approaches -1.
4

Understanding the Dot Product

The dot product is one of the building blocks of cosine similarity. For two same-length vectors, multiply corresponding components and add the results.

A[a₁, aβ‚‚, a₃]
Γ—
B[b₁, bβ‚‚, b₃]
β†’
A Β· Ba₁b₁ + aβ‚‚bβ‚‚ + a₃b₃
Important:The dot product alone is not cosine similarity. The magnitudes in the denominator normalize the result.
5

Understanding Vector Magnitude

Magnitude is the length of a vector. For a vector with components x₁, xβ‚‚, …, xβ‚™, its magnitude is the square root of the sum of squared components.

||A|| = √(a₁² + aβ‚‚Β² + … + aβ‚™Β²)Magnitude measures vector length.
LONGER VECTOR

More magnitude

Its length is larger, but cosine similarity can still be high if its direction matches another vector.

VS
NORMALIZED DIRECTION

Same direction

Scaling a vector changes its length without changing its direction.

6

Cosine Similarity vs Euclidean Distance

Both metrics compare vectors, but they answer different questions. Cosine similarity focuses on direction; Euclidean distance measures straight-line distance between points.

COSINE SIMILARITY

How aligned?

Useful when the orientation of embedding vectors matters more than their raw length.

Direction / angle
VS
EUCLIDEAN DISTANCE

How far apart?

Measures geometric distance directly and can be sensitive to vector magnitude.

Distance / length
Do not assume one metric always wins:Use the metric that matches the embedding model, index, and retrieval objective. Evaluate it on your real data.
7

Python: Calculate Cosine Similarity

Here is the basic NumPy implementation. It makes every part of the formula visible.

</> PythonBasic cosine similarity
import numpy as np

def cosine_similarity(a, b):
    dot_product = np.dot(a, b)
    magnitude_a = np.linalg.norm(a)
    magnitude_b = np.linalg.norm(b)

    return dot_product / (magnitude_a * magnitude_b)

a = np.array([1, 2, 3])
b = np.array([2, 4, 6])

score = cosine_similarity(a, b)
print(f"Cosine similarity: {score:.3f}")
Expected idea:Because the second vector points in exactly the same direction as the first, the score is 1.000.
8

Python: Compare Different Directions

Changing the direction changes the cosine score, even when the vectors have similar dimensions.

</> PythonCompare vector directions
import numpy as np

def cosine_similarity(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))

vectors = {
    "same direction": (np.array([1, 2]), np.array([2, 4])),
    "perpendicular": (np.array([1, 0]), np.array([0, 1])),
    "opposite": (np.array([1, 2]), np.array([-1, -2])),
}

for label, (a, b) in vectors.items():
    score = cosine_similarity(a, b)
    print(f"{label}: {score:.3f}")
Same directionβ‰ˆ 1
Perpendicularβ‰ˆ 0
Opposite directionβ‰ˆ -1
9

What Do Cosine Scores Mean?

For the standard cosine similarity formula, the mathematical range is -1 to 1. In many embedding applications, scores may cluster in a narrower positive range, so the raw number should not be interpreted with a universal rule.

-101
-1Opposite direction
0Perpendicular direction
1Same direction
For real embeddings:Do not say β€œ0.75 always means relevant.” Score distributions depend on the model, data, preprocessing, and task.
10

Ranking Search Results with Cosine Similarity

Semantic search commonly calculates a query-to-document similarity score and sorts candidates from highest to lowest.

</> PythonRank candidates
import numpy as np

def cosine_similarity(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))

query = np.array([0.8, 0.2, 0.1])
documents = {
    "password reset": np.array([0.78, 0.24, 0.12]),
    "account login": np.array([0.70, 0.30, 0.15]),
    "weather forecast": np.array([0.05, 0.90, 0.20]),
}

results = []
for name, vector in documents.items():
    score = cosine_similarity(query, vector)
    results.append((name, score))

results.sort(key=lambda item: item[1], reverse=True)

for name, score in results:
    print(f"{name}: {score:.3f}")

The highest-scoring candidate becomes the first retrieval result. A production system may then apply metadata filters, reranking, business rules, or a relevance threshold.

11

Why Normalization Matters

Cosine similarity divides by both vector magnitudes, which makes the comparison less dependent on raw vector length. This is one reason it is useful for high-dimensional representations.

Raw vectorDirection + magnitude
β†’
MagnitudeCalculate length
β†’
NormalizeAccount for scale
β†’
Compare angleCosine similarity
Useful intuition:If one vector is simply a positive scaled version of another, their directions are identical and their cosine similarity is 1.
12

Zero Vectors: An Important Edge Case

A zero vector has no direction. Because its magnitude is zero, the cosine formula would divide by zero. Your implementation should therefore handle zero vectors explicitly.

Zero vector[0, 0, 0]
Magnitude0
ProblemDivision by zero
</> PythonHandle zero vectors
import numpy as np

def cosine_similarity(a, b):
    denominator = np.linalg.norm(a) * np.linalg.norm(b)

    if denominator == 0:
        return 0.0

    return np.dot(a, b) / denominator

print(cosine_similarity(
    np.array([0.0, 0.0]),
    np.array([1.0, 2.0])
))
13

Cosine Similarity in Semantic Search

A typical semantic search pipeline creates a vector for the user's query, compares it with stored document vectors, and retrieves the strongest matches.

01User queryβ€œHow do I reset my password?”
β†’
02Query embeddingText β†’ vector
β†’
03Cosine similarityCompare directions
β†’
04RankHighest scores first
Connection to embeddings:Embeddings provide the vectors. Cosine similarity provides a way to compare those vectors.
14

Cosine Similarity in RAG

In RAG, cosine similarity can help identify which document chunks are closest to the query in embedding space before those chunks are passed to the language model.

DocumentsKnowledge base
β†’
ChunkingSplit content
β†’
EmbeddingsCreate vectors
β†’
CosineCompare vectors
β†’
Top chunksContext for LLM

Retrieval quality still depends on chunking, embedding model, metadata, indexing, query rewriting, reranking, and evaluation. Cosine similarity is one component of the retrieval process.

15

Common Mistakes

Confusing dot product with cosine similarity

The denominator is what normalizes the dot product by vector lengths.

Using a threshold without evaluation

A score that works for one dataset may fail on another.

Ignoring zero vectors

Always protect the denominator in custom implementations.

Comparing incompatible embeddings

Vectors need to belong to a compatible embedding space.

Assuming high score means factual correctness

Similarity ranks content; it does not verify facts.

Forgetting exact-match signals

Hybrid retrieval can be useful when names, IDs, codes, or exact terms matter.

16

When Should You Use Cosine Similarity?

01Semantic Search

Rank documents by embedding-direction similarity.

02FAQ Matching

Compare a user question with known questions.

03RAG Retrieval

Find candidate chunks for an LLM context window.

04Duplicate Detection

Find records with similar semantic representations.

05Recommendations

Compare user and content representations.

06Clustering Support

Use vector similarity as one signal when grouping content.

HANDS-ON PRACTICE

Build a Cosine Similarity Ranker

Create a small Python experiment that ranks FAQ embeddings against a user query.

  1. Create five sample FAQ vectors.
  2. Create one query vector.
  3. Implement cosine similarity from scratch with NumPy.
  4. Calculate the score for every FAQ.
  5. Sort from highest to lowest.
  6. Add a zero-vector test.
  7. Try different vectors and observe how the angle changes the score.
Challenge: Add a labeled set of real queries and measure whether the highest cosine-similarity result is actually relevant. Compare the result with Euclidean distance.
QUICK QUIZ

Test Your Understanding

1. What does cosine similarity primarily compare?

The direction or angle between two vectors.

2. What are the main parts of the cosine formula?

The dot product in the numerator and the product of the two vector magnitudes in the denominator.

3. What happens when two non-zero vectors point in exactly the same direction?

Their cosine similarity is 1.

4. What is the mathematical range of cosine similarity?

From -1 to 1.

5. Does a high cosine score guarantee a correct answer?

No. It is a similarity or ranking signal, not proof of correctness.

30-Second Recap

1Cosine similarity compares vector directions.
2It uses dot product and vector magnitudes.
3Same direction gives a score of 1.
4Zero vectors need explicit handling.
5It is widely useful for embedding retrieval.
6Evaluate scores on your real application data.

Key Takeaways

  • Cosine similarity focuses on the angle between vectors.
  • Normalization reduces the effect of raw vector magnitude.
  • It is a common comparison method for embedding-based retrieval.
  • Never treat a similarity score as a universal relevance threshold.
  • In RAG, similarity helps retrieve candidate context; it does not replace evaluation or answer verification.