Sub topic 11
Normalizing document vectors
This chapter assumes you can read a TF-IDF matrix, know what a NumPy vector norm is, and have used TfidfVectorizer once. It explains the last step of the TF-IDF recipe: scaling each document vector to length 1.
Why raw weights are not comparable across documents
After counts are multiplied by IDF, long documents still have larger weights than short ones. A document that repeats the same text twice gets every weight doubled. Its words are the same, but a distance or a dot product treats it as a different document.
L2 normalization fixes this by dividing each row by its Euclidean length (its L2 norm):
x_normalized = x / sqrt(x1^2 + x2^2 + ... + xn^2)Every row then has length exactly 1. Only the direction of the vector is kept, which is the relative mix of terms. The length, which mostly reflects document size, is discarded.
Where it sits in the pipeline
TfidfVectorizer applies normalization last, after the term weights are computed.
The order matters. If you normalized the counts first and applied IDF afterward, the rows would no longer have length 1.
A worked example
Use the three-document corpus from earlier chapters:
- "the cat sat on the mat"
- "the dog sat on the log"
- "the cat chased the dog"
The vocabulary is cat, chased, dog, log, mat, on, sat, the. With scikit-learn's smooth IDF, the first document has these weights before normalization:
| Term | Count | IDF | Count × IDF |
|---|---|---|---|
| cat | 1 | 1.288 | 1.288 |
| mat | 1 | 1.693 | 1.693 |
| on | 1 | 1.288 | 1.288 |
| sat | 1 | 1.288 | 1.288 |
| the | 2 | 1.000 | 2.000 |
The sum of squares is 1.288² × 3 + 1.693² + 2.000² ≈ 11.841, so the L2 norm is about 3.441. Dividing each weight by 3.441 gives cat 0.374, mat 0.492, on 0.374, sat 0.374 and the 0.581. The squares of these values add up to 1.
You can check this in code by turning normalization off and on:
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
raw = TfidfVectorizer(norm=None).fit_transform(docs).toarray()
unit = TfidfVectorizer(norm="l2").fit_transform(docs).toarray()
print(np.linalg.norm(raw, axis=1).round(3))
print(np.linalg.norm(unit, axis=1).round(3))
print(raw[0].round(3))
print(unit[0].round(3))The first line prints the raw row lengths, [3.441 3.441 3.191]. The second prints [1. 1. 1.]. The last two lines show document 1 before and after scaling, in the column order cat, chased, dog, log, mat, on, sat, the.
Normalization removes the length effect
The next example makes the effect concrete. The second document is the first one repeated twice.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import normalize
docs = [
"the cat sat on the mat",
"the cat sat on the mat the cat sat on the mat",
]
X = CountVectorizer().fit_transform(docs)
before = np.linalg.norm((X[0] - X[1]).toarray())
Xn = normalize(X, norm="l2")
after = np.linalg.norm((Xn[0] - Xn[1]).toarray())
print(round(before, 3), round(after, 3))This prints 2.828 0.0. On raw counts the two documents are 2.828 apart. After normalization they are the same point. CountVectorizer has no norm argument, so the example calls sklearn.preprocessing.normalize. It accepts sparse matrices and keeps them sparse.
Why normalized vectors make similarity simple
For two unit-length vectors, the dot product equals the cosine of the angle between them. The squared Euclidean distance is also a function of the cosine:
distance^2 = 2 - 2 * cosineThis has three practical consequences:
- A single sparse matrix product,
X @ X.T, gives all pairwise cosine similarities. - Nearest neighbors by Euclidean distance and by cosine produce the same ranking.
- Linear models see inputs on a comparable scale, so a long document does not dominate the loss.
For documents 1 and 3 the shared terms are cat and the. The dot product is about 0.374 × 0.404 + 0.581 × 0.627 ≈ 0.52. That is the similarity you get from cosine_similarity on this matrix.
Choosing a norm
TfidfVectorizer accepts norm="l2" (the default), "l1" or None.
| Setting | Row property | Typical use |
|---|---|---|
| `"l2"` | Squares sum to 1 | Cosine similarity, linear models, SVMs, k-nearest neighbors |
| `"l1"` | Absolute values sum to 1 | Treating each row as a distribution over terms |
| `None` | Weights unchanged | Models that need counts or length, or custom scaling later |
Keep the default unless you have a reason to change it. With norm=None, document length reaches the model directly, which can help when length is itself a signal, such as spam that is unusually short.
Edge cases and common errors
- Empty rows stay zero. A document with no in-vocabulary terms has norm 0. scikit-learn leaves the row as all zeros and does not divide by zero. At prediction time this happens for text that shares no vocabulary with the training set. Such rows have cosine similarity 0 with everything.
- Pruning changes the norms. The norm is taken over the columns that survive
min_df,max_df,max_featuresandstop_words. Changing these settings changes every weight in a row, including terms you kept. - Normalizing twice does nothing harmful. A row that already has length 1 is unchanged. But normalizing a
TfidfVectorizeroutput withnorm="l1"afterward gives a different, non-TF-IDF scale. Pick one on purpose. - Do not use L2-normalized TF-IDF with models that expect counts.
MultinomialNBis designed for counts, though it often works acceptably with TF-IDF. Test it before relying on it. - Length is lost. Two documents with different lengths but the same term proportions become identical rows. If length matters for your task, add it back as a separate feature, for example the log of the token count.
- Normalization does not fix IDF leakage. The row scaling is per document. The IDF values are learned from data, so you still need to fit the vectorizer on the training set only.
Exercises
Exercise
A TF-IDF row before normalization is [3, 4, 0]. What is its L2 norm, and what is the normalized row? What is the L1-normalized row?
Show answer
The L2 norm is sqrt(3² + 4² + 0²) = 5, so the normalized row is [0.6, 0.8, 0]. The squares 0.36 + 0.64 sum to 1. The L1 norm is 3 + 4 = 7, so the L1-normalized row is [3/7, 4/7, 0], about [0.429, 0.571, 0].
Exercise
You build TfidfVectorizer(norm=None) and feed its output to a k-nearest-neighbors search with Euclidean distance. A very long document keeps appearing as nobody's close neighbor. Why, and what is the smallest change that fixes it?
Show answer
Without normalization, a long document has large weights, so its vector lies far from the origin and from shorter documents even when the term proportions match. Euclidean distance reflects that length. Use the default norm="l2", or apply sklearn.preprocessing.normalize to the matrix, so that distance depends on direction only.