Search

Search papers and lessons

Cosine Similarity

Level 1 · 9 min read

Cosine similarity scores how alike two vectors point by taking the dot product and dividing out their lengths, so only the angle between them matters.

On this page

  • Colour = topic mix
  • Linear algebra
  • Representation learning
  • Discrete math
  • Sign in to see your progress

TL;DR

Cosine similarity compares two vectors by the angle between them. It is the dot product of the two vectors divided by the product of their lengths, so the answer lies between −1-1 and 11. A value of 11 means the vectors point the same way, 00 means they are at right angles, and −1-1 means they point in opposite directions.

Because the lengths are divided out, cosine similarity ignores how big the vectors are and keeps only their direction. That is what you want when a long document and a short document about the same topic should count as alike.

Where you'll see it: in ranking search results and retrieval-augmented systems, where embeddings are compared with a cosine score, and in recommender systems that match a user vector to item vectors.

Intuition

Two arrows, one angle

Picture two arrows starting from the same point. If they point the same way, they agree completely. If they point at right angles, they have nothing in common. If they point in opposite directions, they disagree completely. The angle θ\theta between the arrows captures this, and the cosine of that angle runs from 11 (angle 00) down through 00 (angle 90∘90^\circ) to −1-1 (angle 180∘180^\circ).

The plot shows cos⁡θ\cos\theta for angles from 00 to π\pi radians.

00.511.522.53−1−0.500.51angle θ between the two vectors (radians)cosine similarity
  • cos θ
Cosine similarity as a function of the angle. Markers at 0, 60°, 90° and 180°: the score is 1, 0.5, 0 and −1.

Why divide out the length

The plain dot product also reflects direction, but it is scaled by the lengths too. Double one vector and its dot product with anything else doubles. In many settings that scaling is noise. Suppose you describe two documents by counts of words. A long article about cats uses every cat word many times, and a short note about cats uses them fewer times. The counts are different, but the topic is the same. Dividing by the lengths removes that effect, and the score depends only on the proportions of the words.

This is why cosine similarity is the usual choice for comparing text, embeddings and other high-dimensional data where the overall size of a vector is less informative than its pattern.

flowchart LR
  A[Vector a] --> D[Dot product a · b]
  B[Vector b] --> D
  A --> N1[Length of a]
  B --> N2[Length of b]
  D --> C[Divide]
  N1 --> M[Multiply the lengths]
  N2 --> M
  M --> C
  C --> S[Cosine similarity]

The math

Definition

Definition: Cosine similarity

For two nonzero vectors a\mathbf{a} and b\mathbf{b} in Rd\mathbb{R}^d, the cosine similarity is

cos⁡(a,b)=a⋅b∥a∥ ∥b∥,\cos(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a} \cdot \mathbf{b}}{\|\mathbf{a}\|\,\|\mathbf{b}\|},

where a⋅b\mathbf{a} \cdot \mathbf{b} is the dot product and ∥a∥\|\mathbf{a}\| is the Euclidean length of a\mathbf{a}.

Here a⋅b=∑i=1daibi\mathbf{a}\cdot\mathbf{b} = \sum_{i=1}^{d} a_i b_i is the sum of the products of matching entries. The length ∥a∥=∑i=1dai2\|\mathbf{a}\| = \sqrt{\sum_{i=1}^{d} a_i^2} is the square root of the sum of the squared entries. Dividing by both lengths is the step that removes the effect of size.

The angle θ\theta between the vectors is defined by cos⁡θ=cos⁡(a,b)\cos\theta = \cos(\mathbf{a}, \mathbf{b}), so θ=arccos⁡(cos⁡(a,b))\theta = \arccos\big(\cos(\mathbf{a}, \mathbf{b})\big). The inverse cosine returns an angle between 00 and π\pi. Cosine similarity itself never requires computing that angle.

Range

The Cauchy-Schwarz inequality (the dot product of two vectors can never be larger in size than the product of their lengths) says ∣a⋅b∣≤∥a∥ ∥b∥|\mathbf{a} \cdot \mathbf{b}| \le \|\mathbf{a}\|\,\|\mathbf{b}\|. Dividing both sides by the positive number ∥a∥ ∥b∥\|\mathbf{a}\|\,\|\mathbf{b}\| gives −1≤cos⁡(a,b)≤1-1 \le \cos(\mathbf{a}, \mathbf{b}) \le 1. Equality holds exactly when one vector is a scalar multiple of the other: +1+1 for a positive multiple, −1-1 for a negative one.

