Linear algebra
Cosine similarity
linalg.cosine-similarityAlso called cosine similarity, cosine, cos sim, cossim
Cosine of the angle between two nonzero vectors: their dot product divided by the product of their norms. Ranges from −1 to 1.
Notation
first vector
x ∈ ℝn
second vector
y ∈ ℝn
vector length
Size, at least 1
Result: the similarity
scalar
Worked examples
Each result is solved exactly and confirmed by two independent computations.
Given
Result
Given
Result
Given
Result
≈ 0.707106781187
Given
Result
≈ 0.974631846197
Common mistakes
Divides by one norm only
The dot product is divided by the norm of x but not of y.
Fix: Divide by the product of both norms.
Divides by squared norms
The denominator uses the sums of squares without their square roots.
Fix: Divide by ‖x‖‖y‖.
Source
Manning et al. 2008
Manning, Christopher D.; Raghavan, Prabhakar; Schütze, Hinrich. Introduction to Information Retrieval. Cambridge University Press, 2008.