Unit 2 · Length, angle and the dot product
Lesson 13 · Available to read
Cosine similarity
Cosine similarity compares the directions of two vectors and ignores their lengths, as search engines and recommenders do.
The dot product mixes two kinds of information: the angle between vectors and their lengths. To compare direction alone, divide by the norms. The result is the cosine similarity:
cos(a, b) = (a · b) / (‖a‖ ‖b‖),
which is the cosine of the angle between the vectors, and equivalently the dot product of their unit vectors. It always lies between −1 and 1: a value of 1 means identical directions, 0 means orthogonal, and −1 means opposite directions.
Scaling either vector by a positive number leaves the cosine similarity unchanged. For instance, [1, 2] and [2, 4] have cosine similarity exactly 1, although their lengths differ by a factor of two.
This property is precisely what is needed to compare documents. Represent each document by the counts of selected words. A short article A = [2, 1] and a longer one B = [8, 4] use the words in the same proportions, so cos(A, B) = 1: they are about the same topic. A third document C = [1, 4.5] uses them in a different mix; here cos(A, C) = 6.5 / (√5 · √21.25) ≈ 0.63. Euclidean distance would wrongly suggest that A is closer to C than to B, simply because B is long.
Search engines, recommendation systems and language-model retrieval all rank items by cosine similarity between such vectors.
The takeaway
Cosine similarity, a · b / (‖a‖‖b‖), measures alignment of direction regardless of length.
Practice
0 of 5 attempted
- 1Calculate
Compute the cosine similarity of [1, 0] and [1, 1].
Saved in this browser
- 2Calculate
Compute the cosine similarity of [1, 2] and [3, 6].
Saved in this browser
- 3Multiple choice
You want to compare the topics of articles of very different lengths. Which measure is most suitable?
- 4Explain in your own words
Why is it often desirable to ignore vector length when comparing documents?
Saved in this browser
- 5Apply
A user's taste vector is [5, 1] (action, romance). Film X is [4, 1] and film Y is [1, 4]. Which should be recommended, and why?
Saved in this browser