A Persistent Label Encoder for Training and Inference

Save your label encodings at training time, reuse them at inference, and map unseen categories to Unknown instead of crashing.
Machine Learning
Author
Published

February 11, 2022

Label encoding looks like the easiest preprocessing step there is. Turn each category into a number, train the model, done. It gets tricky once the model leaves the notebook and has to make predictions on new data.

This is a small helper I wrote to deal with that, and I’ve reused it in most tabular projects since.

Code: Zilch123/Persistent-Label-Encoder

The problem

scikit-learn’s LabelEncoder assigns numbers in sorted order of the values it sees:

from sklearn.preprocessing import LabelEncoder

LabelEncoder().fit_transform(["Riga", "Paris", "Oslo"])   # [2, 1, 0]

Three things go wrong at inference time:

  1. Refitting changes the numbers. If you fit a new encoder on the inference data, “Riga” might become 1 instead of 2. The model was trained on 2, so its predictions are now quietly wrong, with no error to warn you.
  2. New categories crash. If you reuse the training encoder, any value it hasn’t seen (“Tokyo”) raises ValueError: y contains previously unseen labels. In production, new categories always turn up eventually.
  3. Nulls crash too. A missing value at inference is just another unseen label.

What we want is to fit once, save the mapping, and reuse it, with a safe fallback for anything new.

The idea

  • At training time, add an extra Unknown class to every column before fitting.
  • Save the classes for each column in a plain dict, and pickle it with the model.
  • At inference, load the dict, and replace anything not in the saved classes (including nulls) with Unknown before encoding.

Saving the classes as a plain dict of lists, rather than pickling the encoder objects, keeps the saved file simple and readable.

The code

This is a tidied version of the code in the repo.

import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder

UNKNOWN = 'Unknown'


def _as_labels(series):
    """Nulls become Unknown, everything else a string (10 and 10.0 both become '10')."""
    def to_label(v):
        if pd.isna(v):
            return UNKNOWN
        if isinstance(v, float) and v.is_integer():
            return str(int(v))
        return str(v)
    return series.map(to_label)


def fit(df, categorical_features):
    """Fit one label encoder per column. Returns the encoded DataFrame and a dict of classes."""
    df_encoded = df.copy()
    encoder_dict = {}
    for col in categorical_features:
        values = _as_labels(df[col])
        enc = LabelEncoder().fit(np.append(values.unique(), UNKNOWN))
        encoder_dict[col] = enc.classes_.tolist()
        df_encoded[col] = enc.transform(values)
    return df_encoded, encoder_dict


def transform(df, encoder_dict, categorical_features):
    """Encode new data with the saved classes. Unseen values and nulls map to Unknown."""
    df_encoded = df.copy()
    for col in categorical_features:
        enc = LabelEncoder()
        enc.classes_ = np.array(encoder_dict[col])
        values = _as_labels(df[col])
        values = values.where(values.isin(enc.classes_), UNKNOWN)
        df_encoded[col] = enc.transform(values)
    return df_encoded

Converting every value to a string matters more than it looks. A numeric column with a missing value becomes a float column in pandas, so 10 turns into 10.0 and no longer matches the saved class '10'. The _as_labels helper makes sure the same value always produces the same label.

Using it

At training time:

import joblib

train = pd.DataFrame({"city": ["Riga", None, "Paris", "Oslo"],
                      "code": [10, 20, 10, 30]})

train_encoded, encoder_dict = fit(train, ["city", "code"])
joblib.dump(encoder_dict, "encoder.pkl")

The saved dict is easy to read:

{'city': ['Oslo', 'Paris', 'Riga', 'Unknown'],
 'code': ['10', '20', '30', 'Unknown']}

At inference time, possibly in a different process or on a different machine:

encoder_dict = joblib.load("encoder.pkl")

new = pd.DataFrame({"city": ["Oslo", "Tokyo", None, "Riga"],
                    "code": [30, 99, 10, None]})

transform(new, encoder_dict, ["city", "code"])
city encoded code encoded
Oslo 0 30 2
Tokyo (unseen) 3 (Unknown) 99 (unseen) 3 (Unknown)
missing 3 (Unknown) 10 0
Riga 2 missing 3 (Unknown)

“Oslo” and “Riga” get the same numbers as in training, and the new or missing values fall back to Unknown instead of crashing.

Things to keep in mind

  • Treat Unknown as a real category. If many rows end up there at inference, your data has drifted, and it’s worth monitoring that share.
  • Rare categories help the model learn Unknown. If training never contains Unknown, the model has no real examples of it. Grouping very rare training values into Unknown gives it some.
  • Label encoding suits tree models. Numbers imply an order (Oslo < Paris < Riga), which tree models like random forest and XGBoost can handle but linear models take literally. For those, use one-hot encoding (OneHotEncoder(handle_unknown='ignore') solves the same unseen-category problem).
  • Version the encoder with the model. The encoder dict and the model belong together. Save and load them as a pair.

Newer versions of scikit-learn also have OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1), which covers the same ground for multiple columns at once. The idea is the same: decide at training time what unseen values should become, and save it.