Sub topic 18
The hashing trick for very large vocabularies
This chapter assumes you know CountVectorizer and TfidfVectorizer, how a document-term matrix is stored as a sparse matrix, and how fit and predict work in a scikit-learn pipeline. You also need to be comfortable with modulo arithmetic.
The problem with a stored vocabulary
CountVectorizer builds a dictionary that maps each term to a column index. That dictionary causes three problems at scale:
- Memory. With word n-grams on a large corpus, the dictionary can hold tens of millions of strings. It can take more memory than the sparse matrix itself.
- Two passes.
fitmust read the whole corpus to build the vocabulary beforetransformcan produce any features. That rules out streaming data. - Hard to parallelize. Every worker needs the same dictionary, or each worker's columns mean something different.
The hashing trick removes the dictionary. It computes a column index directly from the token text.
How hashing replaces the dictionary
A hash function turns any string into an integer. To pick a column, take that integer modulo n_features, which is a size you choose. The same token always lands in the same column, on every machine and in every run. Nothing needs to be learned or stored.
scikit-learn uses the 32-bit MurmurHash3 function. It also uses a second bit of the hash as a sign (+1 or -1) for reasons explained below.
The code below uses a deliberately small n_features. With alternate_sign=False and norm=None, each cell holds a plain count, so each row sums to the number of tokens in the document.
from sklearn.feature_extraction.text import HashingVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = HashingVectorizer(n_features=16, alternate_sign=False, norm=None)
X = vec.transform(docs)
print(X.shape)
print(X.toarray().sum(axis=1))The shape is (3, 16), and the row sums are [6. 6. 5.]. There is no fit call and no get_feature_names_out. The vectorizer is stateless, so fit does nothing and exists only for pipeline compatibility.
Collisions
Two different tokens can map to the same column. This is a collision. The pigeonhole principle guarantees one whenever there are more distinct tokens than columns. The next snippet puts the eight words of our toy vocabulary into four columns.
from sklearn.feature_extraction.text import HashingVectorizer
words = ["cat", "chased", "dog", "log", "mat", "on", "sat", "the"]
vec = HashingVectorizer(n_features=4, alternate_sign=False, norm=None)
cols = [int(vec.transform([w]).nonzero()[1][0]) for w in words]
print(dict(zip(words, cols)))Every column index is between 0 and 3, so at least two words share a column. After a collision the model cannot tell which word produced a count. The two words' counts are added together.
Collisions do less damage than they first seem to, for two reasons:
- Most real vocabularies are dominated by rare terms. A rare term that collides with another rare term adds a little noise to one column.
- A linear model can usually still learn useful weights. A frequent, informative term outweighs the rare terms that share its column.
The alternate_sign option
By default HashingVectorizer uses alternate_sign=True. Each token is added as +1 or -1, depending on a second hash bit. When two tokens collide, their contributions tend to cancel instead of accumulating. The expected value of the inner product between two documents then stays unbiased. The cost is that cells can be negative.
Two consequences follow:
- Negative values break models that require non-negative input, such as
MultinomialNB. Setalternate_sign=Falsefor those. - Signed counts do not combine meaningfully with IDF weighting. The usual choice when you want TF-IDF is
alternate_sign=False.
Choosing n_features
Use a power of two, such as 2**18 or 2**20. The default is 2**20, which is about one million columns. A larger value gives fewer collisions. It also makes the coefficient vector of a linear model larger, because that vector has one entry per column. The sparse matrix itself barely grows, because it stores only nonzero cells.
A practical way to choose is to try 2**16, 2**18 and 2**20 and compare validation scores. If the score stops improving, the extra columns are not helping.
Getting TF-IDF from hashed features
HashingVectorizer has no IDF, because IDF needs document frequencies counted over a corpus. You can add it afterward with TfidfTransformer. That step does need a fit pass to count document frequencies per hashed column. It is much cheaper than building a string vocabulary, because the columns are plain integers.
from sklearn.feature_extraction.text import HashingVectorizer, TfidfTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
train_texts = [
"great movie, loved it",
"wonderful acting and a great story",
"terrible plot and bad acting",
"boring, bad and far too long",
]
train_labels = [1, 1, 0, 0]
model = make_pipeline(
HashingVectorizer(
n_features=2**18,
alternate_sign=False,
norm=None,
ngram_range=(1, 2),
),
TfidfTransformer(sublinear_tf=True),
LogisticRegression(max_iter=1000),
)
model.fit(train_texts, train_labels)
print(model.predict(["loved the acting"]))Here norm=None in the vectorizer leaves normalization to TfidfTransformer, which applies L2 normalization by default. The pipeline prints one predicted label. The tiny training set makes it only a demonstration.
Streaming with partial_fit
The main use of hashing is out-of-core learning, where the data does not fit in memory. Because the feature space is fixed in advance, you can transform one batch at a time and update a model incrementally. Use a classifier that supports partial_fit, such as SGDClassifier.
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
vec = HashingVectorizer(n_features=2**20)
clf = SGDClassifier(loss="log_loss", random_state=0)
classes = [0, 1]
batches = [
(["great movie, loved it", "terrible plot and bad acting"], [1, 0]),
(["wonderful acting and a great story", "boring, bad and far too long"], [1, 0]),
]
for texts, labels in batches:
clf.partial_fit(vec.transform(texts), labels, classes=classes)
print(clf.predict(vec.transform(["loved the acting"])))Pass classes on every call, or at least the first. The model cannot know labels that have not appeared in the first batch. Here the default alternate_sign=True and norm="l2" are fine, because no IDF is applied.
Trade-offs
| Aspect | CountVectorizer / TfidfVectorizer | HashingVectorizer |
|---|---|---|
| Memory for vocabulary | Grows with the number of distinct terms | None |
| Passes over data | `fit` plus `transform` | `transform` only |
| Streaming and `partial_fit` | Hard | Natural |
| Inspect which words matter | Yes, by column name | No, the hash cannot be inverted |
| Collisions | None | Yes |
| IDF | Built in with `TfidfVectorizer` | Needs `TfidfTransformer` |
| `min_df`, `max_df`, `max_features` | Available | Not available |
Common errors
- Trying to read feature names.
HashingVectorizerhas noget_feature_names_out. If you need to explain predictions, use a stored vocabulary instead. - Expecting pruning options. There is no
min_dformax_df, because nothing counts documents. Rare terms stay in and take up hash space. - Using negative values with the wrong model. The default signed output fails in
MultinomialNB. Setalternate_sign=False. - Changing
n_featuresor the token settings between training and prediction. The same text then lands in different columns, and the trained weights no longer line up. Fix these settings in one pipeline object. - Setting
n_featurestoo small. Scores drop quietly, with no error. Compare several sizes on validation data.
Exercise
You train a classifier on HashingVectorizer(n_features=2**18, alternate_sign=False) features, then add TF-IDF weighting. Which scikit-learn class do you add, and why can it not be part of the vectorizer? Also name one reason to prefer TfidfVectorizer if the corpus fits in memory.
Show answer
Add TfidfTransformer after the vectorizer. IDF needs document frequencies counted over a corpus, and HashingVectorizer is stateless, so it keeps no counts. TfidfTransformer learns them per hashed column in fit. With a corpus that fits in memory, TfidfVectorizer has no collisions and gives column names you can inspect, and it supports min_df, max_df and max_features.