Linear Algebra
Dot product and cosine similarity
Measuring alignment, length, and similarity
One number decides whether two arrows point the same way, sit at right angles, or pull dead against each other. Divide out the two lengths and it becomes the exact yardstick a language model uses to decide what means the same thing.
The asks a single question: how much of one vector points along the other? It is largest when the two are parallel, exactly zero when they are perpendicular, and negative when they oppose. Reduce "similar" to geometry and this is what you get.
The dot product, two ways
The dot product takes two vectors and returns a single scalar. There are two recipes for it, and the small miracle of linear algebra is that they always agree. The algebraic one multiplies matching components and adds them up. The geometric one multiplies the two lengths by the cosine of the angle between them.
Length, right angles, and shadows
Turn the dial
Rotate and stretch below. is fixed along the horizontal. Watch the readouts: the dot product and swing from (aligned) through (perpendicular) to (opposite). The shaded bar along is 's projection, the shadow .
These two vectors are loosely similar.
Notice what moves the numbers
Similarity is just the angle
To compare direction alone, strip the lengths out of the dot product by dividing by both magnitudes. What survives is the cosine of the angle, .
Because it is bounded in and blind to magnitude, it is the natural way to score "how alike are these two directions?". A long vector and a short vector that point the same way score a perfect . This is precisely how a model compares embeddings, the vectors it stores for words and documents. Below, drag the query direction and the words re-rank live by cosine similarity to wherever you point it.
- 1. cat0.99
- 2. dog0.99
- 3. bus0.31
- 4. car0.08
- 5. king-0.11
- 6. queen-0.31
Length is irrelevant, angle is everything
The whole computation is two lines.
import numpy as np
a = np.array([4.0, 0.0])
b = np.array([3.0, 2.0])
dot = a @ b # 12.0 = 4*3 + 0*2
cos = dot / (np.linalg.norm(a) * np.linalg.norm(b)) # 0.832 = pure angleCheck yourself
Two nonzero vectors have a dot product of exactly zero. The vectors must be:
Cosine similarity divides the dot product by both magnitudes. The main effect is to:
Give both forms of a·b, and say what cosine similarity does that the raw dot product does not.
One recipe is arithmetic, the other is geometry. Try to state it, then check.
Lock it in
- The dot product is sum of products, and also length times length times cos.
- Zero dot product means orthogonal; positive means aligned, negative opposed.
- Divide out both lengths to get cosine similarity: pure direction in [-1, 1].
- This is how attention scores tokens and how RAG ranks documents.
Primary source
Where this reappears