Dot Products and Cosine Similarity in Machine Learning
Learn what a dot product measures, how cosine similarity differs from it and from distance, and how to pick one for search or scoring.
Key takeaways
- The dot product a · b equals the two lengths multiplied by the cosine of the angle between the vectors.
- Cosine similarity ignores length and always lies between −1 and 1.
- Dot product, cosine similarity and Euclidean distance can rank the same candidates differently.
- For vectors of length 1, all three give the same nearest-neighbor ordering.
- Use the similarity that an embedding model was trained with, and confirm it on your own examples.
A dot product multiplies two vectors entry by entry and adds the results into one number. It is large and positive when the vectors point in similar directions and are long, near zero when they are perpendicular, and negative when they point in opposing directions.
Cosine similarity is the dot product after dividing out both lengths, so only the angle between the vectors remains. Which one you want depends on whether length carries information in your problem.
Two formulas for one number
For vectors a and b with d entries each, the algebraic definition is a sum of products.
a · b = a₁b₁ + a₂b₂ + ... + a_d b_d The geometric definition says the same quantity equals ‖a‖ ‖b‖ cos θ, where ‖a‖ is the Euclidean length of a and θ is the angle between the two vectors.
Take a = (3, 4) and b = (4, 3).
a · b = 3·4 + 4·3 = 24
‖a‖ = √(9 + 16) = 5
‖b‖ = √(16 + 9) = 5
cos θ = 24 / (5·5) = 0.96
θ ≈ 16.3° The first formula is how a computer calculates it. The second is how you should picture it: the length of one vector, times the length of the other's shadow along it.
What the sign and size tell you
| Angle between vectors | cos θ | Dot product |
|---|---|---|
| 0°, same direction | 1 | Largest possible for those lengths |
| Less than 90° | Between 0 and 1 | Positive |
| 90°, orthogonal | 0 | 0 |
| More than 90° | Between −1 and 0 | Negative |
| 180°, opposite | −1 | Most negative for those lengths |
The largest value the dot product can take is ‖a‖ ‖b‖. This bound is the Cauchy-Schwarz inequality, written |a · b| ≤ ‖a‖ ‖b‖. It is the reason cosine similarity can never leave the range from −1 to 1, apart from tiny rounding errors in floating point.
Orthogonal does not mean opposite. Two documents with no words in common have a cosine of zero under word counts, which says "nothing shared", not "contrary".
Removing length with cosine similarity
Cosine similarity is a · b divided by ‖a‖ ‖b‖. Multiply b by 10 and the dot product with a jumps from 24 to 240, while the cosine stays at 0.96.
That is useful for text. If you paste a document twice into itself, every word count doubles, but its topic is unchanged. Cosine similarity treats both versions as identical in direction. This is one reason it is common with word counts, TF-IDF and text embeddings.
Length is sometimes informative. In a recommender trained with dot product scores, an item vector's length may partly reflect how popular or broadly liked the item is. Dividing it out changes what gets recommended.
Three rankings that disagree
Let the query be q = (1, 1), with two candidates u = (2, 2) and v = (5, 1).
| Candidate | Dot product with q | Cosine with q | Euclidean distance to q |
|---|---|---|---|
| u = (2, 2) | 4 | 1.00 | about 1.41 |
| v = (5, 1) | 6 | about 0.83 | 4 |
The dot product prefers v, because v is long. Cosine similarity and distance prefer u. All three calculations are correct; they answer different questions.
When all three agree
If every vector is scaled to length 1, called L2 normalization, the dot product and the cosine become the same number. Distance joins them through a simple identity.
‖a − b‖² = ‖a‖² + ‖b‖² − 2 a · b expand the square
= 2 − 2 cos θ when ‖a‖ = ‖b‖ = 1 Check it with a = (0.6, 0.8) and b = (0.8, 0.6). The difference is (−0.2, 0.2), with squared length 0.08. The cosine is 0.96, and 2 − 2·0.96 = 0.08.
Higher cosine therefore means smaller distance, and sorting by either gives the same order. Many vector search systems exploit this by normalizing once at indexing time and then computing fast dot products.
The shadow of one vector on another
Dividing a · b by the length of b gives the scalar projection of a onto b: how far a reaches in the direction of b. Multiplying that number by the unit vector along b gives the shadow itself.
a = (3, 4), b = (1, 0)
scalar projection = (a · b) / ‖b‖ = 3
projected vector = (a · b / b · b) · b = (3, 0)
leftover = a − (3, 0) = (0, 4)
leftover · b = 0 the leftover is orthogonal to b Every vector splits this way into a part along a chosen direction and a part at right angles to it. A linear classifier uses only the part of an input that lies along its weight vector. Any change to the input in an orthogonal direction leaves the score exactly where it was.
The same split is the basis of least squares regression and of removing an unwanted direction from a representation. Removing one direction does not guarantee that the related information is gone, because it may also be stored in other directions or in nonlinear form. Test with a fresh classifier on held-out data.
Where dot products sit inside models
Dot products are the basic arithmetic of most models.
- A linear model's score is w · x plus a constant. The weight vector defines the direction that raises the score.
- Each unit in a dense layer takes a dot product of its weights with the incoming values.
- A matrix product is a table of dot products between the rows of one matrix and the columns of another.
- Attention compares query and key vectors with scaled dot products, as in self-attention computed by hand.
- A matrix factorization recommender predicts a preference from the dot product of a user vector and an item vector.
Kernel methods go one step further. They replace the plain dot product with a function that behaves like a dot product in a different, often much larger, space.
Centering changes the meaning
Subtract each vector's own mean from its entries, then take the cosine. The result is the Pearson correlation between the two lists of numbers.
Consider ratings from two people on three films: (1, 2, 3) and (3, 4, 5). Their raw cosine is 26 / √(14 · 50) ≈ 0.98, high but not 1. After centering, both become (−1, 0, 1) and the cosine is exactly 1. The second person rates everything two points higher but ranks the films the same way.
When all entries are positive, raw cosines tend to crowd toward the top of the range. Centering, using means computed from training data, often spreads them out and makes differences easier to read.
Computing it safely
Here X holds one item per row, with shape (n, d), and q is a query of shape (d,).
import numpy as np
def normalize(A, eps=1e-12):
norms = np.linalg.norm(A, axis=-1, keepdims=True)
return A / np.maximum(norms, eps)
X = np.array([[2.0, 2], [5, 1], [-1, 0]]) # shape (3, 2)
q = np.array([1.0, 1]) # shape (2,)
scores = normalize(X) @ normalize(q) # shape (3,)
order = np.argsort(-scores)
print(scores.round(3), order) The small constant eps guards against dividing by zero. A zero vector has no direction, so its cosine with anything is undefined. The guard returns 0, and you should decide whether such rows belong in the index at all.
For a handful of thousands of items, comparing against everything is simple and exact. At much larger scale, approximate nearest neighbor search trades a little accuracy for a lot of speed.
Pitfalls worth checking
Reading a cosine as a probability. A value of 0.8 does not mean an 80% chance that two items match. The typical range differs from one embedding model to another, so choose thresholds from labeled pairs in your own data.
Treating 1 − cosine as a true distance. This "cosine distance" can break the triangle inequality. For unit vectors at 0°, 45° and 90°, the direct value from first to last is 1, while the two steps add to about 0.59. If a data structure requires a real metric, use the angle itself or Euclidean distance on normalized vectors.
Ignoring dimension. Two random directions in a space with many dimensions are almost always close to orthogonal. For random unit vectors, the typical size of the cosine shrinks roughly like 1/√d. A cosine of 0.2 can be noise in 10 dimensions and a clear signal in 1,000.
Mixing models. Vectors from two different embedding models live in unrelated coordinate systems, even if they have the same length. Re-embed everything when you switch.
Common questions
Which should I use for embeddings?
Start with whatever the model's documentation or training loss used. If it was trained on cosine similarity, normalize. If it was trained on raw dot products, normalizing may discard useful information. Then compare both on a labeled retrieval set, as described in evaluating embedding models.
Can cosine similarity be negative for word counts?
Not for raw counts or ordinary TF-IDF weights, since no entry is negative. It can be negative after centering, and for learned embeddings with entries of both signs.
Why do attention layers rescale the dot product?
Sums over more terms tend to grow in size. Dividing by the square root of the key dimension keeps the scores in a range where the softmax that follows still has useful gradients.