Study Vault Search notes, aliases and full text
Graph
ConceptLinear Algebra used inDBISAI-written · not yet proofread

Cosine Similarity

Also cos-similarity

The cosine similarity of two nonzero vectors is their dot product divided by the product of their Euclidean norms, cos-sim(x, y) = x·y / (‖x‖ ‖y‖), which equals the cosine of the angle between them.

Notation: DBIS writes x∙yx \bullet y for the dot product and ∣x∣|x| for ∥x∥2\|x\|_2. MML defines the angle for any inner product ⟨⋅,⋅⟩\langle \cdot, \cdot \rangle as cos⁡ω=⟨x,y⟩/(∥x∥∥y∥)\cos\omega = \langle x, y \rangle / (\|x\| \|y\|); cosine similarity is the case of the dot product.

Formula#

Normalize first. With the unit vectors x′=x/∥x∥2x' = x / \|x\|_2 and y′=y/∥y∥2y' = y / \|y\|_2 (so ∥x′∥2=∥y′∥2=1\|x'\|_2 = \|y'\|_2 = 1):

cos-sim(x,y)=cos-sim(x′,y′)=x′⋅y′.\text{cos-sim}(x, y) = \text{cos-sim}(x', y') = x' \cdot y'.

So after normalizing all vectors once, every cosine similarity is a plain dot product, and the similarities of one vector qq to all columns of a matrix AA are the single product q′⊤A′q'^\top A' (A′A' = AA with normalized columns).

Properties#

  • Range: cos-sim(x,y)∈[−1,1]\text{cos-sim}(x, y) \in [-1, 1], by the Cauchy–Schwarz inequality ∣x⋅y∣≤∥x∥2∥y∥2|x \cdot y| \le \|x\|_2 \|y\|_2.
    • =1= 1: same direction (y=λxy = \lambda x, λ>0\lambda > 0).
    • =0= 0: orthogonal (x⋅y=0x \cdot y = 0).
    • =−1= -1: opposite direction (y=λxy = \lambda x, λ<0\lambda < 0).
    • For vectors with nonnegative entries (e.g. term counts) it lies in [0,1][0, 1].
  • Scale invariance: cos-sim(λx,y)=cos-sim(x,y)\text{cos-sim}(\lambda x, y) = \text{cos-sim}(x, y) for every λ>0\lambda > 0; for λ<0\lambda < 0 the sign flips. It compares directions only and ignores lengths, unlike the plain dot product, which grows with ∥x∥2\|x\|_2.
  • Symmetric: cos-sim(x,y)=cos-sim(y,x)\text{cos-sim}(x, y) = \text{cos-sim}(y, x).
  • Not a metric: it is a similarity (large = similar), not a distance. For unit vectors it determines the Euclidean distance: ∥x′−y′∥22=2−2 cos-sim(x,y)\|x' - y'\|_2^2 = 2 - 2\,\text{cos-sim}(x, y). So ranking by highest cos-sim is the same as ranking normalized vectors by smallest Euclidean distance.
  • Undefined for the zero vector (division by 00).
ProofVia the law of cosines

The triangle spanned by xx and yy has the third side x−yx - y. The law of cosines (c2=a2+b2−2abcos⁡γc^2 = a^2 + b^2 - 2ab\cos\gamma, which for γ=90°\gamma = 90° is Pythagoras) gives

∥x−y∥22=∥x∥22+∥y∥22−2∥x∥2∥y∥2cos⁡ω.\|x - y\|_2^2 = \|x\|_2^2 + \|y\|_2^2 - 2\|x\|_2\|y\|_2 \cos\omega.

Expanding with the dot product: ∥x−y∥22=(x−y)⋅(x−y)=∥x∥22−2 x⋅y+∥y∥22\|x - y\|_2^2 = (x - y)\cdot(x - y) = \|x\|_2^2 - 2\,x \cdot y + \|y\|_2^2. Comparing both sides gives x⋅y=∥x∥2∥y∥2cos⁡ωx \cdot y = \|x\|_2 \|y\|_2 \cos\omega.

Example#

Sources#

Search

Type In
↑ ↓ move ↵ open ⇥ next section Ctrl↵ results page Prefix # to search text only