Similarity and distance are two sides of one coin
Every retrieval, deduplication, and clustering task in NLP rests on the same primitive: a function that takes two texts and returns a number you can sort by. The number is either a similarity, where bigger means closer, or a distance, where smaller means closer, and the two are related by a monotone transform such as one minus the similarity. Choosing badly rarely crashes anything â it just quietly returns the wrong neighbour, which is harder to notice than an exception.
The choice is not aesthetic. Cosine similarity throws away magnitude and keeps direction, which is exactly right when a document's length is irrelevant to its meaning. Jaccard ignores frequency entirely and keeps only membership, which is right for tag sets and wrong for prose. Euclidean distance keeps both, which makes it sensitive to how long a document is and therefore usually wrong for raw text vectors. The rest of this lesson makes those claims concrete with implementations you can run, then shows where each one belongs.
Cosine similarity: angle without magnitude
Cosine similarity takes the dot product of two vectors and divides by the product of their norms. The division is what removes length: a 400-word review and a 40-word excerpt expressing the same opinion end up nearly collinear, so their cosine approaches one even though their magnitudes differ by an order of magnitude.
import math
from collections import Counter
def bow_vector(text, vocab=None):
counts = Counter(text.lower().split())
if vocab is None:
vocab = sorted(counts)
return [counts.get(w, 0) for w in vocab], vocab
def cosine(v1, v2):
dot = sum(a * b for a, b in zip(v1, v2))
n1 = math.sqrt(sum(a * a for a in v1))
n2 = math.sqrt(sum(b * b for b in v2))
if n1 == 0 or n2 == 0:
return 0.0
return dot / (n1 * n2)
t1 = "the cat sat on the mat"
t2 = "the cat sat on the rug"
t3 = "quarterly earnings beat estimates"
v1, vocab = bow_vector(t1)
v2, _ = bow_vector(t2, vocab)
v3, _ = bow_vector(t3, vocab)
print("t1 vs t2:", round(cosine(v1, v2), 3)) # 0.857
print("t1 vs t3:", round(cosine(v1, v3), 3)) # 0.000
Note the failure mode visible in that output: t1 and t2 share four of six words but differ on the object, so cosine scores them high on pure lexical overlap. Cosine measures surface agreement. It does not know that mat and rug are both floor coverings, and no amount of normalization will teach it.
Jaccard, overlap, and set membership
Jaccard similarity divides the size of the intersection by the size of the union, discarding counts in the process. It is the natural metric for anything that is genuinely a set â user tags, diagnosed codes, keyword lists, the vocabulary of a short paragraph â and it has a useful bounded range from zero to one.
def jaccard(t1, t2):
a, b = set(t1.lower().split()), set(t2.lower().split())
return len(a & b) / len(a | b) if (a | b) else 0.0
def overlap_coefficient(t1, t2):
a, b = set(t1.lower().split()), set(t2.lower().split())
return len(a & b) / min(len(a), len(b)) if a and b else 0.0
def dice(t1, t2):
a, b = set(t1.lower().split()), set(t2.lower().split())
return 2 * len(a & b) / (len(a) + len(b)) if (a or b) else 0.0
short, long_ = "kubernetes ingress", "kubernetes ingress controller for nginx behind a load balancer"
print("jaccard: ", round(jaccard(short, long_), 3)) # 0.429
print("overlap: ", round(overlap_coefficient(short, long_), 3)) # 1.0
print("dice: ", round(dice(short, long_), 3)) # 0.6
The three coefficients disagree because they answer different questions. Jaccard asks how much of the combined material they share; the overlap coefficient asks how much of the smaller one the larger contains; Dice weights the intersection twice to soften Jaccard's penalty on small sets. Reporting jaccard = 0.43 for a query fully contained in a document is technically correct and practically misleading, which is why overlap is the better containment metric.
Euclidean distance and the length problem
Euclidean distance is the straight-line gap between two vectors. On unit-normalized vectors it is monotonically related to cosine â squared distance equals 2 minus 2 times cosine â so on normalized data the two rank identically. On unnormalized count vectors they diverge completely, because Euclidean grows with magnitude and therefore treats any long document as far from everything, including documents about the same topic.
| Metric | Range | Length sensitive | Handles counts | Best suited to |
|---|---|---|---|---|
| Cosine | â1 to 1 | No | Yes, after normalization | Retrieval, clustering |
| Jaccard | 0 to 1 | Partially | No, sets only | Tags, dedup, containment |
| Dice | 0 to 1 | Partially | No, sets only | Short text, segmentation |
| Euclidean | 0 to infinity | Yes | Poorly | Normalized embeddings |
| Manhattan | 0 to infinity | Yes | Better on sparse data | High-dimensional sparse |
| Hellinger | 0 to 1 | No | Yes, on distributions | Topic mixtures |
The properties worth checking before you commit
Not every similarity function is a metric, and the distinction matters once you put one inside a search index. A true metric is symmetric, so the distance from a to b equals the distance from b to a; it satisfies the triangle inequality, so going via an intermediate point can never be shorter than the direct route; and it returns zero only for identical inputs. Cosine satisfies none of these on raw vectors â it is symmetric, but two documents pointing in the same direction with different magnitudes are not identical, and the triangle inequality does not hold for the angle itself. Jaccard is a proper metric only after the usual transformation, and many ad-hoc similarity scores used in production satisfy nothing at all.
This is not pedantry. Approximate nearest neighbour libraries such as FAISS and Annoy rely on metric properties to prune the search space safely: a pruning step that assumes the triangle inequality will silently drop the true nearest neighbour when the assumption is violated, and you will never see an error, only a recall loss you cannot explain. Before adopting any custom similarity function, verify symmetry numerically on a sample, verify the triangle inequality on triples, and only then hand it to an index that promises approximate recall guarantees. When the properties genuinely do not hold, fall back to a brute-force scan or to a projection that makes them hold.
Ranking a corpus end to end
The production shape of the problem is always the same: vectorize the corpus once, vectorize the query with the identical fitted transformer, compute one row of similarities, and sort. Everything that goes wrong in practice goes wrong in the vectorization step rather than in the metric.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances
documents = [
"Postgres query planner and index selectivity",
"Kubernetes rolling updates with readiness probes",
"Sourdough hydration ratios and bulk fermentation",
"B-tree index maintenance and vacuum behaviour",
"Container orchestration and pod scheduling",
]
query = "database index tuning"
vec = TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True)
X = vec.fit_transform(documents + [query])
sims = cosine_similarity(X[-1], X[:-1])[0]
dists = euclidean_distances(X[-1], X[:-1])[0]
order = sorted(range(len(documents)), key=lambda i: -sims[i])
for rank, i in enumerate(order, 1):
print(f"{rank}. cos={sims[i]:.3f} eu={dists[i]:.3f} {documents[i]}")
# consistency check: on normalized rows the two orders must agree
assert [i for i in sorted(range(len(documents)), key=lambda i: dists[i])] == order
The assertion is worth keeping. If cosine and Euclidean disagree in ranking on L2-normalized rows, one of the two matrices was fitted differently â a bug in the pipeline rather than a property of the data.
Approximate search once the corpus grows
Exact cosine over a million documents is a million dot products per query, which is fine, and over a billion it is not. The standard escape is approximate nearest neighbours: locality-sensitive hashing buckets similar items together so only one bucket is probed, MinHash estimates Jaccard from a compact signature, and libraries such as FAISS and Annoy implement product quantization and random projection trees. These trade a little recall for orders of magnitude in latency, and the trade is controlled by a single index parameter you tune against a labelled query set.
đĄNormalize before you compare
Common Mistakes
Computing cosine on raw count vectors and expecting length invariance
Fix: Normalization is what removes magnitude; cosine on unnormalized counts is dominated by the longest document.
Reporting Jaccard when the query is a subset of the document
Fix: Use the overlap coefficient, which returns 1.0 for containment instead of penalizing the size difference.
Fitting the vectorizer separately for queries
Fix: Fit once on the corpus and call transform on queries, otherwise column order differs and every score is wrong.
Picking a metric without measuring downstream ranking quality
Fix: Evaluate against a graded relevance set; metric disagreement is task dependent and rarely obvious a priori.
Best Practices
- L2-normalize vectors before any pairwise comparison
- Keep both a similarity and a distance implementation and assert they induce the same ranking
- Switch to approximate search only after measuring the latency curve on real query volume
- Log the top-k scores, not just the top-k ids, so degenerate all-zero results are visible
Interview Questions
Q1: Why is cosine preferred over Euclidean for text?
Text vectors are sparse and vary enormously in magnitude with document length, so Euclidean mostly measures length; cosine divides out the norms and compares direction instead.
Q2: When would you use Jaccard rather than cosine?
When the representation is genuinely a set â tags, codes, keywords â because Jaccard ignores multiplicity and returns a bounded, interpretable intersection-over-union.
Q3: What is the relationship between cosine and Euclidean on normalized vectors?
Squared Euclidean distance equals 2 minus 2 times cosine, so the two induce identical rankings once every vector has unit norm.
Key Takeaways
- Cosine keeps direction and discards magnitude, which is why it dominates retrieval on sparse text
- Jaccard, Dice, and overlap answer different set questions and disagree on containment
- Euclidean on raw counts mostly measures document length, and matches cosine only after normalization
- Vectorization consistency matters more than the metric: fit once and transform everywhere
- Beyond a million documents, approximate nearest neighbour indexes trade controlled recall for large latency wins