Sub topic 3
Measuring Similarity with Cosine
Prerequisites and the main idea
This chapter assumes you know basic Python and NumPy, vectors, dot products, vector norms, and the idea of word embeddings. A word embedding is a dense vector that represents a word using patterns learned from its context.
To compare two word embeddings, use cosine similarity. Cosine similarity measures the angle between two vectors rather than their lengths:
\text{cosine}(u,v)=\frac{u\cdot v}{\|u\|\|v\|}The dot product is written as \(u\cdot v\). The norm, written as \(\|u\|\), is the vector's length.
If two vectors point in the same direction, their cosine similarity is 1. If they are perpendicular, it is 0. If they point in opposite directions, it is -1.
A worked example
Consider these vectors:
- \(a=[1,0]\)
- \(b=[1,1]\)
Their dot product is \(1\). The length of \(a\) is \(1\), and the length of \(b\) is \(\sqrt{2}\). Therefore:
\text{cosine}(a,b)=\frac{1}{1\cdot\sqrt{2}}\approx0.707The vectors differ by a 45-degree angle, so their similarity is about 0.707.
import numpy as np
def cosine(u, v):
u_norm = np.linalg.norm(u)
v_norm = np.linalg.norm(v)
if u_norm == 0 or v_norm == 0:
raise ValueError("Cosine similarity is undefined for a zero vector")
return float(np.dot(u, v) / (u_norm * v_norm))
a = np.array([1.0, 0.0])
b = np.array([1.0, 1.0])
print(cosine(a, b)) # 0.707106..., the cosine of 45 degreesThe function rejects a zero vector because division by its norm would divide by zero.
Why cosine fits word embeddings
Word embeddings often encode related words as vectors with similar directions. For example, vectors for “cat” and “dog” may point in similar directions because both occur near words such as “pet,” “food,” and “animal.”
Vector length can also vary because of training details or word frequency. Cosine similarity ignores this length and compares direction:
Common errors and interpretation
Cosine similarity is a comparison score, not a guarantee that two words have the same meaning. Antonyms can appear in similar contexts, so “hot” and “cold” may receive a high score. A word can also have several meanings, but one static embedding usually combines those meanings.
Do not compare scores across unrelated embedding models without checking their training data and preprocessing. A threshold such as 0.7 is not universally “similar.” Choose thresholds using validation examples from your task.
> callout note > Normalize vectors only when it matches your workflow. If every vector has unit length, cosine similarity becomes the dot product, which can make repeated comparisons faster.
Exercise
What is the cosine similarity of u = [1, 0] and v = [0, 1], and what does it mean?
Show answer
It is 0 because the vectors are perpendicular. Their directions share no component.