Sign in

Encoding

Categorical and text encoding

An encoder that turns one column of categories or short texts into numbers: one-hot, ordinal, target, hashing, bag of words or TF-IDF.

Overview

Models do arithmetic, and you cannot multiply the word red by a weight. Encoding gives every category or word a numeric form. The simplest form is a row of zeros with a single one in the position of the category. Other forms trade size for information: a single index, the average label seen for that category, a position chosen by a hash, or word counts weighted by how rare each word is. Which one fits depends on how many distinct values the column has and what the model can do with them.

A short history

One-hot encoding comes from the dummy variables statisticians used in regression long before machine learning. Karen Sparck Jones introduced inverse document frequency in 1972, which became the TF-IDF weighting of text retrieval. Daniele Micci-Barreca described target encoding for high-cardinality categories in 2001, and Weinberger and colleagues analysed the hashing trick for large scale learning in 2009.

How it works

  1. Pick a method. For categories: onehot, ordinal, target or hashing. For text: count or tfidf.
  2. In fit, collect the known categories (or words), sort them and give each an output position. Values seen fewer than min_count times are treated as unknown.
  3. For target encoding, also compute the smoothed mean of the label for each category and the global mean. For TF-IDF, compute one inverse document frequency per word.
  4. In transform, map each value to its numbers: a 0/1 row, an index, a mean, a hashed position, or a row of word counts.
  5. For TF-IDF, multiply each count by the word's weight and divide the row by its length so every document has length 1.
  6. A category not seen in fit becomes an all-zero row (onehot), −1-1 (ordinal) or the global mean (target), or raises an error if handle_unknown is error.

Watch out for

  • Target encoding computed on the same rows the model trains on leaks the label into the feature, so the model looks strong in training and weaker on new data. Fit it on the training split only.
  • Ordinal encoding invents an order (blue below green below red) that a linear model will treat as real distances.
  • Hashing sends different categories to the same position when the output is narrow, and the model cannot tell them apart afterwards.
  • One-hot encoding a column with thousands of categories makes a very wide, mostly empty table that is slow to fit and easy to overfit.
  • Hashing and target encoding cannot be reversed. The template defines inverse_transform for onehot and ordinal only and raises an error for the other methods.

Use cases

When to use it

Before any model that needs numeric input. Use onehot for a handful of categories, ordinal for tree models, target or hashing when there are very many categories, and count or tfidf for short texts fed to a linear model.

In industry

Online advertising
Click prediction models see millions of distinct ad and user identifiers. Feature hashing maps them into a fixed number of columns so a linear model stays small.
Insurance and credit
Postcode or occupation has thousands of levels. Target encoding replaces each level with a smoothed average of the outcome, which suits tree and linear models.
Customer support
Short ticket texts are turned into TF-IDF vectors and fed to a linear classifier that routes each ticket to the right team.

Choosing it: what must hold

  • A column of categories or short texts that the model cannot read directly.
  • The encoder is fitted on training rows only. Target encoding in particular leaks the label if fitted on rows it later transforms.
  • A plan for values never seen in training, such as an unknown bucket.
  • For one-hot, a small number of categories, since every category adds a column.

When to choose something else

IfUse instead
The model accepts categorical columns directlyCatBoost or LightGBM with their built-in categorical handling
There are very many categories and a neural network is being trainedLearned embeddings, as in the Wide and Deep, DeepFM or Two Tower models
The text is long or meaning depends on word orderEmbeddings from a pretrained Transformer

