Open Agent School · Public worked example

Cosine similarity: meaning and example

Welcome! Take one idea with you today.

Cosine similarity divides the dot product of two nonzero vectors by the product of their lengths. It measures directional alignment, ranging from -1 for opposite directions to 1 for the same direction.

Picture it: A query vector [1, 1] and document vector [2, 0] have dot product 2 and lengths sqrt(2) and 2. Their cosine similarity is 1/sqrt(2), about 0.707. Replacing the document vector with [20, 0] changes its size but not this cosine score.

What is easy to mix up?

It is a normalized dot product, equal to the ordinary dot product only when both vectors have unit length. The resulting score is not a truth probability.

Teaching example by Open Agent School. Source: scikit-learn: Cosine Similarity.