Sign in

Encoding

Categorical encoding

Turns one categorical column into numbers a model can compute with, by one of five encodings.

Overview

A model multiplies and adds, so a column of labels such as red, green and blue must become numbers. The danger is that numbers carry meaning the labels never had. If red is 0, green is 1 and blue is 2, the model reads blue as twice green and green as halfway between the others. Each encoding is a different answer to that problem. One-hot gives every category its own column so no order is implied. Others replace the category by a single meaningful number, such as how common it is or what the target usually is for it.

A short history

Statisticians have written categories as 0 or 1 dummy variables in regression since the mid 1900s, and one-hot encoding is the same idea under a machine learning name. Columns with thousands of categories pushed newer methods: Daniele Micci-Barreca described smoothed target encoding in 2001, and it spread widely through data science competitions and gradient boosting libraries. No one person invented the practice as a whole.

How it works

  1. Call fit on the training column. It collects the distinct categories, sorts them, and gives each an index from 0 to K−1K - 1.
  2. It also counts how often each category appears and, for the target method, sums the target per category.
  3. Call transform. onehot writes a 1 in the category's column and 0 elsewhere. ordinal writes the index.
  4. frequency writes the share of training rows that have the category. target writes the smoothed mean of the target for the category.
  5. binary writes the bits of the index plus one, which needs only about log⁡2K\log_2 K columns.
  6. A category never seen in fit either raises an error or gets a neutral code, as handle_unknown says.
  7. Use feature_names to label the output columns, and inverse_transform to recover categories from onehot, ordinal or binary output.

Watch out for

  • Ordinal codes follow the sorted order of the labels, which is usually alphabetical and meaningless. A linear model will treat that order as real.
  • Target encoding uses the answer to build the feature. Encoding training rows with means that include their own target leaks it, and the model overfits. Fit on one fold and transform another.
  • One-hot on a column with thousands of categories makes thousands of mostly empty columns. Training slows down and rare categories get too few rows to learn from.
  • In a linear model with an intercept the full set of one-hot columns sums to 1 in every row, which makes the columns exactly dependent. Set drop_first to avoid it.
  • Frequency encoding gives two different categories the same number when they are equally common, so the model cannot tell them apart.

Use cases

When to use it

Any time a feature is a label and not a quantity. Use onehot for a handful of categories, ordinal for tree models or truly ordered labels, and frequency, target or binary when there are hundreds of categories.

In industry

Online advertising
Click prediction models encode high-cardinality fields such as site, advertiser and device with target or frequency codes, or with learned embeddings.
Credit scoring
Lenders one-hot encode fields such as employment type and loan purpose for logistic regression scorecards.
Retail forecasting
Demand models encode store, product family and promotion type so that tree models can use them.

Choosing it: what must hold

  • A column of categories, with the mapping fitted on the training data only.
  • For one-hot, a small number of categories, since each one adds a column.
  • For ordinal codes, a real order among the categories, or a tree model that does not read the codes as distances.
  • For target encoding, smoothing and out-of-fold fitting so the target does not leak into the feature.
  • A rule for categories that appear only after training.

When to choose something else

IfUse instead
The model is CatBoost or LightGBMTheir built-in categorical handling
There are very many categories and you train a neural networkA learned embedding layer
The column is free text, not a fixed set of labelsText features such as tokenisation and embeddings

Math foundations

  1. One-hot

    e(ci)=(0,…,0,1i,0,…,0)∈{0,1}Ke(c_i) = (0, \dots, 0, \underset{i}{1}, 0, \dots, 0) \in \{0, 1\}^{K}

    Category ii becomes a vector of length KK with a single 1. Every pair of categories is the same distance apart, so no order or closeness is implied.

  2. Frequency

    fc=ncnf_c = \frac{n_c}{n}

    The share of training rows with category cc. It tells the model how common the category is, in one column.

  3. Smoothed target mean

    tc=∑i: xi=cyi  +  m yˉnc+mt_c = \frac{\sum_{i:\,x_i = c} y_i \;+\; m\,\bar{y}}{n_c + m}

    The mean target of the category, pulled toward the overall mean yˉ\bar{y}. It acts as if mm extra rows with the average target were added, so small categories do not get extreme values.

  4. The same formula as a blend

    tc=ncnc+m yˉc+mnc+m yˉt_c = \frac{n_c}{n_c + m}\,\bar{y}_c + \frac{m}{n_c + m}\,\bar{y}

    A weighted average of the category mean and the overall mean. The more rows a category has, the more its own mean counts.

  5. Width of the binary encoding

    b=⌊log⁡2K⌋+1b = \lfloor \log_2 K \rfloor + 1

    The number of bits needed to write the codes 1 to KK. Code 0 is kept for an unknown category. A thousand categories need 10 columns where one-hot needs 1000.