Math foundations

  1. One-hot encoding

    e(c)k={1if c=ck0otherwise,k=1,…,Ke(c)_k = \begin{cases} 1 & \text{if } c = c_k \\ 0 & \text{otherwise} \end{cases}, \qquad k = 1, \dots, K

    A category becomes a vector with a single 1 in the position of that category. No order or distance between categories is implied.

  2. Smoothed target encoding

    μ^c=Sc+m yˉnc+m\hat{\mu}_c = \frac{S_c + m\,\bar{y}}{n_c + m}

    The mean label of category cc, pulled toward the global mean yˉ\bar{y}. A category seen often keeps its own mean, a rare one stays close to yˉ\bar{y}. The strength mm is the smoothing parameter.

  3. Feature hashing

    h(c)=CRC32⁡(c) mod Dh(c) = \operatorname{CRC32}(c) \bmod D

    The output position is computed from the category's bytes, so nothing has to be learned or stored. Two categories with the same hh collide.

  4. Inverse document frequency

    idf⁡(w)=ln⁡ ⁣1+N1+df⁡(w)+1\operatorname{idf}(w) = \ln\!\frac{1 + N}{1 + \operatorname{df}(w)} + 1

    A word that appears in every document gets weight 1, a rare word gets more. The added ones keep the weight finite and positive.

  5. TF-IDF, scaled to unit length

    vd,w=tf⁡(d,w) idf⁡(w)∑u(tf⁡(d,u) idf⁡(u))2v_{d,w} = \frac{\operatorname{tf}(d,w)\,\operatorname{idf}(w)}{\sqrt{\sum_{u} \big(\operatorname{tf}(d,u)\,\operatorname{idf}(u)\big)^{2}}}

    Each count is weighted by rarity, then the row is divided by its Euclidean length. Long and short documents become comparable.

Symbols

cc
a category value
ckc_k
the k-th known category in sorted order
KK
number of known categories
Sc, ncS_c,\, n_c
sum of the labels and number of rows of category c
yˉ\bar{y}
mean label over all training rows
mm
smoothing strength
DD
n_features, the width of the hashed output
NN
number of documents seen in fit
df⁡(w)\operatorname{df}(w)
number of documents that contain word w
tf⁡(d,w)\operatorname{tf}(d,w)
number of times word w occurs in document d
vd,wv_{d,w}
final TF-IDF value of word w in document d

Worked by hand

Fit TF-IDF on two documents, "the cat sat" and "the dog", then encode "the cat". So N=2N = 2, the word the is in 2 documents and cat is in 1.

idf⁡(the)=ln⁡1+21+2+1=1\operatorname{idf}(\text{the}) = \ln\frac{1 + 2}{1 + 2} + 1 = 1
idf⁡(cat)=ln⁡1+21+1+1=1.4055\operatorname{idf}(\text{cat}) = \ln\frac{1 + 2}{1 + 1} + 1 = 1.4055
length=12+1.40552=2.9754=1.7249\text{length} = \sqrt{1^{2} + 1.4055^{2}} = \sqrt{2.9754} = 1.7249
vthe=11.7249=0.5797,vcat=1.40551.7249=0.8148v_{\text{the}} = \frac{1}{1.7249} = 0.5797, \qquad v_{\text{cat}} = \frac{1.4055}{1.7249} = 0.8148

The rarer word cat carries more weight than the. The words dog and sat do not occur, so their entries are 0, and the row has length 1.

Visual example

Loading the example.

Try this

  • Pick tfidf: the numbers for the new text, the cat, are the ones in the worked example.
  • Pick hashing and lower D until two colours land in the same position.
  • Pick target and raise the smoothing m: every category mean is pulled toward the global mean.

Code sample

from impl import Encoder
from config import EncodingConfig

colors = ["red", "blue", "red", "green"]
onehot = Encoder(EncodingConfig(method="onehot")).fit(colors)
print(onehot.categories_)                    # ['blue', 'green', 'red']
print(onehot.transform(["red", "purple"]))   # [[0, 0, 1], [0, 0, 0]]

tfidf = Encoder(EncodingConfig(method="tfidf")).fit(["the cat sat", "the dog"])
print(tfidf.transform(["the cat"]))          # one row, unit length
Read the implementation (154 lines)
"""Encoders that turn one column of categories or texts into numbers.

NumPy only. One `Encoder` class, six methods chosen by the config:
    onehot, ordinal, target, hashing   for a column of categories (any hashable values, compared as strings)
    count, tfidf                       for a column of texts
`fit` learns the categories or the vocabulary, `transform` returns a float array of shape (n_rows, n_outputs).
"""
from __future__ import annotations

import re
import zlib
from collections import Counter

import numpy as np

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

_WORD = re.compile(r"\w+")


def tokenize(text: str, lowercase: bool = True) -> list[str]:
    """Split a text into words (runs of letters, digits and underscore)."""
    text = str(text)
    return _WORD.findall(text.lower() if lowercase else text)


def _bucket(value: str, n_features: int) -> int:
    """Stable hash bucket of a string in [0, n_features). CRC32 gives the same answer in every process."""
    return zlib.crc32(value.encode("utf-8")) % n_features


class Encoder:
    """Encode one column. See the module docstring for the methods.

    After `fit`:
        categories_  sorted list of known categories (onehot, ordinal, target) or of words (count, tfidf)
        index_       dict from category or word to its output position
        target_mean_ dict from category to its smoothed label mean (target only)
        prior_       global label mean (target only)
        idf_         shape (n_words,), inverse document frequency (tfidf only)
    """

    def __init__(self, config: EncodingConfig | None = None) -> None:
        self.config = config or EncodingConfig()
        self.categories_: list[str] = []
        self.index_: dict[str, int] = {}
        self.target_mean_: dict[str, float] = {}
        self.prior_: float = 0.0
        self.idf_: np.ndarray | None = None
        self._fitted = False

    # ----------------------------------------------------------------------------------------------- fit
    def fit(self, values, y=None) -> "Encoder":
        """Learn the encoding.

        values: sequence of length n_rows. Categories for the categorical methods, texts for count and tfidf.
        y:      sequence of n_rows numbers, required for method "target" only.
        """
        cfg = self.config
        values = [str(v) for v in values]
        if cfg.method in ("count", "tfidf"):
            doc_freq: Counter = Counter()
            for text in values:
                doc_freq.update(set(tokenize(text, cfg.lowercase)))
            self.categories_ = sorted(w for w, c in doc_freq.items() if c >= cfg.min_count)
            if cfg.method == "tfidf":
                df = np.array([doc_freq[w] for w in self.categories_], dtype=float)
                self.idf_ = np.log((1.0 + len(values)) / (1.0 + df)) + 1.0
        elif cfg.method != "hashing":
            counts = Counter(values)
            self.categories_ = sorted(c for c, k in counts.items() if k >= cfg.min_count)
            if cfg.method == "target":
                if y is None:
                    raise ValueError("target encoding needs y")
                y = np.asarray(y, dtype=float)
                if y.shape[0] != len(values):
                    raise ValueError(f"values has {len(values)} rows, y has {y.shape[0]}")
                self.prior_ = float(y.mean())
                sums: dict[str, float] = {}
                for value, label in zip(values, y):
                    sums[value] = sums.get(value, 0.0) + float(label)
                self.target_mean_ = {
                    c: (sums[c] + cfg.smoothing * self.prior_) / (counts[c] + cfg.smoothing) for c in self.categories_
                }
        self.index_ = {c: i for i, c in enumerate(self.categories_)}
        self._fitted = True
        return self

    # ----------------------------------------------------------------------------------------- transform
    def transform(self, values) -> np.ndarray:
        """Encode `values` (length n_rows). Returns a float array of shape (n_rows, n_outputs)."""
        if not self._fitted:
            raise RuntimeError("call fit before transform")
        cfg = self.config
        values = [str(v) for v in values]
        n = len(values)
        if cfg.method == "hashing":
            out = np.zeros((n, cfg.n_features))
            for i, value in enumerate(values):
                out[i, _bucket(value, cfg.n_features)] = 1.0
            return out
        if cfg.method in ("count", "tfidf"):
            out = np.zeros((n, len(self.categories_)))
            for i, text in enumerate(values):
                for word in tokenize(text, cfg.lowercase):
                    j = self.index_.get(word)
                    if j is not None:  # words outside the vocabulary are dropped, as in any bag of words
                        out[i, j] += 1.0
            if cfg.method == "tfidf":
                out = out * self.idf_
                norms = np.linalg.norm(out, axis=1, keepdims=True)
                out = out / np.where(norms == 0.0, 1.0, norms)
            return out

        unknown = [v for v in values if v not in self.index_]
        if unknown and cfg.handle_unknown == "error":
            raise ValueError(f"unknown categories: {sorted(set(unknown))}")
        if cfg.method == "onehot":
            out = np.zeros((n, len(self.categories_)))
            for i, value in enumerate(values):
                j = self.index_.get(value)
                if j is not None:
                    out[i, j] = 1.0
            return out
        if cfg.method == "ordinal":
            return np.array([[float(self.index_.get(v, -1))] for v in values]).reshape(n, 1)
        return np.array([[self.target_mean_.get(v, self.prior_)] for v in values]).reshape(n, 1)

    def fit_transform(self, values, y=None) -> np.ndarray:
        """`fit(values, y)` then `transform(values)`."""
        return self.fit(values, y).transform(values)

    def inverse_transform(self, encoded) -> list:
        """Map onehot or ordinal output back to categories. Unknown rows come back as None."""
        if self.config.method not in ("onehot", "ordinal"):
            raise ValueError("inverse_transform is defined for onehot and ordinal only")
        encoded = np.asarray(encoded, dtype=float)
        if self.config.method == "ordinal":
            codes = encoded.reshape(-1).astype(int)
        else:
            codes = np.where(encoded.sum(axis=1) > 0, encoded.argmax(axis=1), -1)
        return [self.categories_[c] if c >= 0 else None for c in codes]

    def feature_names(self, prefix: str = "x") -> list[str]:
        """Names of the output columns, for example ["color=blue", "color=red"] with prefix "color"."""
        method = self.config.method
        if method == "hashing":
            return [f"{prefix}#{i}" for i in range(self.config.n_features)]
        if method in ("ordinal", "target"):
            return [f"{prefix}_{method}"]
        return [f"{prefix}={c}" for c in self.categories_]
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Fit Encoder(EncodingConfig(method="target", smoothing=1.0)) on a color column with a 0/1 label where one color appears only once. Print target_mean_ and prior_, then refit with smoothing 0 and 10 and describe how the rare color's value moves.

Check on learning

  1. A category appears once in training and its single label is 1. Without smoothing its target encoding is 1.0. Why is that a problem, and what does the smoothing term do about it?
    A way to think about it

    Ask how much evidence one row is. Then set nc=1n_c = 1 in the formula and watch the value slide toward yˉ\bar{y} as mm grows.

  2. You hash 10,000 categories into 16 positions. What does the model lose, and why might hashing into 4,096 positions still beat a one-hot table?
    A way to think about it

    Count how many categories share a position in each case. Then compare the memory and the handling of categories that only appear after training.

  3. A linear model receives a color column as ordinal codes 0, 1, 2. What false statement about the colors is the model now forced to make?
    A way to think about it

    Write the model's contribution as weight times code. The step from the first color to the second must equal the step from the second to the third.

  4. In TF-IDF, why is a word that appears in every document nearly useless for telling documents apart, and how does the formula reflect that?
    A way to think about it

    Set df⁡(w)=N\operatorname{df}(w) = N and compare the result with a word that occurs in one document. Think about what the row scaling does next.

  5. At serving time a new category appears that was never seen in fit. Compare what each method does with it and say which behaviour is safest for your model.
    A way to think about it

    List the outputs: an all-zero row, −1-1, the global mean, a hashed position. For each, ask whether the model has ever seen that input pattern during training.