Sub topic 15
Comparing Documents with Cosine Similarity
This chapter assumes you understand TF-IDF vectors, NumPy arrays, and basic scikit-learn usage. You will use cosine similarity to measure how closely two documents match by word usage.
The basic idea
A document can be represented as a vector. Each position in the vector corresponds to a vocabulary term, and each value is that term's count or TF-IDF weight.
Cosine similarity compares the direction of two vectors rather than their length:
cosine_similarity(a, b) = (a · b) / (||a|| ||b||)
Here, a · b is the dot product. ||a|| is the vector's length, also called its Euclidean norm.
The result usually ranges from 0 to 1 for nonnegative text vectors:
1means the vectors point in the same direction.0means they share no weighted terms.- A larger value means greater similarity.
Document length matters less than it would with a raw dot product. A long document can contain more words without automatically appearing more similar.
A small example
Suppose two documents have these vectors:
| Document | cat | dog | garden |
|---|---|---|---|
| A | 1 | 1 | 0 |
| B | 1 | 0 | 1 |
Their dot product is 1. Each vector has length √2, so:
similarity = 1 / (√2 × √2) = 0.5
The documents share the term cat, but each has one different term. Their similarity is therefore halfway between identical and completely unrelated vectors.
TF-IDF vectors are often L2-normalized, meaning each row has length 1. When that is true, cosine similarity becomes the dot product of the two rows.
Computing similarity with scikit-learn
TfidfVectorizer creates normalized TF-IDF vectors by default. cosine_similarity compares one row with every row in a matrix.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
docs = [
"the cat sat on the mat",
"the cat slept on the rug",
"a dog ran through the park",
]
vectorizer = TfidfVectorizer(stop_words="english")
X = vectorizer.fit_transform(docs)
scores = cosine_similarity(X[0], X)
print(scores.round(2))The first score is 1.00 because the first document is compared with itself. The second score should be higher than the third because the first two documents share more terms.
Choosing a useful threshold
A similarity score has meaning only in context. A score of 0.6 might be useful for duplicate detection but too low for merging support tickets. Test thresholds on labeled examples instead of choosing one by intuition.
Common causes of misleading scores include inconsistent lowercasing, unsuitable stop-word removal, and a vocabulary that is too small. N-grams can help distinguish short phrases such as “credit card” from documents that merely contain “credit” and “card” separately.
Exercise
Why is the self-similarity of a normalized document vector equal to 1?
Show answer
Its dot product with itself is 1, because its squared L2 length is 1.