Cosine similarity

Cosine Similarity

A measure of how similar the directions of two vectors are, equal to their dot product divided by the product of their lengths, ranging from −1 to 1.

Traditional algorithm

How it works

cos(a,b) = Σ a_i b_i ÷ (√Σ a_i² · √Σ b_i²). It is not affected by vector length, so it suits comparing texts of different lengths.

Steps

  1. Compute the dot product
  2. Compute the two lengths
  3. Divide
InputsTwo vectors
OutputsA number between −1 and 1
ComplexityO(d)

Example

cos((1,0),(1,1)) = 1/√2 ≈ 0.707

Strengths

  • Simple and fast
  • Independent of length

Cons

  • Does not measure differences in magnitude
  • Its meaning depends on the quality of the vectors

Uses

  • Semantic search
  • Similarity between documents
  • Recommender systems

Libraries that implement it

NumPyscikit-learn (cosine_similarity)

See Libraries guide For licenses and runtime requirements.

References

  • Salton, G. & McGill, M. J. (1983). Introduction to Modern Information Retrieval. McGraw-Hill.