Sub topic 4
Measuring similarity with cosine
This chapter assumes you know vectors, dot products and norms, and basic NumPy. By now you have seen that dense embeddings place words in a vector space. This chapter covers how to turn "these two vectors are close" into a number you can compute, rank and compare.
Why not Euclidean distance?
The obvious choice is the straight-line distance between two vectors. In embedding spaces it behaves badly. The length (norm) of a word vector often reflects how frequent the word is and how varied its contexts are, and that is not the same as meaning. Two vectors can point in almost the same direction and still sit far apart because one is longer.
Cosine similarity compares only direction. It is the cosine of the angle between two vectors:
cos(u, v) = (u · v) / (‖u‖ ‖v‖)The numerator is the dot product. The denominator rescales both vectors to length 1. The result lies in [-1, 1]:
| Value | Meaning |
|---|---|
| 1 | Same direction |
| 0 | Orthogonal (no shared direction) |
| -1 | Opposite direction |
import numpy as np
def cosine(u, v):
return float(np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v)))
a = np.array([1.0, 0.0])
b = np.array([1.0, 1.0])
print(cosine(a, b)) # about 0.707, the cosine of a 45 degree angle
print(cosine(a, 10 * a)) # 1.0, scaling does not change directionThe second print shows the key property. Multiplying a vector by a positive constant leaves the score unchanged.
Computing many similarities at once
Looping over a vocabulary of hundreds of thousands of words with the function above is slow. Normalize every row once, and then each similarity is a plain dot product. A single matrix-vector product scores the whole vocabulary.
import numpy as np
def normalize_rows(M):
norms = np.linalg.norm(M, axis=1, keepdims=True)
return M / np.maximum(norms, 1e-12)
def nearest(word, words, E, k=2):
U = normalize_rows(E)
i = words.index(word)
sims = U @ U[i]
order = np.argsort(-sims)
return [(words[j], float(sims[j])) for j in order if j != i][:k]
words = ["cat", "dog", "car"]
E = np.array([
[0.9, 0.1, 0.0],
[0.8, 0.3, 0.1],
[0.0, 0.2, 0.9],
])
print(nearest("cat", words, E))
# [('dog', about 0.96), ('car', about 0.02)]This is essentially what most_similar in gensim does: it keeps a normalized copy of the embedding matrix and takes dot products against it.
Connection to Euclidean distance
Once vectors have unit length, the two measures agree on ranking. For unit vectors u and v:
‖u − v‖² = 2 − 2 cos(u, v)A larger cosine means a smaller Euclidean distance, so nearest-neighbour order is identical. The two measures differ only when the vectors have different lengths. Normalizing first and then using any distance gives you cosine behaviour.
Common errors and gotchas
- Zero vectors. The norm is 0, so the formula divides by zero and returns
nan. Thenp.maximum(norms, 1e-12)guard innormalize_rowsreturns a zero vector instead, which yields similarity 0. Decide explicitly how your code should treat a word with no vector. - Raw dot product is not cosine. A raw dot product favours long vectors, so frequent words tend to dominate rankings. Use it only when you have deliberately normalized.
- Cosine is not a true distance.
1 - cosdoes not satisfy the triangle inequality. If an algorithm requires a metric, use angular distance,arccos(cos), or normalize and use Euclidean distance. - Scores are model-specific. A cosine of 0.5 can mean "strongly related" in one model and "barely related" in another. It depends on dimension, training corpus and algorithm. Compare scores only within one embedding space, and rely on rankings or on thresholds you tuned yourself. Do not compare across models.
- Different spaces cannot be compared. Vectors from two separately trained models have unrelated axes. Cosine between a word2vec vector and a GloVe vector is meaningless.
- Negative values are uncommon. In many embedding spaces most word pairs score between 0 and 1. A score near 0 means "unrelated", and negative scores do not reliably mean "opposite meaning".
What a high score means
Cosine measures closeness of distributional behaviour, meaning how similar the contexts are in which two words appear. That produces a few results that surprise newcomers:
- Similarity versus relatedness. "cat" and "dog" are similar (they are substitutable). "coffee" and "cup" are related (they co-occur) but do not substitute for each other. Embeddings mix both, and the balance depends on window size and training method.
- Antonyms score high. "hot" and "cold" occur in the same contexts ("it was very ___"), so they often sit close together.
- Rare words are noisy. A vector trained from a handful of occurrences can have a high cosine with an unrelated word by accident.
- High dimensions concentrate scores. In 300 dimensions, random vectors are nearly orthogonal. A cosine of 0.3 can therefore already be meaningful.
Some embedding spaces also share a common direction that raises every pairwise cosine. A common remedy is to subtract the mean vector from all embeddings before computing cosine. Try it only if you see all scores bunched near the top, and check the effect against a similarity benchmark.
Where cosine appears later
Nearest-neighbour queries and analogies in later chapters rely on it. An analogy query adds and subtracts vectors, and then ranks the vocabulary by cosine against the result. Intrinsic evaluation also uses it. Benchmarks compare cosine scores with human similarity judgements through rank correlation.
Exercise
Let u = [3, 4] and v = [4, 3]. Compute cos(u, v). Then say what happens to the cosine if you replace v with 100 * v, and what happens to the Euclidean distance between u and v.
Show answer
The dot product is 34 + 43 = 24. Both norms are 5, so cos = 24 / 25 = 0.96. Replacing v with 100 * v leaves the cosine at 0.96, because it depends only on direction. The Euclidean distance grows from sqrt(2) (about 1.41) to a very large value (about 500), because the distance depends on length.
Exercise
Your code computes nearest neighbours with a raw dot product between the query vector and the unnormalized embedding matrix. The top results are dominated by very common words. Explain why and give a one-line fix.
Show answer
A raw dot product equals cos(u, v) ‖u‖ ‖v‖, so words with large norms score high regardless of direction. Normalize each row to unit length first (for example U = E / np.linalg.norm(E, axis=1, keepdims=True)), then take U @ U[i], which is exactly cosine similarity.