Symbols

c, cic,\ c_i
a category, and the category with index i
KK
the number of distinct categories seen in fit
n, ncn,\ n_c
the number of training rows, and of rows with category c
yiy_i
the target value of row i
yˉ, yˉc\bar{y},\ \bar{y}_c
the mean target over all rows (prior_), and over the rows of category c
mm
the smoothing setting
fc, tcf_c,\ t_c
the frequency code and the target code of category c
bb
the number of binary columns (n_bits)

Worked by hand

The overall target mean is yˉ=0.4\bar{y} = 0.4 and smoothing is m=1m = 1. A rare category has 2 rows, both with target 1. A common category has 20 rows, all with target 1. Compute the target code of each.

trare=2+1×0.42+1=2.43=0.80t_{\text{rare}} = \frac{2 + 1 \times 0.4}{2 + 1} = \frac{2.4}{3} = 0.80
tcommon=20+1×0.420+1=20.421≈0.971t_{\text{common}} = \frac{20 + 1 \times 0.4}{20 + 1} = \frac{20.4}{21} \approx 0.971

Both categories have a raw mean of 1.0. The rare one is pulled down to 0.80 because two rows are weak evidence. The common one stays near 1.

Visual example

Loading the example.

Try this

  • Step through the five methods and watch how many columns each one writes for the same ten rows.
  • Choose target and move the smoothing m: red has only two rows, so its code moves toward the overall mean much faster than blue's.
  • Press a colour or a target in the table to change that row, and see every code that depends on it change.

Code sample

from impl import CategoricalEncoder
from config import CategoricalEncoderConfig

colours = ["red", "blue", "red", "green"]
enc = CategoricalEncoder(CategoricalEncoderConfig(method="onehot", handle_unknown="ignore")).fit(colours)
print(enc.feature_names("colour"))        # ['colour=blue', 'colour=green', 'colour=red']
print(enc.transform(["red", "purple"]))   # [[0. 0. 1.] [0. 0. 0.]]
print(enc.inverse_transform(enc.transform(colours)))   # ['red', 'blue', 'red', 'green']
Read the implementation (138 lines)
"""Categorical to numeric encoders for one column: one-hot, ordinal, frequency, target and binary.

NumPy only. `fit` learns the categories (and their frequencies or target means) from the training column,
`transform` returns a float array with one row per value, and `inverse_transform` recovers the categories for
the encodings that keep them (one-hot, ordinal, binary).
"""
from __future__ import annotations

import numpy as np

try:
    from .config import CategoricalEncoderConfig
except ImportError:  # run from the template's own folder
    from config import CategoricalEncoderConfig


