Cosine similarity scores two term-weight vectors by the cosine of their angle, $\vec{a} \cdot \vec{b} / (\lvert \vec{a} \rvert \lvert \vec{b} \rvert)$, kept between $-1$ and 1 by the Cauchy–Schwarz inequality in any dimension. A document appended to itself scores the same. For a fixed query the dot product ranks by $\lvert \vec{d} \rvert \cos\theta$ and Euclidean distance by $\vec{q} \cdot \vec{d} - \tfrac{1}{2}\lvert \vec{d} \rvert^2$, so all three rank alike when document vectors have equal length. For unit vectors $\lvert \vec{v}_1 - \vec{v}_2 \rvert^2 = 2(1 - \cos\theta)$. On the running example (ntc.ntc) the cosine ranks $d_1$, $d_3$, $d_2$, $d_4$, putting the headline first (0.686) where the dot product put it third. Random directions in $m$ dimensions have cosines of mean 0 and variance $1/m$.
In TF-IDF weighting, the four documents of this topic's running example were scored for best car insurance, and the short headline $d_1$, the best match, came last. Every count in it is 1, so it could not compete with longer documents that repeat their words. Now take any document and append a copy of it to itself. The new document says exactly the same things, in the same proportions, but every term frequency has doubled. A measure that treats the two as very different has missed the point. How can we compare a query with documents so that what a document says counts, and how long it is does not?
The answer of the vector space model is cosine similarity. Treat each document and the query as a vector of term weights, and measure the angle between two vectors rather than the distance between their tips. Doubling a vector does not change its direction, so the doubled document and the original get the same score. Later articles in this topic, and the clustering and classification topics of the course, build on the definitions here.
The measure is older than the model's usual citation. Dubin (2004) finds the cosine of the angle between vectors recommended as a measure of association in an article by Gerard Salton from 1963, and the same procedures at the center of the SMART system in its earliest descriptions of 1965. The model itself is often cited to a 1975 overview, "A vector space model for information retrieval", which does not exist. Dubin shows that the citation confuses two 1975 articles, Salton, Wong, and Yang (1975) and Salton, Yang, and Yu (1975), both about choosing index terms by their discrimination value and neither an overview of the vector space as a model of retrieval. By his account Salton first referred to it as a model of retrieval in 1979.
Here is the route. First we set up the vector representation. Then we see why distance fails and angle works, and prove that the dot product divided by the lengths is a cosine. Next we score the running example and compare cosine with the dot product and with distance when vectors are left unnormalized. Then we compare three novels and score a query against them, adapting examples from Manning, Raghavan, and Schütze (2008, §6.3). Finally we look at what a cosine is worth in a space of many dimensions, and solve three problems.
Documents as vectors
Fix a vocabulary of $M$ terms. A document $d$ becomes a vector $\vec{V}(d)$ with one component per term. The component for term $t$ is a weight, typically the TF-IDF weight of $t$ in $d$, and 0 if $t$ does not occur. A collection of $N$ documents is then an $M \times N$ term-document matrix, with one column per document.
The matrix is very sparse, since each document contains a tiny fraction of the vocabulary. A search engine does not store it as a matrix. The inverted index stores the same nonzero entries, organized by row. Learned sparse retrieval keeps this representation and this index, but lets a trained model set the weights and add terms the text lacks.
A query is treated the same way. The query jealous gossip is a vector with nonzero components for jealous and gossip and zeros elsewhere. Representing queries and documents in the same space is what makes it possible to compare them with a single measure.
In the running example, the vocabulary has six terms (auto, best, car, insurance, loan, rate). So every document and the query best car insurance are vectors in a six-dimensional space. The columns of the TF-IDF matrix in that article are the document vectors. The car-insurance headline $d_1$, for example, is $(0, 0, 0.125, 0.301, 0, 0.301)$.
With documents as points in a space, the obvious way to compare them is by how far apart they are. For a query and a document that fails.
Angle, not distance
The natural measure of difference between two points is the Euclidean distance. For a query and a document it gives the wrong answer, for the reason in the opening paragraph. Consider two terms, a query $q = (1, 1)$, a document $d = (3, 1)$, and the doubled document $d' = (6, 2)$:
| Euclidean distance from $q$ | Cosine similarity with $q$ | |
|---|---|---|
| $d = (3, 1)$ | 2.00 | 0.894 |
| $d' = (6, 2)$ | 5.10 | 0.894 |
By distance, the doubled document is much less similar to the query, simply because it is longer. By angle, the two are identical. Long documents have larger term frequencies whether or not they are more relevant, so distance would systematically penalize them for their length. The angle depends only on the proportions among the terms.
The penalty also runs the other way: distance rewards documents for being short. A query vector is short, since it has a few small weights, so any document near the origin is close to it, whether or not it shares a term. An empty document, the zero vector, is at distance $\lvert \vec{q} \rvert$ from every query. The running example below shows that this is not a curiosity.
The cosine measure
Here is the idea in one sentence: multiply two vectors component by component and add, then divide out their lengths, so that only their directions remain.
The dot product of two vectors is the sum of the products of their components,
$$\vec{V}(d_1) \cdot \vec{V}(d_2) = \sum_{t} V_t(d_1)\, V_t(d_2).$$
It is large when the two vectors give large weights to the same terms. It also grows with the vectors' lengths. Dividing by both lengths gives the cosine of the angle $\theta$ between them:
$$\text{sim}(d_1, d_2) = \cos\theta = \frac{\vec{V}(d_1) \cdot \vec{V}(d_2)}{\lvert \vec{V}(d_1) \rvert \, \lvert \vec{V}(d_2) \rvert},$$
where $\lvert \vec{V} \rvert = \sqrt{\sum_t V_t^2}$ is the Euclidean length. With nonnegative weights, the cosine ranges from 0, when the vectors share no terms and are at right angles, to 1, when they point in the same direction.
Why the ratio is a cosine. In two dimensions, write each vector by its length and direction: $\vec{a} = \lvert \vec{a} \rvert (\cos\alpha, \sin\alpha)$ and $\vec{b} = \lvert \vec{b} \rvert (\cos\beta, \sin\beta)$. Then
$$\vec{a} \cdot \vec{b} = \lvert \vec{a} \rvert \lvert \vec{b} \rvert (\cos\alpha \cos\beta + \sin\alpha \sin\beta) = \lvert \vec{a} \rvert \lvert \vec{b} \rvert \cos(\alpha - \beta),$$
by the angle-difference identity, and $\alpha - \beta$ is the angle between them.
In the $M$-dimensional term space there are no coordinates $\alpha$ and $\beta$ to write down, so the argument has to be made differently. It takes two steps: the ratio always lies between $-1$ and $1$, so it is the cosine of some angle, and that angle is the one in the triangle the two vectors form.
Step 1 (the Cauchy–Schwarz inequality). For any vectors $\vec{a}$ and $\vec{b}$, $\lvert \vec{a} \cdot \vec{b} \rvert \le \lvert \vec{a} \rvert \lvert \vec{b} \rvert$. If $\vec{b}$ is the zero vector both sides are 0. Otherwise, for any real number $\lambda$ the squared length of $\vec{a} - \lambda \vec{b}$ is not negative:
$$0 \le (\vec{a} - \lambda\vec{b}) \cdot (\vec{a} - \lambda\vec{b}) = \lvert \vec{a} \rvert^2 - 2\lambda\, \vec{a} \cdot \vec{b} + \lambda^2 \lvert \vec{b} \rvert^2.$$
Choose $\lambda = \vec{a} \cdot \vec{b} / \lvert \vec{b} \rvert^2$. The right-hand side becomes $\lvert \vec{a} \rvert^2 - (\vec{a} \cdot \vec{b})^2 / \lvert \vec{b} \rvert^2$, so $(\vec{a} \cdot \vec{b})^2 \le \lvert \vec{a} \rvert^2 \lvert \vec{b} \rvert^2$, and taking square roots gives the inequality. For nonzero vectors the ratio $\vec{a} \cdot \vec{b} / (\lvert \vec{a} \rvert \lvert \vec{b} \rvert)$ therefore lies in $[-1, 1]$, and there is exactly one angle $\theta$ between 0 and 180 degrees whose cosine it is. This step is also what guarantees that a cosine score never exceeds 1.
Step 2 (the law of cosines). The points $\vec{0}$, $\vec{a}$ and $\vec{b}$ are the corners of a triangle with sides of length $\lvert \vec{a} \rvert$, $\lvert \vec{b} \rvert$ and $\lvert \vec{a} - \vec{b} \rvert$. Three points always lie in a plane, whatever the dimension of the space around them, so the law of cosines of plane geometry applies to this triangle. With $\varphi$ the angle at the corner $\vec{0}$, it says $\lvert \vec{a} - \vec{b} \rvert^2 = \lvert \vec{a} \rvert^2 + \lvert \vec{b} \rvert^2 - 2 \lvert \vec{a} \rvert \lvert \vec{b} \rvert \cos\varphi$. Expanding the same squared length as a dot product, in any number of dimensions,
$$\lvert \vec{a} - \vec{b} \rvert^2 = (\vec{a} - \vec{b}) \cdot (\vec{a} - \vec{b}) = \lvert \vec{a} \rvert^2 + \lvert \vec{b} \rvert^2 - 2\, \vec{a} \cdot \vec{b}.$$
Comparing the two expressions gives $\vec{a} \cdot \vec{b} = \lvert \vec{a} \rvert \lvert \vec{b} \rvert \cos\varphi$. So the angle $\theta$ of step 1 is $\varphi$, the angle between the two vectors in the plane they span. (If one vector is a multiple of the other the triangle is flat, $\varphi$ is 0 or 180 degrees, and the two expressions still agree.)
Check it on the figure's example. Here $q \cdot d = 1 \times 3 + 1 \times 1 = 4$, $\lvert q \rvert = \sqrt{2}$ and $\lvert d \rvert = \sqrt{10}$, so $\cos\theta = 4 / \sqrt{20} \approx 0.894$, an angle of about 26.6 degrees. For $d'$ the dot product doubles to 8 and the length doubles to $\sqrt{40}$, so the ratio does not change.
The division is length normalization. It is often done once, in advance, by scaling every vector to length 1. For unit vectors $\vec{v}(d) = \vec{V}(d) / \lvert \vec{V}(d) \rvert$, the cosine is simply the dot product, $\text{sim}(d_1, d_2) = \vec{v}(d_1) \cdot \vec{v}(d_2)$. Search engines store each document's length, or its normalized weights, at indexing time, so that query-time scoring only needs to multiply and add.
Angle and distance after normalization
So is distance useless? Not after normalization. The two measures then agree, which later topics use when they switch between cosine and distance freely.
Proposition. For unit vectors $\vec{v}_1$ and $\vec{v}_2$ at angle $\theta$, $\lvert \vec{v}_1 - \vec{v}_2 \rvert^2 = 2(1 - \cos\theta)$.
Proof. Expand the squared distance as a dot product of the difference with itself:
$$\lvert \vec{v}_1 - \vec{v}_2 \rvert^2 = (\vec{v}_1 - \vec{v}_2) \cdot (\vec{v}_1 - \vec{v}_2) = \vec{v}_1 \cdot \vec{v}_1 - 2\, \vec{v}_1 \cdot \vec{v}_2 + \vec{v}_2 \cdot \vec{v}_2.$$
Each vector has length 1, so $\vec{v}_1 \cdot \vec{v}_1 = \vec{v}_2 \cdot \vec{v}_2 = 1$, and $\vec{v}_1 \cdot \vec{v}_2 = \cos\theta$. Substituting gives $2(1 - \cos\theta)$.
The right-hand side decreases as $\cos\theta$ increases. So ranking by cosine is the same as ranking by Euclidean distance between the normalized vectors. In the figure, $\sqrt{2(1 - 0.894)} \approx 0.460$, the chord between the two points on the unit circle. The problem with distance was never distance itself, but distance between vectors of different lengths.
The running example scored
Back to best car insurance. Score the running example's documents with TF-IDF weights on both sides and cosine normalization of both, the scheme called ntc.ntc in the SMART notation.
The query's TF-IDF vector has weights 0.125 for best and car and 0.301 for insurance. Its length is $\sqrt{0.125^2 + 0.125^2 + 0.301^2} \approx 0.349$. Each document's length is the square root of the sum of its squared TF-IDF weights. For $d_1$ that is $\sqrt{0.125^2 + 0.301^2 + 0.301^2} \approx 0.444$.
| Document | Dot product with query | Length | Cosine |
|---|---|---|---|
| $d_1$ | 0.125 × 0.125 + 0.301 × 0.301 = 0.106 | 0.444 | 0.106 / (0.444 × 0.349) = 0.686 |
| $d_2$ | 0.250 × 0.125 + 0.625 × 0.125 = 0.109 | 0.737 | 0.425 |
| $d_3$ | 0.125 × 0.125 + 0.602 × 0.301 = 0.197 | 1.093 | 0.516 |
| $d_4$ | 0.250 × 0.125 + 0.375 × 0.125 = 0.078 | 2.611 | 0.086 |
All values are rounded to three decimals and computed without intermediate rounding. The ranking is $d_1$, $d_3$, $d_2$, $d_4$. It is the first in this topic's running example that puts both documents the reader wants on top.
Compare the unnormalized dot products in the second column, which rank $d_3$ first and $d_1$ third, below the car review. Why did normalization move $d_1$ up?
- $d_1$'s length is mostly on the query. Two of its three terms are query terms, one of them insurance, which carries most of the query's weight.
- The car review's length is mostly elsewhere. Its weight is on car and auto, which the query weights lightly or not at all, and none of it is on insurance.
- The car-loan page falls far behind. Most of $d_4$'s length is the weight 2.408 on loan, a term the query does not contain.
Normalized to unit length, the vectors are:
| Term | $d_1$ | $d_2$ | $d_3$ | $d_4$ | query |
|---|---|---|---|---|---|
| auto | 0 | 0.408 | 0.827 | 0 | 0 |
| best | 0 | 0.339 | 0.114 | 0.096 | 0.358 |
| car | 0.282 | 0.848 | 0 | 0.144 | 0.358 |
| insurance | 0.678 | 0 | 0.551 | 0 | 0.862 |
| loan | 0 | 0 | 0 | 0.922 | 0 |
| rate | 0.678 | 0 | 0 | 0.346 | 0 |
Each cosine is now the dot product of a document column with the query column. For $d_1$, $0.282 \times 0.358 + 0.678 \times 0.862 \approx 0.686$, as before.
Example (the headline doubled). Double every count in $d_1$, as in the opening. Its dot product with the query doubles, from 0.106 to 0.212. The cosine stays at 0.686. The distance between the unnormalized vectors grows from 0.326 to 0.696, so by distance the doubled headline would fall from first place to second.
Euclidean distance would rank these documents differently. Between the unnormalized TF-IDF vectors and the query, the distances are 0.326 for $d_1$, 0.668 for $d_2$, 0.960 for $d_3$ and 2.605 for $d_4$: exactly the order of the documents' lengths. An empty document would be at distance 0.349, closer to the query than every document except $d_1$, although it shares nothing with it. Between the normalized vectors, the distances are 0.793, 1.073, 0.984 and 1.352. Each is $\sqrt{2(1 - \cos\theta)}$ for the cosine above, as the proposition says, and they give the same ranking as the cosine.
The demo below scores the same collection and lets every part of it be changed: the text of each document, the query, and the weighting scheme on each side.
The table of dot products and the two lists of distances gave three different orders for the same four documents. The next section says exactly when the three measures agree.
Dot product, cosine and distance without normalization
Here is the idea in one sentence: for a fixed query, the dot product ranks by cosine times the document's length, and distance ranks by the dot product minus half the squared length, so the three orders agree when all documents have the same length and can differ otherwise.
The formal version. By the result above, $\vec{q} \cdot \vec{d} = \lvert \vec{q} \rvert \lvert \vec{d} \rvert \cos\theta$. The query's length is the same for every document, so ranking by dot product is ranking by $\lvert \vec{d} \rvert \cos\theta$. For the distance, expand the square as before:
$$\lvert \vec{q} - \vec{d} \rvert^2 = \lvert \vec{q} \rvert^2 + \lvert \vec{d} \rvert^2 - 2\, \vec{q} \cdot \vec{d}.$$
Again $\lvert \vec{q} \rvert^2$ is common to all documents, so ranking by increasing distance is ranking by decreasing $\vec{q} \cdot \vec{d} - \tfrac{1}{2}\lvert \vec{d} \rvert^2$. Each measure thus treats length differently. The cosine ignores it, the dot product rewards it, and distance penalizes it. If every document vector has the same length $L$, then $\lvert \vec{d} \rvert \cos\theta$ is $\cos\theta$ multiplied by the constant $L$, and $\vec{q} \cdot \vec{d} - \tfrac{1}{2}L^2$ is the dot product less a constant, so all three orders are the same. The proposition on unit vectors is the case $L = 1$. The query never needs normalizing for this.
On the running example, with the unnormalized TF-IDF vectors and $\lvert \vec{q} \rvert = 0.349$:
| Document | $\cos\theta$ | $\lvert \vec{d} \rvert$ | $\lvert \vec{d} \rvert \cos\theta$ | $\vec{q} \cdot \vec{d}$ | $\vec{q} \cdot \vec{d} - \tfrac{1}{2}\lvert \vec{d} \rvert^2$ | Distance |
|---|---|---|---|---|---|---|
| $d_1$ | 0.686 | 0.444 | 0.304 | 0.106 | 0.008 | 0.326 |
| $d_2$ | 0.425 | 0.737 | 0.313 | 0.109 | −0.162 | 0.668 |
| $d_3$ | 0.516 | 1.093 | 0.564 | 0.197 | −0.400 | 0.960 |
| $d_4$ | 0.086 | 2.611 | 0.224 | 0.078 | −3.331 | 2.605 |
The three measures give three rankings:
- Cosine: $d_1$, $d_3$, $d_2$, $d_4$.
- Dot product: $d_3$, $d_2$, $d_1$, $d_4$. The fourth column is the dot product divided by $\lvert \vec{q} \rvert$, so it orders the documents the same way.
- Distance: $d_1$, $d_2$, $d_3$, $d_4$, the order of the lengths.
By dot product, $d$ outranks $d'$ exactly when $\lvert \vec{d} \rvert \cos\theta > \lvert \vec{d}' \rvert \cos\theta'$, that is, when its advantage in cosine exceeds its disadvantage in length. The headline's cosine is 1.329 times that of the auto-insurance page, but $d_3$ is 2.462 times as long, so the dot product puts $d_3$ ahead. A longer vector here means larger TF-IDF weights, which come from repeated or rare words. Ranking by dot product therefore favors documents that repeat their words, the flaw the overlap score had in TF-IDF weighting.
Removing length entirely is not always best either. Pivoted length normalization divides by a quantity that grows more slowly than the length, which leaves part of the length's effect in the score.
Turning a dot-product ranking into a distance ranking
Indexes for geometric search are built to find the nearest point by distance. A ranking by dot product over vectors of unequal length can be handed to such an index by adding one coordinate to every vector (Bachrach et al., 2014, Theorem 1).
Proposition. Let $M$ be the largest length among the document vectors. Append to each document vector the coordinate $\sqrt{M^2 - \lvert \vec{d} \rvert^2}$, giving $\hat{d}$, and append 0 to the query, giving $\hat{q}$. Then the document nearest to $\hat{q}$ by Euclidean distance is the document with the largest dot product $\vec{q} \cdot \vec{d}$, and the whole order by distance is the order by dot product.
Proof. The new coordinate adds $M^2 - \lvert \vec{d} \rvert^2$ to the squared length of $\vec{d}$, so every $\hat{d}$ has length exactly $M$. The query's new coordinate is 0, so $\hat{q} \cdot \hat{d} = \vec{q} \cdot \vec{d}$ and $\lvert \hat{q} \rvert = \lvert \vec{q} \rvert$. The expansion above gives $\lvert \hat{q} - \hat{d} \rvert^2 = \lvert \vec{q} \rvert^2 + M^2 - 2\, \vec{q} \cdot \vec{d}$. Only the last term depends on the document, so the distance decreases exactly as the dot product increases.
On the running example $M = 2.611$, the length of $d_4$. The appended coordinates are 2.573, 2.505, 2.372 and 0, and the distances from $\hat{q}$ are 2.594, 2.593, 2.559 and 2.605 for $d_1$ to $d_4$. Sorted, they give $d_3$, $d_2$, $d_1$, $d_4$, the dot-product order of the table. Similarity measures for embeddings proves the other reductions among dot product, distance and cosine, and what this one costs an approximate index.
The cosine compares any two vectors, not only a query with a document. The next section uses it to compare documents with each other.
Comparing three novels
Manning, Raghavan, and Schütze (2008, §6.3.1) compare three novels: Jane Austen's Sense and Sensibility (SaS) and Pride and Prejudice (PaP), and Emily Brontë's Wuthering Heights (WH). They use the counts of three terms, affection, jealous and gossip. The table below adds a fourth, wuthering, which occurs only in WH. Real novels serve here where the running example cannot, because their counts run into the hundreds:
| Term | SaS | PaP | WH |
|---|---|---|---|
| affection | 115 | 58 | 20 |
| jealous | 10 | 7 | 11 |
| gossip | 2 | 0 | 6 |
| wuthering | 0 | 0 | 38 |
The textbook normalizes the raw counts directly. Here, instead, weight each count with logarithmic term frequency, $1 + \log_{10} \mathit{tf}$ (explained in variants of TF-IDF), with no IDF. Normalize each vector to unit length:
| Term | SaS | PaP | WH |
|---|---|---|---|
| affection | 0.789 | 0.832 | 0.524 |
| jealous | 0.515 | 0.555 | 0.465 |
| gossip | 0.335 | 0 | 0.405 |
| wuthering | 0 | 0 | 0.588 |
The cosine similarities are the dot products of the columns:
| Pair | Cosine |
|---|---|
| SaS and PaP | 0.942 |
| SaS and WH | 0.789 |
| PaP and WH | 0.694 |
The two Austen novels are the most similar pair, which matches what a reader would expect.
The same comparison using raw counts instead of logarithms is instructive. It gives 0.999 for SaS and PaP, but only about 0.47 for each Austen novel with Wuthering Heights. (The textbook, with raw counts and only the first three terms, reports 0.999 and 0.888.) The raw count of affection, 115 in SaS, dominates the vectors. Any two documents that use affection heavily then look nearly identical, and Wuthering Heights looks very different mainly because of one term. Dampening term frequency spreads the weight more evenly across terms.
Scoring a query
A query is scored against each document in the same way. The query jealous gossip, with each term weighted 1, has unit vector $(0, 1/\sqrt{2}, 1/\sqrt{2}, 0)$ over the four terms. Its cosine with each novel is the sum of the novel's normalized jealous and gossip weights, divided by $\sqrt{2}$:
| Novel | Cosine with jealous gossip |
|---|---|
| WH | 0.615 |
| SaS | 0.601 |
| PaP | 0.393 |
Wuthering Heights ranks first, narrowly. It uses gossip more than Sense and Sensibility does, even though its normalized jealous weight is lower. Pride and Prejudice ranks last because it never uses gossip, although it does use jealous. Unlike a Boolean AND, cosine similarity gives the document partial credit for matching one of the two terms.
Example (normalizing the query). Dividing the query vector by its length does not change the ranking, since it divides every document's score by the same constant. With the query left as $(0, 1, 1, 0)$ the three scores are 0.870, 0.851 and 0.555 (from unrounded weights), each $\sqrt{2}$ times the value in the table, in the same order. The normalization is kept so that scores are true cosines, between 0 and 1.
Example (a common misreading). A cosine of 0.6 for one query and 0.3 for another does not mean the first result is twice as good. Scores for different queries are not comparable in any calibrated sense: each is an angle to a different query vector, and nothing ties a given angle to a given degree of relevance.
Many dimensions
The running example has six dimensions, and a real collection has one for every term of its vocabulary, tens or hundreds of thousands. What a given cosine is worth depends on that number.
Here is the idea in one sentence: two directions chosen at random are nearly at right angles when the dimension is large, and the typical size of their cosine is one over the square root of the dimension.
Proposition. Let $\vec{u}$ be a random unit vector in $m$ dimensions whose distribution is the same in every direction (rotating or reflecting the space does not change it), and let $\vec{v}$ be any fixed unit vector. Then the cosine $\vec{u} \cdot \vec{v}$ has mean 0 and variance exactly $1/m$.
Proof. Choose a rotation $T$ that carries $\vec{v}$ to the first coordinate direction $\vec{e}_1 = (1, 0, \dots, 0)$. Rotations preserve dot products, so $\vec{u} \cdot \vec{v} = (T\vec{u}) \cdot \vec{e}_1$, the first coordinate of $T\vec{u}$. By assumption $T\vec{u}$ has the same distribution as $\vec{u}$, so the cosine has the distribution of the first coordinate $u_1$. Reflecting the first axis sends $u_1$ to $-u_1$ without changing the distribution, so $u_1$ and $-u_1$ have the same mean, which must be 0. Exchanging two axes is also a reflection of the space, so every $u_i^2$ has the same mean. The squares add to 1 because $\vec{u}$ has length 1, so $m$ times that common mean is 1, and the mean of $u_1^2$ is $1/m$. With mean 0, that is the variance.
The standard deviation of the cosine is therefore $1/\sqrt{m}$. Chebyshev's inequality turns this into a bound on how often a random cosine is large: the probability that $\lvert \cos \rvert \ge \varepsilon$ is at most $1/(m\varepsilon^2)$. In 1,000 dimensions a random direction has a cosine of 0.1 or more in size with probability at most 0.1, and in 10,000 dimensions at most 0.01.
A seeded simulation agrees with the proposition. For each dimension it draws 20,000 random directions (2,000 for the largest), 30 times over, and takes the standard deviation of their cosines with a fixed direction. It also places 1,000 random unit vectors and a random unit query, and divides the largest distance from the query by the smallest. Each entry is the median of the 30 runs:
| Dimensions $m$ | $1/\sqrt{m}$ | Standard deviation of the cosine | Largest distance ÷ smallest |
|---|---|---|---|
| 2 | 0.707 | 0.706 | |
| 6 | 0.408 | 0.408 | 6.46 [5.24, 8.13] |
| 100 | 0.100 | 0.100 | 1.39 [1.37, 1.43] |
| 1,000 | 0.032 | 0.032 | 1.11 [1.11, 1.11] |
| 10,000 | 0.010 | 0.010 | 1.03 [1.03, 1.03] |
The brackets in the last column are the quartiles over the 30 runs. The ratio for $m = 6$ varies widely from run to run and should be read as "about 6". (The ratio is left out for $m = 2$, where one of 1,000 points on a circle lies almost on top of the query and the ratio is in the hundreds.) The last column is explained by the proposition together with the one on unit vectors. The distance between two unit vectors is $\sqrt{2(1 - \cos\theta)}$, so when every cosine is close to 0 every distance is close to $\sqrt{2}$, and the nearest and the farthest of the random points are almost equally far away. Beyer, Goldstein, Ramakrishnan, and Shaft (1999, Theorem 1) proved a general form of this: for a fixed number of points drawn independently from one distribution and a query drawn independently of them, if the variance of the distance (raised to any fixed power $p$), divided by the square of its mean, tends to 0 as the dimension grows, the ratio of the farthest distance to the nearest converges to 1 in probability. The table's last column is a measurement of that convergence for uniformly random directions, not a proof of it. Nearest neighbor search in high dimensions proves the theorem under the same hypotheses, with a bound for each dimension from Chebyshev's inequality.
Two consequences matter for this topic.
- The same cosine means different things in different spaces. A cosine of 0.3 between random directions is unremarkable in six dimensions, where the standard deviation is 0.408. In 10,000 dimensions it is thirty standard deviations from the mean.
- Term vectors are not random directions. Their weights are never negative, so their cosines are never negative. Two documents that share no term have a cosine of exactly 0, and a pair's cosine is positive only through the terms the two share. The high dimension of the term space therefore shows up as sparsity and many exact zeros, not as small random cosines around zero. The proposition describes vectors spread evenly over all directions. It is the baseline against which cosines between dense learned vectors, which the last article of this topic names as the model's descendant, have to be read. Limits of single-vector retrieval writes a term-weighting score as a dot product in the vocabulary's dimensions and bounds what compressing it into one dense vector loses.
Properties
- Partial matching. Any document sharing at least one term with the query receives a positive score, provided that term has a nonzero weight. (A term in every document has IDF zero and contributes nothing.) Documents matching more of the query, or matching its more heavily weighted terms, score higher.
- Length independence, and its side effect. Normalization removes the advantage long documents would otherwise have. In practice it overcorrects: on real collections, cosine normalization tends to rank short documents too highly relative to how often they are relevant. Pivoted length normalization addresses this.
- Symmetry. $\text{sim}(a, b) = \text{sim}(b, a)$, so the same measure compares documents with each other. That is the basis of finding similar documents and of clustering.
- Term independence. Each term is its own dimension, orthogonal to every other, so car and automobile are as unrelated as car and banana. This is the model's central limitation, discussed in strengths and limits of the vector space model. In the running example, the auto-insurance page $d_3$ gets no credit at all for auto, although the query asks for car.
Worked problems
The first problem is Exercise 6.15 of the course text (Manning, Raghavan, and Schütze, 2008), which continues its Exercise 6.10, solved in TF-IDF weighting. The second is its Exercise 6.17, which ranks the same three documents for a query, and the third is posed on the running example. All numbers are computed by tools/experiments/vsm/running_example.py.
Problem 1 (Exercise 6.15 of the course text). The TF-IDF weights of four terms in three documents were computed in the worked problems of TF-IDF weighting:
| Term | Doc1 | Doc2 | Doc3 |
|---|---|---|---|
| car | 44.55 | 6.60 | 39.60 |
| auto | 6.24 | 68.64 | 0 |
| insurance | 0 | 53.46 | 46.98 |
| best | 21.00 | 0 | 25.50 |
Compute the Euclidean-normalized document vectors, with one component for each of the four terms.
Solution. Each vector is divided by its length, the square root of the sum of its squared weights:
- Doc1: $\sqrt{44.55^2 + 6.24^2 + 21.00^2} = \sqrt{1984.70 + 38.94 + 441.00} = \sqrt{2464.64} \approx 49.65$.
- Doc2: $\sqrt{6.60^2 + 68.64^2 + 53.46^2} = \sqrt{43.56 + 4711.45 + 2857.97} = \sqrt{7612.98} \approx 87.25$.
- Doc3: $\sqrt{39.60^2 + 46.98^2 + 25.50^2} = \sqrt{1568.16 + 2207.12 + 650.25} = \sqrt{4425.53} \approx 66.52$.
| Term | Doc1 | Doc2 | Doc3 |
|---|---|---|---|
| car | 44.55 / 49.65 = 0.897 | 6.60 / 87.25 = 0.076 | 39.60 / 66.52 = 0.595 |
| auto | 0.126 | 0.787 | 0 |
| insurance | 0 | 0.613 | 0.706 |
| best | 0.423 | 0 | 0.383 |
Each column's squares now add to 1, up to rounding: for Doc1, $0.897^2 + 0.126^2 + 0.423^2 = 0.805 + 0.016 + 0.179 = 1.000$. That is what dividing by the length does: the squared length $\sum_t V_t^2$ is divided by itself.
Problem 2 (Exercise 6.17 of the course text). With the normalized vectors of Problem 1, rank the documents for the query car insurance when (a) each query term has weight 1, and (b) the query weights are the terms' IDF values, 1.65 and 1.62, normalized to unit length.
Solution. Both weightings rank Doc3, Doc1, Doc2. (a) The score is the sum of the document's car and insurance components. (b) The query's length is $\sqrt{1.65^2 + 1.62^2} = \sqrt{5.3469} \approx 2.312$, so its weights are $1.65/2.312 = 0.714$ and $1.62/2.312 = 0.701$:
| Document | (a) car + insurance | (b) 0.714 × car + 0.701 × insurance |
|---|---|---|
| Doc1 | 0.897 + 0 = 0.897 | 0.640 + 0 = 0.640 |
| Doc2 | 0.076 + 0.613 = 0.688 | 0.054 + 0.429 = 0.483 |
| Doc3 | 0.595 + 0.706 = 1.301 | 0.425 + 0.495 = 0.920 |
(Scores are computed from unrounded components.) The scores in (a) are not cosines, because the query $(1, 1)$ has length $\sqrt{2}$. Dividing by $\sqrt{2}$ gives the cosines 0.635, 0.487 and 0.920, in the same order. The two query weightings agree closely here because the two IDF values are nearly equal, so the normalized query is almost $(1, 1)/\sqrt{2}$.
Without normalization, the TF-IDF sums of the earlier problem were 44.55, 60.06 and 86.58, which rank Doc3, Doc2, Doc1. Normalization exchanges Doc1 and Doc2. Doc2 is the longest vector, 87.25, and most of that length is its weight on auto, which the query does not contain. Doc1 is the shortest, and car is its largest component.
Problem 3 (copies of the headline). By dot product with the unnormalized TF-IDF vectors, the headline $d_1$ of the running example ranks third. Find the smallest number of copies of the headline, placed end to end in one document, that the dot product ranks first, and the cosine of that document.
Solution. Two copies are enough, and the cosine stays at 0.686. A document of $k$ copies has every count multiplied by $k$, so its TF-IDF vector is $k$ times that of $d_1$ and its dot product with the query is $k \times 0.106$. The largest dot product among the other documents is 0.197, for $d_3$. One copy gives 0.106, which is less. Two copies give 0.212, which is more, since $0.197 / 0.106 \approx 1.85 < 2$. Scaling a vector does not change its direction, so the cosine is 0.686 for every $k$. (The collection's IDF values are taken as fixed here. Adding the document to the collection would not change them, since it contains the same terms as $d_1$ and replaces it.) A dot-product ranking can thus be raised by repeating a document's text, and a cosine ranking cannot.
What we have learned
Cosine similarity compares two weight vectors by their angle: the dot product divided by both lengths, a ratio that the Cauchy–Schwarz inequality keeps between $-1$ and 1. It ignores a document's length and keeps the proportions among its terms. For vectors of equal length, cosine, dot product and Euclidean distance rank alike, and one extra coordinate turns a dot-product ranking into a distance ranking. On the running example, normalization moved the headline $d_1$ from last to first. In many dimensions random directions are nearly at right angles, with cosines of typical size $1/\sqrt{m}$.
The definition sums over the whole vocabulary, for every document. The next article, Computing Vector Scores, shows how a search engine computes the same cosines while touching only the documents that share a term with the query.
Every number in the running example is computed by tools/experiments/vsm/running_example.py in the site repository, which also checks that the demo computes the same scores (check_demo.py). The simulation of random directions is tools/experiments/vsm/high_dimensions.py (seeds 790 to 819), and the figure comes from tools/figures/cosine-similarity.py.
References
- Bachrach, Y., Finkelstein, Y., Gilad-Bachrach, R., Katzir, L., Koenigstein, N., Nice, N., and Paquet, U. (2014). Speeding up the Xbox recommender system using a Euclidean transformation for inner-product spaces. In Proceedings of RecSys 2014, 257–264. record · 2 pages
- Beyer, K., Goldstein, J., Ramakrishnan, R., and Shaft, U. (1999). When is "nearest neighbor" meaningful? In C. Beeri and P. Buneman (Eds.), Database Theory: ICDT'99 (Lecture Notes in Computer Science, Vol. 1540, pp. 217–235). Springer. record · 3 pages
- Dubin, D. (2004). The most influential paper Gerard Salton never wrote. Library Trends, 52(4), 748–764. record
- Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, section 6.3. Cambridge University Press. record · 102 pages
- Salton, G., Wong, A., and Yang, C. S. (1975). A vector space model for automatic indexing. Communications of the ACM, 18(11), 613–620. record · 3 pages
- Salton, G., Yang, C. S., and Yu, C. T. (1975). A theory of term importance in automatic text analysis. Journal of the American Society for Information Science, 26(1), 33–44. record
Reviewed: verified, 16 Nov 2026 · checked against sources, 23 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 12 revisions