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.
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
- Compute the dot product
- Compute the two lengths
- Divide
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
See Libraries guide For licenses and runtime requirements.
References
- Salton, G. & McGill, M. J. (1983). Introduction to Modern Information Retrieval. McGraw-Hill.