Unit vectors

If both vectors have length 1, the denominator is 1 and the cosine equals the dot product. Many systems normalise every vector to length 1 first, so that a plain dot product gives the same ranking as cosine similarity. For a unit vector a^=a/∥a∥\hat{\mathbf{a}} = \mathbf{a}/\|\mathbf{a}\|, we have cos⁡(a,b)=a^⋅b^\cos(\mathbf{a}, \mathbf{b}) = \hat{\mathbf{a}} \cdot \hat{\mathbf{b}}.

Distance

Cosine distance is 1−cos⁡(a,b)1 - \cos(\mathbf{a}, \mathbf{b}). It is 00 for vectors pointing the same way and 22 for opposite ones. It is not a true metric, because the triangle inequality can fail, but it is a convenient way to turn a similarity into something that behaves like a distance.

Worked examples

Example
Two vectors in the plane

Let a=(1,1)\mathbf{a} = (1, 1) and b=(2,0)\mathbf{b} = (2, 0).

  1. Dot product: a⋅b=1×2+1×0=2\mathbf{a} \cdot \mathbf{b} = 1 \times 2 + 1 \times 0 = 2.
  2. Length of a\mathbf{a}: ∥a∥=12+12=2≈1.4142\|\mathbf{a}\| = \sqrt{1^2 + 1^2} = \sqrt{2} \approx 1.4142.
  3. Length of b\mathbf{b}: ∥b∥=22+02=2\|\mathbf{b}\| = \sqrt{2^2 + 0^2} = 2.
  4. Divide: cos⁡(a,b)=22×2=12≈0.7071\cos(\mathbf{a}, \mathbf{b}) = \dfrac{2}{\sqrt{2} \times 2} = \dfrac{1}{\sqrt{2}} \approx 0.7071.
  5. Angle: θ=arccos⁡(0.7071)=45∘\theta = \arccos(0.7071) = 45^\circ.

The vectors are 45 degrees apart. The arrow b\mathbf{b} points along the horizontal axis and a\mathbf{a} is the diagonal, so 45 degrees is what the picture shows.

Example
Three word vectors

Take three toy embeddings with three dimensions each: cat=(0.8,0.6,0.1)\mathbf{cat} = (0.8, 0.6, 0.1), dog=(0.7,0.7,0.2)\mathbf{dog} = (0.7, 0.7, 0.2) and car=(0.1,0.2,0.9)\mathbf{car} = (0.1, 0.2, 0.9).

  1. Lengths: ∥cat∥=0.64+0.36+0.01=1.01≈1.0050\|\mathbf{cat}\| = \sqrt{0.64 + 0.36 + 0.01} = \sqrt{1.01} \approx 1.0050; ∥dog∥=1.02≈1.0100\|\mathbf{dog}\| = \sqrt{1.02} \approx 1.0100; ∥car∥=0.86≈0.9274\|\mathbf{car}\| = \sqrt{0.86} \approx 0.9274.
  2. Cat and dog: dot product 0.56+0.42+0.02=1.000.56 + 0.42 + 0.02 = 1.00. Cosine =1.00/(1.0050×1.0100)≈0.985= 1.00 / (1.0050 \times 1.0100) \approx 0.985.
  3. Cat and car: dot product 0.08+0.12+0.09=0.290.08 + 0.12 + 0.09 = 0.29. Cosine =0.29/(1.0050×0.9274)≈0.311= 0.29 / (1.0050 \times 0.9274) \approx 0.311.
  4. Dog and car: dot product 0.07+0.14+0.18=0.390.07 + 0.14 + 0.18 = 0.39. Cosine =0.39/(1.0100×0.9274)≈0.416= 0.39 / (1.0100 \times 0.9274) \approx 0.416.

Interpretation: cat and dog point almost the same way (score near 1), so the model treats them as close. Car is only loosely related to either. The scores are the ranking a search engine would use to put "dog" ahead of "car" when the query is "cat".

Example
Scaling does not change the score

