Sub topic 18
The Hashing Trick for Very Large Vocabularies
Prerequisites
This chapter assumes you understand tokenization, sparse vectors, TF-IDF, and the basic fit and predict pattern for classifiers. The hashing trick is useful when a vocabulary may contain millions of terms or keeps growing over time.
Hashing Text into Fixed-Size Vectors
CountVectorizer learns a vocabulary dictionary. It assigns one column to each observed token. That dictionary can become large because it must store every token and its column number.
HashingVectorizer avoids this dictionary. It sends each token through a hash function, which deterministically maps the token to one of a fixed number of columns:
column = hash(token) modulo n_featuresFor example, with n_features=8, both camera and river might map to column 3. This event is a collision. The vectorizer combines their counts in that column. Some implementations use a signed hash so that colliding terms can cancel instead of always adding.
The number of columns is chosen in advance. A larger n_features reduces collisions but uses more memory. Since hashing is deterministic, the same token reaches the same bucket in every process.
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.pipeline import make_pipeline
documents = [
"fast camera with a sharp lens",
"river camera for wildlife photos",
]
model = make_pipeline(
HashingVectorizer(
n_features=2**12,
ngram_range=(1, 2),
alternate_sign=False,
norm=None,
),
TfidfTransformer(),
)
X = model.fit_transform(documents)
print(X.shape)
print(X.nnz)HashingVectorizer is stateless. It does not learn a vocabulary, so it can transform data in batches and can process new tokens without refitting. TfidfTransformer then learns document frequencies from the training documents and applies IDF weighting. Setting alternate_sign=False makes the hashed counts easier to interpret as nonnegative values.
Limitations and Alternatives
Hashing trades interpretability for bounded memory.
| Choice | Strength | Cost |
|---|---|---|
| HashingVectorizer | Fixed memory and streaming support | Collisions and no token names |
| TfidfVectorizer | Inspectable vocabulary and IDF | Vocabulary memory and refitting |
| Word embeddings | Semantic similarity | More computation and model dependence |
The main failure modes are:
- Too few buckets create many collisions and weaken model accuracy.
- You cannot reliably recover the original token from a bucket.
- The hashing trick does not understand synonyms, negation, or word meaning.
- Hashing alone does not provide IDF values. Add
TfidfTransformerwhen distinctive terms should receive more weight.
Use HashingVectorizer for high-volume streams, distributed processing, or unpredictable vocabularies. Use TfidfVectorizer when the dataset fits in memory and feature inspection matters. Use embeddings or a transformer model when semantic similarity and word order are central to the task.
Exercise
Why might a production text system use HashingVectorizer followed by TfidfTransformer instead of TfidfVectorizer?
Show answer
HashingVectorizer keeps a fixed memory footprint and does not need a stored vocabulary, while TfidfTransformer still learns IDF weights from the training stream.