Sub topic 15
Comparing Documents with Cosine Similarity
This chapter assumes you can already build a TF-IDF matrix with TfidfVectorizer, including L2 row normalization. Here you will turn those row vectors into a similarity score between documents and use it for ranking and search.
Why not just use distance?
Once documents are rows in a matrix, you could compare them with Euclidean distance. That works poorly for text because document length changes the vector's magnitude. A document pasted twice has the same topic but twice the counts, so it sits far from the original in Euclidean terms.
Cosine similarity compares the direction of two vectors and ignores their length:
cos(a, b) = (a · b) / (‖a‖ · ‖b‖)Term weights are never negative, so scores for count and TF-IDF vectors fall between 0 and 1. A score of 1 means the vectors point the same way. A score of 0 means the documents share no vocabulary terms.
Cosine similarity on TF-IDF vectors
TfidfVectorizer L2-normalizes each row by default, so every row has length 1. The denominator is then 1, and cosine similarity reduces to a dot product. That is why scikit-learn also offers the cheaper linear_kernel for TF-IDF output.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = TfidfVectorizer()
X = vec.fit_transform(docs)
print(cosine_similarity(X).round(2))
print((X @ X.T).toarray().round(2))Both prints show the same 3 by 3 matrix. The diagonal is 1, and the matrix is symmetric. The first document scores about 0.62 against the second and about 0.52 against the third.
The sparse product X @ X.T only does work where documents share terms. For a large corpus this is much faster than comparing dense vectors.
Worked example: why 0.62?
The first two documents share on, sat and the. The word the has an IDF of 1.0, the lowest possible with the smoothed formula, but it appears twice in each document. With a raw count of 2, it contributes 4 to the dot product, and the vectors have squared norms of about 11.84. Most of the similarity comes from the.
Removing stop words shows the effect:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
for stop in (None, "english"):
X = TfidfVectorizer(stop_words=stop).fit_transform(docs)
print(stop, cosine_similarity(X[0], X).round(2))Without stop words, the first document scores 1.0, 0.62 and 0.52 against the three documents. With them removed, the scores are 1.0, 0.27 and 0.27. Each remaining pair shares exactly one term, so the similarities are equal. Your choice of preprocessing changes the numbers you rank by.
Searching with a query
To rank documents against new text, transform the query with the already fitted vectorizer. Do not call fit_transform on the query. A refit would change the vocabulary and IDF values.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = TfidfVectorizer()
X = vec.fit_transform(docs)
query = vec.transform(["a dog chased a cat"])
scores = cosine_similarity(query, X).ravel()
for i in scores.argsort()[::-1]:
print(f"{scores[i]:.2f} {docs[i]}")The best match is the cat chased the dog at about 0.78. The other two documents each score about 0.19. The word a is dropped because the default token pattern keeps only tokens of two or more characters.
Edge cases and common errors
| Situation | What happens | What to do |
|---|---|---|
| Query has no words from the vocabulary | The query vector is all zeros, and every score is 0 | Check for an all-zero result and report "no match" |
| Using `fit_transform` on the query | The vocabulary and IDF are rebuilt from the query alone, and scores become meaningless | Use `transform` only |
| Comparing vectors from two different vectorizers | Columns mean different words | Use one fitted vectorizer for both sides |
| Near-duplicate documents | Scores near 1.0 | Use a threshold such as 0.9 for deduplication, and tune it on examples |
| Very different document lengths | Short documents can score high on a few shared rare words | Inspect the top results, and consider `sublinear_tf=True` |
| Pairwise matrix on a large corpus | An n by n dense result needs n² memory | Compare in chunks, or keep only the top k per row |
A score of 0 is reliable in one direction only. It proves that the documents share no vocabulary terms, but a low score does not prove the documents are unrelated. car and automobile are different columns, so they contribute nothing to each other. This is the main limit of bag-of-words similarity.
Choices that change the scores
- Stop words and
max_df: Removing very common terms stops them from dominating the dot product, as the worked example showed. - N-grams: With
ngram_range=(1, 2), shared phrases such ascat chasedadd similarity beyond shared single words. sublinear_tf=True: Replaces a countcwith1 + ln(c), so a word repeated ten times does not count ten times as much.- Normalization: If you set
norm=None, rows are no longer unit length. Then usecosine_similarity, which normalizes internally, and not a plain dot product.
Exercise
You fit a TfidfVectorizer on 10,000 product descriptions and compare a user's search text to all of them. The search text is "wireless headphones", and neither word appears in the vocabulary. What do you see in the similarity scores, and how should the application respond?
Show answer
The query vector is all zeros, so every similarity score is 0. The application should detect that the query vector has no non-zero entries (or that the top score is 0) and return "no results" or fall back to another method, instead of showing an arbitrary ranking.
Exercise
A teammate computes X @ X.T on a TfidfVectorizer(norm=None) matrix and calls the result cosine similarity. Why is this wrong, and what are two ways to fix it?
Show answer
With norm=None the rows are not unit length, so the dot product grows with document length and values can exceed 1. Fix it either by leaving the default norm="l2" in the vectorizer, or by calling sklearn.metrics.pairwise.cosine_similarity(X), which divides by the vector lengths itself.