class CategoricalEncoder:
    """Encoder for one categorical column.

    After `fit`: `categories_` is the sorted list of categories, `frequencies_` and `target_means_` are arrays
    of shape (n_categories,) (the latter only for "target"), `prior_` is the global target mean.
    """

    def __init__(self, config: CategoricalEncoderConfig | None = None) -> None:
        self.config = config or CategoricalEncoderConfig()
        self.categories_: list | None = None
        self.frequencies_: np.ndarray | None = None
        self.target_means_: np.ndarray | None = None
        self.prior_: float | None = None
        self._index: dict = {}

    @staticmethod
    def _values(values) -> list:
        """Column as a list of plain Python values (NumPy scalars are unwrapped so they hash like Python ones)."""
        return [v.item() if isinstance(v, np.generic) else v for v in list(values)]

    def fit(self, values, y=None) -> "CategoricalEncoder":
        """Learn the categories from `values`, a sequence of n hashable values.

        y: numeric target, shape (n,), required for "target".
        """
        values = self._values(values)
        if not values:
            raise ValueError("cannot fit an encoder on an empty column")
        try:
            self.categories_ = sorted(set(values))
        except TypeError:  # mixed types that cannot be ordered: order by type name, then text
            self.categories_ = sorted(set(values), key=lambda v: (type(v).__name__, str(v)))
        self._index = {c: i for i, c in enumerate(self.categories_)}
        codes = np.array([self._index[v] for v in values])
        counts = np.bincount(codes, minlength=len(self.categories_)).astype(float)
        self.frequencies_ = counts / counts.sum()
        if self.config.method == "target":
            if y is None:
                raise ValueError("target encoding needs y")
            y = np.asarray(y, dtype=float)
            if y.shape != (len(values),):
                raise ValueError(f"y must have shape ({len(values)},), got {y.shape}")
            self.prior_ = float(y.mean())
            sums = np.bincount(codes, weights=y, minlength=len(self.categories_))
            m = self.config.smoothing
            self.target_means_ = (sums + m * self.prior_) / (counts + m)
        return self

    @property
    def n_bits(self) -> int:
        """Number of columns of the binary encoding: bits needed for the codes 1..n_categories (0 = unknown)."""
        return max(1, int(len(self.categories_)).bit_length())

    def _codes(self, values) -> np.ndarray:
        """Category index per value, shape (n,); -1 for an unknown category when those are ignored."""
        if self.categories_ is None:
            raise RuntimeError("call fit before transform")
        values = self._values(values)
        codes = np.array([self._index.get(v, -1) for v in values], dtype=int)
        if self.config.handle_unknown == "error" and (codes < 0).any():
            unknown = sorted({str(v) for v, c in zip(values, codes) if c < 0})
            raise ValueError(f"unknown categories: {unknown}")
        return codes

    def transform(self, values) -> np.ndarray:
        """Encode n values. Returns a float array of shape (n, n_columns); see `feature_names` for the columns."""
        codes = self._codes(values)
        known = codes >= 0
        n, k = len(codes), len(self.categories_)
        method = self.config.method
        if method == "onehot":
            out = np.zeros((n, k))
            out[np.flatnonzero(known), codes[known]] = 1.0
            return out[:, 1:] if self.config.drop_first else out
        if method == "ordinal":
            return codes.astype(float)[:, None]
        if method == "frequency":
            return np.where(known, self.frequencies_[np.maximum(codes, 0)], 0.0)[:, None]
        if method == "target":
            return np.where(known, self.target_means_[np.maximum(codes, 0)], self.prior_)[:, None]
        shifted = codes + 1  # binary: 0 is kept for "unknown", categories use 1..k
        bits = self.n_bits
        return ((shifted[:, None] >> np.arange(bits - 1, -1, -1)) & 1).astype(float)

    def fit_transform(self, values, y=None) -> np.ndarray:
        """Fit on the column and return its encoding.

        For "target" this encodes the training rows with means that include their own target, which leaks a
        little; with small categories prefer fitting on one fold and transforming another.
        """
        return self.fit(values, y).transform(values)

    def inverse_transform(self, encoded) -> list:
        """Recover the categories from a one-hot, ordinal or binary encoding. Unknown rows give None."""
        if self.categories_ is None:
            raise RuntimeError("call fit before inverse_transform")
        encoded = np.asarray(encoded, dtype=float)
        method = self.config.method
        if method == "onehot":
            if self.config.drop_first:
                encoded = np.hstack([1.0 - encoded.sum(axis=1, keepdims=True), encoded])
            codes = np.where(encoded.sum(axis=1) > 0.5, encoded.argmax(axis=1), -1)
        elif method == "ordinal":
            codes = np.rint(encoded.reshape(-1)).astype(int)
        elif method == "binary":
            weights = 1 << np.arange(encoded.shape[1] - 1, -1, -1)
            codes = (np.rint(encoded).astype(int) * weights).sum(axis=1) - 1
        else:
            raise ValueError(f"{method} encoding does not keep the category and cannot be inverted")
        return [self.categories_[c] if 0 <= c < len(self.categories_) else None for c in codes]

    def feature_names(self, prefix: str = "x") -> list[str]:
        """Names of the output columns, for example ["x=blue", "x=red"] for one-hot."""
        if self.categories_ is None:
            raise RuntimeError("call fit before feature_names")
        method = self.config.method
        if method == "onehot":
            cats = self.categories_[1:] if self.config.drop_first else self.categories_
            return [f"{prefix}={c}" for c in cats]
        if method == "binary":
            return [f"{prefix}_bit{b}" for b in range(self.n_bits - 1, -1, -1)]
        return [f"{prefix}_{method}"]
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Take a column of 30 city names with 6 distinct values and a 0 or 1 target. Fit a CategoricalEncoder for each method through CategoricalEncoderConfig and print transform together with feature_names. For target, compare smoothing 0, 1 and 10 on the rarest city. Then transform a city that was not in the training column with handle_unknown set to ignore and read the neutral code of each method.

Check on learning

  1. Why does a linear model treat ordinal codes 0, 1, 2 very differently from the three one-hot columns, while a decision tree is less affected?
    A way to think about it

    A linear model multiplies the code by one weight. A tree only asks whether the code is above or below a cut. See what each can express about the middle category.

  2. A category appears once in training and its target is 1. With no smoothing, what does target encoding write for that row, and why is that a problem?
    A way to think about it

    The code would equal the row's own answer. Think about what the model learns to trust, and what the code will be for a new row of that category.

  3. Binary encoding uses far fewer columns than one-hot. What does it give up in exchange?
    A way to think about it

    Two categories whose codes share a bit share a column. Ask whether that shared 1 means anything about the categories.

  4. At prediction time a new category shows up. Compare raising an error with the neutral codes. Which would you want for a fraud model, and which for a product recommender?
    A way to think about it

    Weigh the cost of a silent, average-looking prediction against the cost of refusing to predict at all in each setting.