Label encoding

Also known as: integer encoding · ordinal encoding

On this page 7

Label encoding is a feature engineering technique in machine learning that replaces each distinct category of a categorical variable with a unique integer, for example mapping red, green and blue to 0, 1 and 2. It is also called integer encoding, and when the integers follow a meaningful order of the categories it is known as ordinal encoding.

The technique exists because most algorithms, from linear models to support vector machines, accept only numeric input. Label encoding is the most compact way to satisfy that requirement, using one column per feature, but it silently introduces an order and a spacing between categories that may not exist in reality.

How label encoding maps categories to integers

Label encoding works by building a lookup table from the training data: every unique category receives an integer from 0 to k minus 1, where k is the number of categories. The same table is then applied to validation, test and production data, so a given category always maps to the same integer.

Libraries assign integers in different ways. Many default to alphabetical or first-seen order, which is arbitrary, while ordinal encoders accept an explicit category list from the analyst. The table below shows the same city feature encoded with an arbitrary alphabetical mapping.

Original categoryEncoded integerImplied meaning
Berlin0Lowest value
Madrid1Between Berlin and Paris
Paris2Between Madrid and Rome
Rome3Highest value
Alphabetical label encoding of a city feature

The right-hand column exposes the core issue. The integers suggest that Rome is three times as far from Berlin as Madrid is, which is meaningless for cities. Whether this artificial structure harms a model depends entirely on how the algorithm uses numeric distances.

Label encoding, ordinal encoding and target labels

The term label encoding covers two distinct use cases that practitioners often confuse. In the first, it encodes the target variable of a classification task, turning class names such as spam and ham into 0 and 1. Here the order is irrelevant, because classifiers treat target values as unordered class identifiers.

In the second use case, it encodes input features. When categories have a natural order, such as education levels or clothing sizes, the result is ordinal encoding, and the integer order carries genuine information. When categories are nominal, such as colors or countries, the order is fabricated.

VariableCategory typeInteger encoding suitable
Classification targetClass labelsYes, order is ignored
Shirt size S, M, L, XLOrdinalYes, with explicit order
Customer satisfaction 1-5OrdinalYes, already ordered
Country of residenceNominalOnly for tree-based models
Product colorNominalOnly for tree-based models
Where label encoding is and is not appropriate

How different algorithms react to integer codes

The impact of label encoding depends on whether a model interprets features as magnitudes. Algorithms that multiply features by weights or compute distances treat the codes as real quantities, while algorithms that split on thresholds only care about order and can isolate any category given enough splits.

AlgorithmSensitivityReason
Linear and logistic regressionHighOne weight forces a linear effect across codes
k-nearest neighborsHighDistances between codes become fake similarities
Support vector machineHighKernels measure numeric distance
Neural networkMedium to highCan partly compensate but learns less efficiently
Decision tree, random forestLowThreshold splits can separate categories
Gradient boostingLowMany shallow splits isolate groups of codes
Sensitivity of common algorithms to arbitrary integer codes

Even tree models are not fully immune. With an arbitrary order, a tree may need several splits to isolate one category in the middle of the range, which wastes depth and can reduce accuracy on small datasets. Some libraries, such as LightGBM and CatBoost, offer native categorical handling that avoids this problem.

Label encoding compared with other categorical encodings

Label encoding is one of several ways to turn categories into numbers, and choosing among them is a trade-off between dimensionality, information and leakage risk. Its closest neighbors in feature engineering are one-hot encoding, target encoding and feature hashing.

EncodingColumns producedMain advantageMain risk
Label encoding1Compact, fast, memory-efficientFabricated order for nominal data
One-hot encodingkNo implied orderSparse, wide data for high cardinality
Target encoding1Captures relation to the targetData leakage without cross-fitting
Feature hashingFixed numberHandles unseen categoriesCollisions merge categories
Learned embeddingsChosen dimensionRich similarity structureNeeds a neural model and data
Label encoding and alternative encodings

A practical rule follows: use ordinal encoding for ordered categories, label encoding for nominal categories only with tree-based models, and one-hot or target encoding for nominal categories in linear, distance-based or kernel models.

Common mistakes when applying label encoding

Most problems with label encoding come from inconsistent mappings between training and inference rather than from the idea itself. The following errors appear regularly in production pipelines.

  • Fitting the encoder separately on test data, so the same category receives different integers in training and evaluation.
  • Unseen categories at inference: a new value has no code and causes an error unless a reserved unknown code exists.
  • Using a target-label encoder on features, which many libraries discourage because it ignores feature-specific settings.
  • Relying on alphabetical order for ordinal data, which puts Large before Medium and Small.
  • Feeding codes into a linear model and interpreting the single coefficient as a meaningful effect.

Robust pipelines fit the encoder once on training data, store the mapping alongside the model, define an explicit code for unknown or missing values and monitor production data for new categories caused by concept drift.

A non-technical view

Computers that learn from data need numbers, not words. Label encoding gives every word a number. Red might become 0, green 1 and blue 2.

This works well when the words already have an order, like small, medium and large. It can mislead when they do not. A model may assume blue is somehow bigger than red, simply because 2 is bigger than 0. The numbers are only name tags. Some models understand that, and some do not.

A concrete example

An online retailer builds a model to predict whether a customer will return a purchased item. The dataset contains about 2 million orders with categorical features such as product category, clothing size, payment method and delivery region.

The data science team applies ordinal encoding to clothing size with an explicit order from XS to XXL, because size genuinely increases. For product category and delivery region, which have no order, they use plain label encoding and train a gradient boosting model, which handles the arbitrary codes through threshold splits. The encoder is fitted on the training period only and includes a reserved code for unseen categories.

When an analyst later tries logistic regression on the same encoded data, accuracy drops noticeably. Switching the nominal features to one-hot encoding for that model closes most of the gap, confirming that the arbitrary integer order was misleading the linear model.