TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › Binary, Frequency and Hashing Encoding

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 kk categories Pays with
One-hot kk width
Binary ⌈log⁡2(k+1)⌉\lceil \log_2(k + 1) \rceil invented shared bits between unrelated categories
Frequency / count 1 categories with the same count become identical
Hashing mm, 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 kk categories plus a code 0 kept for "unknown", it needs

d=⌈log⁡2(k+1)⌉d = \lceil \log_2(k + 1) \rceil

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:

python · try it yourself
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 ⌈log⁡27⌉=3\lceil \log_2 7 \rceil = 3 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 ncn_c or a share nc/nn_c / n. 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.

python · try it yourself
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 hh maps each category string to one of mm columns:

column(c)=h(c) mod m\text{column}(c) = h(c) \bmod m

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 1/m1/m; with kk categories, the expected number of colliding pairs is

1m(k2)=k(k−1)2m.\frac{1}{m} \binom{k}{2} = \frac{k(k - 1)}{2m}.

scikit-learn's FeatureHasher uses MurmurHash3 and a second hash bit for the sign (+1+1 or −1-1), so collisions partly cancel instead of always adding up:

python · try it yourself
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 −1-1 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 mm much larger than kk 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 mm close to kk 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

  1. How many binary-encoding columns does a column with 1,000 categories need, keeping code 0 for unknown?
Answer

⌈log⁡2(1001)⌉=10\lceil \log_2(1001) \rceil = 10, because 29=512<1001≤1024=2102^9 = 512 < 1001 \le 1024 = 2^{10}. One-hot would need 1,000.

  1. You hash 2,000 merchant IDs into m=218=262144m = 2^{18} = 262144 columns. About how many colliding pairs do you expect?
Answer

2000⋅19992⋅262144≈7.6\frac{2000 \cdot 1999}{2 \cdot 262144} \approx 7.6 pairs, a handful of collisions among 2,000 merchants, usually harmless.

Test yourself

Why should frequency counts be computed on the training data only?

  1. They are slower on test data
  2. They are fitted parameters: computing them on the test set leaks its distribution and makes codes change between batches
  3. Test data has no categories
  4. It does not matter

What is the main downside of the hashing trick?

  1. It needs a vocabulary
  2. It cannot handle unseen categories
  3. Different categories can collide in the same column
  4. It produces one column per category

How many columns does binary encoding need for 6 categories with code 0 kept for unknown?

  1. 2
  2. 3
  3. 6
  4. 7

With k=100k = 100 categories hashed into m=100m = 100 columns, roughly how many colliding pairs do you expect?

  1. 0
  2. About 1
  3. About 50
  4. About 4950