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 for the dot product and for . MML defines the angle for any inner product as ; cosine similarity is the case of the dot product.
Formula#
Normalize first. With the unit vectors and (so ):
So after normalizing all vectors once, every cosine similarity is a plain dot product, and the similarities of one vector to all columns of a matrix are the single product ( = with normalized columns).
Properties#
- Range: , by the Cauchy–Schwarz inequality .
- : same direction (, ).
- : orthogonal ().
- : opposite direction (, ).
- For vectors with nonnegative entries (e.g. term counts) it lies in .
- Scale invariance: for every ; for the sign flips. It compares directions only and ignores lengths, unlike the plain dot product, which grows with .
- Symmetric: .
- Not a metric: it is a similarity (large = similar), not a distance. For unit vectors it determines the Euclidean distance: . So ranking by highest cos-sim is the same as ranking normalized vectors by smallest Euclidean distance.
- Undefined for the zero vector (division by ).
ProofVia the law of cosines
The triangle spanned by and has the third side . The law of cosines (, which for is Pythagoras) gives
Expanding with the dot product: . Comparing both sides gives .
Example#
Sources#
- MML p. 72 (Euclidean norm, dot product), MML p. 75 (induced norm (3.16), Cauchy–Schwarz (3.17))
- MML p. 76 (angle between vectors (3.25)), MML p. 77 (Example 3.6, Def. 3.7 orthogonality)
- Use in DBIS: Slides 11, p. 12 (definition), Slides 11, p. 13 (normalize in advance), DBIS_VL11 > Variant 2: cosine similarity, DBIS_VL11 > Efficient computation, DBIS_VL12 > Processing a query; see Word Embeddings and Language Models for document ranking, word embeddings and RAG
- Exam: DBIS Exam WS2324 (not published) Task 5.1 (implement
cos_simwithout numpy/torch)