Feature hashing, also called the hashing trick, is a technique in machine learning that converts raw features such as words, categories or identifiers into indices of a fixed-length vector by applying a hash function, instead of looking them up in a stored dictionary. Each feature name is hashed to a bucket, and its value is added to that position, so the model input has a predictable size no matter how many distinct features appear.
The method is valued for very high-dimensional, sparse data, such as text, click logs and categorical variables with millions of levels. It trades a small, controllable amount of accuracy, caused by hash collisions, for constant memory, fast streaming processing and the ability to handle unseen feature values without retraining an encoder.
How feature hashing maps features to vector indices
Feature hashing works by computing a hash of each feature name and taking the result modulo the chosen vector size. For a vector of size m, a feature such as the token “invoice” or the pair “country=DE” receives the index h(name) mod m, and its value, often 1 for presence or a count, is added to that index.
Most implementations also use a second, signed hash that multiplies each value by +1 or -1. This sign trick, described by Weinberger and colleagues in 2009, makes collisions cancel out on average, so the hashed inner product is an unbiased estimate of the original inner product. Popular libraries use fast non-cryptographic functions such as MurmurHash3.
The process needs no fitting step: the transformer is stateless, which is why it suits streaming data and distributed pipelines. The table below shows the parameters that control its behavior.
| Parameter | Typical setting | What it controls |
|---|---|---|
| Number of buckets | 2^18 to 2^24 | Vector length and collision rate |
| Hash function | MurmurHash3, 32-bit | Speed and distribution of indices |
| Signed hashing | Enabled | Cancellation of collision bias |
| Input type | Tokens, pairs or dictionaries | How feature names are formed |
| Value normalization | None, binary or TF-IDF | Scale of hashed values |
Hash collisions and choosing the vector size
A hash collision occurs when two different features land in the same bucket, so the model cannot distinguish them. With n distinct active features and m buckets, the expected share of colliding features is roughly n divided by m when n is much smaller than m, which is why the bucket count is usually set several times larger than the expected number of distinct features.
In practice, collisions hurt less than intuition suggests. Rare features tend to collide with other rare features, and regularized linear models spread weight across many inputs, so the accuracy loss is often well below one percentage point at adequate sizes. The table below gives indicative guidance; the exact effect depends on the data and model.
| Buckets | Distinct features | Approximate colliding share | Typical use |
|---|---|---|---|
| 2^16 (65,536) | 100,000 | High, often over half | Prototyping only |
| 2^20 (about 1 million) | 100,000 | Around 10 percent | Text classification |
| 2^22 (about 4 million) | 100,000 | Around 2 to 3 percent | Production linear models |
| 2^24 (about 16 million) | 1,000,000 | Around 6 percent | Large click-through models |
A useful rule is to double the bucket count and measure validation loss; when the improvement becomes negligible, the size is sufficient. Larger vectors raise memory for the model weights, not for the input, because hashed vectors remain sparse.
Feature hashing compared with other encodings
Feature hashing is one of several ways to turn categorical or textual data into numbers, and the right choice depends on cardinality, interpretability and data drift. It differs from one-hot encoding mainly in that it does not store a vocabulary.
| Method | Stored state | Handles unseen values | Interpretability |
|---|---|---|---|
| One-hot encoding | Full vocabulary | No, needs refit or an unknown bucket | High |
| Feature hashing | None | Yes, automatically | Low, buckets are shared |
| Target encoding | Per-category statistics | Falls back to a prior | Moderate, risk of leakage |
| Label encoding | Category-to-integer map | No | Moderate, implies order |
| Learned embeddings | Trained vector table | Needs an unknown token | Low |
Hashing also combines well with feature crosses. Pairs such as “user_region x ad_category” can be hashed directly, which avoids materializing a quadratic vocabulary and is a common pattern in online learning for advertising.
When to use feature hashing in practice
Feature hashing is most useful when the feature space is huge or open-ended and memory or latency matters more than inspecting individual weights. It is supported in mainstream tools, for example the HashingVectorizer and FeatureHasher classes in scikit-learn and the hashing options in Vowpal Wabbit.
| Situation | Recommendation | Reason |
|---|---|---|
| Streaming text or logs | Use hashing | No vocabulary pass is needed |
| Millions of category levels | Use hashing | Memory stays fixed |
| Need to explain each weight | Prefer one-hot encoding | Buckets mix several features |
| Small, stable category set | Prefer one-hot encoding | Collisions add needless noise |
| Tree models on few categories | Prefer label or target encoding | Trees split poorly on sparse hashes |
Limitations and common mistakes
The main costs of feature hashing are lost interpretability and the difficulty of reversing the mapping. Several mistakes recur in practice.
- Too few buckets: small vectors cause heavy collisions and degrade accuracy silently.
- Inconsistent hashing: training and serving must use the same hash function, seed and size, or predictions break.
- Expecting inverse lookup: a bucket cannot be traced back to one feature unless names are logged separately.
- Ignoring namespaces: identical strings from different fields should be prefixed, such as “title:apple”, to avoid unwanted merging.
- Treating it as privacy protection: hashing is not anonymization, because common values can be recovered by hashing candidates.
A non-technical view
Imagine sorting mail into a fixed number of numbered boxes. Instead of keeping a long list of every name, you use a simple rule that turns each name into a box number. The same name always goes to the same box.
Feature hashing does this with data. It puts words or categories into a fixed number of slots for a computer model. Sometimes two names share a box. That causes a little confusion, but it saves a great deal of memory and work.
A concrete example
An online retailer filters spam from millions of product reviews each day. New words, misspellings and product codes appear constantly, so maintaining a vocabulary would require frequent rebuilds. The data team instead hashes word unigrams and bigrams into 2^22 buckets with signed MurmurHash3 and trains a logistic regression model on the result.
The hashed pipeline runs in a streaming job and never needs a vocabulary refresh. Compared with a one-hot baseline built from a monthly vocabulary, validation accuracy differs by less than 0.3 percentage points, while model memory stays fixed at about 16 megabytes of weights. When slang or new product names appear, the filter handles them immediately, and the team retrains weekly simply to update the weights.