Sub topic 11
Normalizing Document Vectors
Prerequisites and purpose
This chapter assumes that you know basic Python, NumPy vectors, logarithms, and the idea of fitting and predicting with a classifier. It also assumes that you have seen a document-term matrix and TF-IDF weights.
A document vector can contain large values simply because a document is long or a term appears many times. Normalization rescales the vector so that its size does not dominate comparisons. This lets similarity measures focus more on the direction of a vector than on its raw length.
L2 normalization
The most common choice is L2 normalization. The L2 norm is the Euclidean length of a vector:
\lVert x\rVert_2 = \sqrt{x_1^2 + x_2^2 + \cdots + x_n^2}To normalize a vector, divide every value by its L2 norm:
\hat{x} = \frac{x}{\lVert x\rVert_2}For example, take the vector [3, 4]:
\lVert x\rVert_2 = \sqrt{3^2 + 4^2} = 5The normalized vector is:
\hat{x} = [3/5, 4/5] = [0.6, 0.8]Its length is now 1. The values changed, but the vector points in the same direction.
import numpy as np
x = np.array([3.0, 4.0])
length = np.linalg.norm(x)
normalized = x / length
print(length)
print(normalized)
print(np.linalg.norm(normalized))A document-term matrix is normalized row by row. Each row represents one document, so every document receives its own norm. A zero row needs special handling because division by zero is undefined. This can happen when preprocessing removes every token from a document.
Why normalization matters for similarity
Cosine similarity compares the angle between two vectors:
\cos(\theta) = \frac{x \cdot y}{\lVert x\rVert_2\lVert y\rVert_2}After both vectors have L2 norm 1, this becomes:
\cos(\theta) = x \cdot yTherefore, normalized TF-IDF rows make cosine similarity efficient. A longer document does not automatically appear more similar merely because it contains more tokens.
TfidfVectorizer uses L2 row normalization by default. You can inspect or change this behavior with the norm parameter.
from sklearn.feature_extraction.text import TfidfVectorizer
docs = ["cat sat", "cat sat sat", "dog ran"]
vec = TfidfVectorizer(norm="l2")
X = vec.fit_transform(docs)
print(X.toarray().round(3))
print((X.multiply(X).sum(axis=1)).A1.round(3))The second output contains approximately 1.0 for each nonzero row. Use norm=None when you need unnormalized TF-IDF values for a specific model or analysis. Make that choice deliberately because downstream comparisons can change.
Exercise
Normalize the vector [1, 2, 2] using the L2 norm. What is the approximate result?
Show answer
Its norm is sqrt(1 + 4 + 4) = 3, so the normalized vector is approximately [0.333, 0.667, 0.667].