Binary, Frequency and Hashing Encoding
One-hot encoding is the honest default for categories, but it grows one column per category. A zip_code column with 8,000 values, a device_model column with 20,000, a merchant_id with a million: one-hot turns each into a matrix that is huge, almost empty and full of categories seen once. This lesson covers three encoders that keep the number of columns small: binary, frequency/count and hashing encoding. Each pays for the compression in a different way.
| Encoder | Columns for categories | Pays with |
|---|---|---|
| One-hot | width | |
| Binary | invented shared bits between unrelated categories | |
| Frequency / count | 1 | categories with the same count become identical |
| Hashing | , chosen by you, fixed | collisions: unrelated categories share a column |
Binary encoding
Binary encoding first gives each category an integer code (as an ordinal encoder does), then writes that code in base 2, one column per bit. With categories plus a code 0 kept for "unknown", it needs
columns: 7 columns for 100 categories, 14 for 10,000. The popular category_encoders package has a BinaryEncoder, but it is not available in the browser and the idea fits in a few lines of NumPy:
import numpy as np
def fit_binary(values):
cats = np.unique(values) # learned on training data
codes = {str(c): i + 1 for i, c in enumerate(cats)} # 0 is kept for unknown
width = int(np.ceil(np.log2(len(cats) + 1)))
return codes, width
def transform_binary(values, codes, width):
ints = np.array([codes.get(v, 0) for v in values])
bits = (ints[:, None] >> np.arange(width - 1, -1, -1)) & 1
return bits
train = np.array(["bus", "car", "bike", "train", "walk", "car", "tram"])
codes, width = fit_binary(train)
print("codes:", codes, "width:", width)
print(transform_binary(np.array(["bike", "car", "walk", "boat"]), codes, width))codes: {'bike': 1, 'bus': 2, 'car': 3, 'train': 4, 'tram': 5, 'walk': 6} width: 3
[[0 0 1]
[0 1 1]
[1 1 0]
[0 0 0]]
Six travel modes need columns instead of 6. bike has code 1 (001), car code 3 (011), walk code 6 (110), and the unseen boat gets code 0, all zeros.
The bits are shared between categories that have nothing in common: bike and car both have their last bit set only because of where they fell in the alphabet. A linear model sees those shared bits as similarity. Trees cope better, because several splits on the bits can isolate one category. Binary encoding is a compromise for tree models on medium-cardinality columns, rarely a first choice.
Frequency and count encoding
Replace each category by how often it occurs in the training data, as a count or a share . The single resulting column says "common or rare", which is often informative: a rare browser or a rare merchant can signal fraud, a popular product sells differently from a niche one.
import pandas as pd
train = pd.DataFrame({"browser": ["chrome"] * 6 + ["firefox"] * 3 + ["safari"] * 3 + ["opera", "lynx"]})
test = pd.DataFrame({"browser": ["chrome", "safari", "lynx", "netsurf"]})
counts = train["browser"].value_counts() # fitted on train only
freq = counts / len(train)
test["count"] = test["browser"].map(counts).fillna(0).astype(int)
test["freq"] = test["browser"].map(freq).fillna(0).round(3)
print(counts.to_dict())
print(test){'chrome': 6, 'firefox': 3, 'safari': 3, 'opera': 1, 'lynx': 1}
browser count freq
0 chrome 6 0.429
1 safari 3 0.214
2 lynx 1 0.071
3 netsurf 0 0.000
chrome becomes 6 (a share of 0.429 of the 14 training rows), lynx 1, and netsurf, never seen in training, 0. firefox and safari both have count 3, so this encoding cannot tell them apart: frequency encoding is often used next to another encoding, not instead of it.
Two rules make it safe. The counts are computed on the training data and stored, like a scaler's mean; recomputing them on a test batch would make the same category mean different things in different batches. And unseen categories need a value: 0 (it is, after all, rare) is the natural choice.
scikit-learn has no built-in count encoder, so inside a pipeline it is a small custom transformer whose fit stores the table and whose transform does the lookup; Pipelines, ColumnTransformer and FunctionTransformer shows how such transformers plug in.
Hashing encoding
The hashing trick skips the category list entirely. A hash function maps each category string to one of columns:
No vocabulary is stored, so the encoder needs no fitting, handles unseen categories automatically, uses a fixed memory and works on a stream. The price is collisions: two different categories can land in the same column. For a pair of categories, the chance is ; with categories, the expected number of colliding pairs is
scikit-learn's FeatureHasher uses MurmurHash3 and a second hash bit for the sign ( or ), so collisions partly cancel instead of always adding up:
import numpy as np
from sklearn.feature_extraction import FeatureHasher
shops = [f"shop_{i}" for i in range(50)]
hasher = FeatureHasher(n_features=64, input_type="string")
X = hasher.transform([[s] for s in shops]).toarray()
cols = np.argmax(np.abs(X), axis=1)
used, per_col = np.unique(cols, return_counts=True)
print("columns used:", len(used), "of 64")
print("columns shared by 2 or more shops:", int((per_col > 1).sum()))
pairs = sum(int(c) * (int(c) - 1) // 2 for c in per_col)
print("colliding pairs:", pairs, "expected about", round(50 * 49 / (2 * 64), 1))
print("first row nonzeros:", {int(j): int(X[0, j]) for j in np.flatnonzero(X[0])})
print("unseen value works too:", int(np.abs(hasher.transform([["shop_new"]]).toarray()).sum()))columns used: 36 of 64
columns shared by 2 or more shops: 14
colliding pairs: 14 expected about 19.1
first row nonzeros: {32: -1}
unseen value works too: 1
The 50 shops landed in 36 of the 64 columns; 14 columns hold two or more shops, giving 14 colliding pairs, near the 19.1 the formula predicts for this size (the exact count depends on the hash values). The first shop's single nonzero entry is in column 32: the sign bit at work. An unseen shop also gets exactly one nonzero entry, with no refitting.
Hashing is the standard tool for very high-cardinality and open-ended inputs: words in text, URLs, user agents, item IDs in online learning. Choose much larger than when collisions hurt, and remember that a hashed column cannot be explained ("column 17 = which shop?") without re-hashing the known categories.
Choosing among them
- Few categories (up to a few dozen): one-hot.
- Ordered categories: ordinal encoding with an explicit order (previous lesson).
- Many categories, rarity matters: frequency/count, often next to another encoding.
- Many categories, the category's own effect matters: target encoding inside folds or learned embeddings.
- Huge or unbounded vocabularies, streaming: hashing.
- Tree models on medium cardinality: binary or ordinal codes are acceptable.
Pitfalls
- Counts from all the data: frequency tables are fitted parameters; compute them on the training part only.
- Collisions ignored: with close to many categories share columns; check the expected collisions.
- Binary bits in a linear model: shared bits invent similarity between unrelated categories.
- Ties in frequency encoding: two categories with the same count become indistinguishable; add another encoding if their difference matters.
Practice
- How many binary-encoding columns does a column with 1,000 categories need, keeping code 0 for unknown?
Answer
, because . One-hot would need 1,000.
- You hash 2,000 merchant IDs into columns. About how many colliding pairs do you expect?
Answer
pairs, a handful of collisions among 2,000 merchants, usually harmless.
Test yourself
Why should frequency counts be computed on the training data only?
- They are slower on test data
- They are fitted parameters: computing them on the test set leaks its distribution and makes codes change between batches
- Test data has no categories
- It does not matter
What is the main downside of the hashing trick?
- It needs a vocabulary
- It cannot handle unseen categories
- Different categories can collide in the same column
- It produces one column per category
How many columns does binary encoding need for 6 categories with code 0 kept for unknown?
- 2
- 3
- 6
- 7
With categories hashed into columns, roughly how many colliding pairs do you expect?
- 0
- About 1
- About 50
- About 4950