Let u=(3,4)\mathbf{u} = (3, 4) and v=(4,3)\mathbf{v} = (4, 3), then compare u\mathbf{u} with 2v=(8,6)2\mathbf{v} = (8, 6).

  1. u⋅v=12+12=24\mathbf{u} \cdot \mathbf{v} = 12 + 12 = 24, ∥u∥=5\|\mathbf{u}\| = 5, ∥v∥=5\|\mathbf{v}\| = 5, so cos⁡(u,v)=24/25=0.96\cos(\mathbf{u}, \mathbf{v}) = 24 / 25 = 0.96.
  2. u⋅(2v)=48\mathbf{u} \cdot (2\mathbf{v}) = 48, ∥2v∥=10\|2\mathbf{v}\| = 10, so cos⁡(u,2v)=48/50=0.96\cos(\mathbf{u}, 2\mathbf{v}) = 48 / 50 = 0.96.

Doubling v\mathbf{v} doubled the dot product and the length, and the score stayed at 0.96. The angle is arccos⁡(0.96)≈16.3∘\arccos(0.96) \approx 16.3^\circ.

Tradeoffs and failure modes

Cosine similarity is a good default when the direction of a vector carries the meaning and its size does not. It stops being the right tool when size carries information.

SituationWhat goes wrongBetter choice
Vector length encodes confidence or popularityCosine throws that signal awayDot product, or a distance that keeps magnitude
Vectors are already unit lengthNothing is wrong; cosine equals the dot productUse the dot product, which is cheaper
A vector is all zerosThe denominator is zero and the score is undefinedGuard the zero case, or add a small epsilon
Entries have very different scalesOne large entry dominates the directionStandardise each dimension first
Need to ignore a common offset in the dataCosine keeps the offset, so every score looks highSubtract the mean first, which gives Pearson correlation
Need a true distance for indexing structuresCosine distance fails the triangle inequalityEuclidean distance on unit vectors, which is monotone with cosine

Two practical points. First, if you normalise your vectors once when you store them, you can use a fast dot product at query time and still get cosine rankings. Second, scores from cosine are comparable across queries in a way that raw dot products are not, which makes thresholds easier to set.

History

The idea comes from geometry and linear algebra, where the cosine of the angle between two vectors had long been used. Its use as a measure of document similarity grew out of information retrieval in the 1960s and 1970s. Researchers building systems such as Gerard Salton's SMART project represented documents as vectors of term weights and ranked them by the angle to the query. Cosine was attractive because it did not favour long documents, which contain more words and would otherwise look more relevant. The vector space model became the standard framework for text search, and cosine remained its usual score. When word and sentence embeddings became common in the 2010s, cosine similarity was carried over unchanged, because learned embeddings are also compared by direction.

Check yourself

QuestionWhat is the cosine similarity of two vectors that are perpendicular to each other?Show answer

The dot product of perpendicular vectors is zero. Dividing zero by the product of the lengths still gives zero, so the cosine is 00. The angle is 90∘90^\circ, and cos⁡90∘=0\cos 90^\circ = 0.

QuestionVectors a=(3,0)\mathbf{a} = (3, 0) and b=(1,1)\mathbf{b} = (1, 1). Compute their cosine similarity.Show answer

The dot product is 3×1+0×1=33 \times 1 + 0 \times 1 = 3. The lengths are ∥a∥=3\|\mathbf{a}\| = 3 and ∥b∥=2≈1.4142\|\mathbf{b}\| = \sqrt{2} \approx 1.4142. So cos⁡(a,b)=3/(3×1.4142)=1/2≈0.7071\cos(\mathbf{a}, \mathbf{b}) = 3 / (3 \times 1.4142) = 1/\sqrt{2} \approx 0.7071. The angle is 45∘45^\circ.

QuestionWhy is cosine similarity often preferred to the plain dot product when comparing documents of very different lengths?Show answer

The dot product grows with the size of both vectors, so a long document would score higher against almost any query just because it has more words. Dividing by the lengths removes size and leaves only the direction, which reflects the proportions of the words. Two documents on the same topic then score as similar regardless of their length.

QuestionYou store unit-length embeddings for a million items. Why can a search system use a dot product at query time and still rank by cosine similarity?Show answer

If every vector has length 1, the denominator in the cosine formula is 1×1=11 \times 1 = 1. So the cosine equals the dot product for every pair, and the ranking by dot product is exactly the ranking by cosine. Normalising once at storage time means the cheaper dot product does the work at query time, and the query vector is normalised once per query.

Sources