

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Semantic Search
incomplete
2: Embeddings
incomplete
3: Embedding Models
incomplete
4: Model Selection
incomplete
5: Vector Operations
incomplete
6: Dimensions
incomplete
7: Dot Product Similarity
incomplete
8: Cosine Similarity
incomplete
9: Why Cosine Similarity?
incomplete
10: Generating Text Embeddings
incomplete
11: Document Embeddings
incomplete
12: Query Embeddings
incomplete
13: Same Model
incomplete
14: Implementing Semantic Search
incomplete
15: Locality-Sensitive Hashing
incomplete
16: Vector Databases
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Dot product has a problem: it's affected by vector magnitude. Vectors have both direction and magnitude (size). Direction is the important part for semantic similarity, but length can affect vector operations. For example, these two vectors have identical direction but different magnitudes:
In semantic search, we usually don't care about vector magnitude, just direction. Magnitude can represent "confidence" or "strength." For example, say we search for "positive Paddington reviews." We probably want both of these in the results set:
Cosine similarity solves this by measuring the angle between vectors, ignoring their length. For example, the dot product of these two vectors:
[0.6, 0.8] (magnitude = 1.0)[3.0, 4.0] (magnitude = 5.0)is 5.0.
The vectors point in exactly the same direction (same type of movie), but the dot product is heavily influenced by magnitude. For our purposes, we want to ignore magnitude and focus on direction.
Cosine similarity measures the cosine of the angle between two vectors, meaning it only cares about their direction. This value conventionally ranges from -1.0 to 1.0:
1.0: Vectors point in exactly the same direction (perfectly similar)0.0: Vectors are perpendicular (no similarity)-1.0: Vectors point in opposite directions (perfectly dissimilar)The formula is as follows:
cosine_similarity = dot_product(A, B) / (magnitude(A) * magnitude(B))
And it works in two steps:
Complete the cosine_similarity function.
If you're curious, euclidean_norm just adds the squares of all the numbers in a vector, then takes the square root of that sum. This should be reminiscent of the Pythagorean theorem.