SeeingML
Working With Data Guide 4 of 8 · tap to switch
✦ Interactive Visual Guide 8 min · 4 hands-on labs · Beginner friendly

One-Hot Encoding & Categorical Encoding

How to turn text categories like London boroughs, cup sizes, and postcodes into clean numbers without tricking your model into fake math.

Computers cannot do math on raw words like "Hackney" or "Mayfair". Before any machine learning model can learn from a spreadsheet, every text column must be converted into numbers without inventing fake rankings between labels that have no natural order. Turning unordered categories into clean 0/1 switches with One-Hot Encoding (and knowing when to use ranked numbers or averages instead) is one of the highest-impact steps in real-world data preparation.

The quickest shortcut beginners try is Label Encoding: alphabetize four London boroughs and assign Camden = 1, Croydon = 2, Hackney = 3, Mayfair = 4. Now hand those innocent-looking numbers to Linear Regression (a model that draws one straight line by multiplying each number by a learned price-per-step weight). Watch what goes wrong below, then switch to Clean: One-Hot Switches.

Interactive Lab 1: Why Assigning 1, 2, 3, 4 Tricks Linear Models
Avg Home PriceTrue AvgForced Straight LineMiss Error£300k£500k£700k£900k£680kCamdencode = 1£340kCroydoncode = 2£520kHackneycode = 3£920kMayfaircode = 4
Average Encoding Error: £185k1 numeric column (fake order)
Fake spacing trap! Turning borough names into Camden = 1, Croydon = 2, Hackney = 3, Mayfair = 4 forces a straight-line model to assume home prices rise by a fixed alphabetical step, creating a £185k average miss (predicting £570k for £340k Croydon!). Click "Clean: One-Hot Switches" above to fix it.

Because 1, 2, 3, 4 sit evenly along a number line, Linear Regression is forced to assume home prices step upward by the exact same pound amount from Camden to Croydon to Hackney to Mayfair. One-Hot Encoding breaks that fake ladder by giving each borough its own independent 0/1 light switch, letting every neighborhood learn its own true average price.


What Is One-Hot Encoding? (vs. Ordinal Encoding & the Dummy Variable Trap)

Not every text column needs separate 0/1 switches. If a coffee shop records cup sizes (Small, Medium, Large, X-Large), the categories genuinely climb in real physical order, so Ordinal Encoding (1, 2, 3, 4) preserves that natural ranking in a single compact column.

For unordered categories like neighborhoods, One-Hot Encoding creates one 0/1 switch per category. Notice one sneaky quirk when you keep every switch, though: if you know a neighborhood is NOT Croydon, NOT Hackney, and NOT Mayfair, you already know with 100% certainty it must be Camden! Keeping that 4th switch adds zero new information and makes plain linear equations tie because multiple weight combinations produce the exact same prediction. Statisticians call this redundant-column tie the Dummy Variable Trap, and the fix is simple: drop one reference column so the baseline neighborhood is represented cleanly by all zeros.

Switch between Unordered (Borough) and Ordered (Cup Size) below, then click Drop 1 Redundant Column (Reference Baseline) to watch the redundant switch disappear cleanly.

Interactive Lab 2: One-Hot Switches, Ordinal Ranks & Redundant Columns
Raw Text
is_Camden
(redundant)
is_Croydon
is_Hackney
is_Mayfair
Row Sum
Camden1000= 1
Croydon0100= 1
Hackney0010= 1
Mayfair0001= 1
4 switch columns (1 redundant)
Look at the Row Sum column: every single row adds up to 1! If Croydon, Hackney, and Mayfair are all 0, the row must be Camden. Keeping that 4th redundant switch makes plain unregularized linear equations tie (the Dummy Variable Trap). Click "Drop 1 Redundant Column (Reference Baseline)" above to fix it.

When One-Hot breaks: high-cardinality columns

Cardinality simply means how many unique categories live inside one column, like 4 neighborhoods compared with 50,000 ZIP codes!

One-Hot Encoding shines on low-cardinality columns with roughly 3 to 15 unique categories. Now imagine encoding 50,000 ZIP codes or 250,000 user IDs. One-Hot Encoding would add 50,000 brand-new columns where almost every single cell is 0, bloating memory and giving your model tens of thousands of near-empty columns to sort through.

Instead of exploding your spreadsheet width, teams switch to two compact fixes:

  • Target Encoding: replace each ZIP code with one rich number showing its historical average outcome (for example, the share of luxury homes in that area).
  • Learned Embeddings: for massive ID columns like 250,000 user or product IDs in neural networks, let the model learn 16 to 64 compact meaning coordinates for each ID so similar items land close together automatically.

Start on ZIP Codes (50,000) below to watch One-Hot explode your table width, then click through all four category counts to see what teams use instead.

Interactive Lab 3: When One-Hot Explodes (Unique Categories in Column)
Best pick: Smoothed Target Encoding
Pick how many unique categories live in your column:
One-Hot Spreadsheet Preview (3 Sample Rows)50,000 columns (99.998% empty zeros!)
Raw Valuec1c2c3c4c5c6c7c8... +49,992 more columns
ZIP 1000101000000+ 49,992 empty "0" cells
ZIP 94107000000001 lone "1" buried in 49,992 empty "0"s
ZIP 60611000000001 lone "1" buried in 49,992 empty "0"s
One-Hot Table Width (Log Scale)50,000 columns
Smart Choice: Smoothed Target Encoding1 historical average column
Smoothed Target Encoding: One-Hot Encoding explodes 1 ZIP code column into 50,000 columns that are 99.998% empty zeros, bloating memory and overfitting rare ZIP codes. Smoothed Target Encoding replaces each ZIP code with 1 reliable historical average.

Target Encoding without overfitting (smoothing rare categories)

Target Encoding compresses thousands of streets or ZIP codes into one informative number by replacing each category with its historical average outcome (for example, the share of luxury homes on that street).

There is just one catch: what if a tiny street only appears once in your dataset, and that single home happens to be luxury? Raw Target Encoding writes down 100% luxury for that entire street! Trusting a tiny 1-home street with a 100% rate is classic overfitting: memorizing a one-row fluke instead of learning a reliable pattern.

The fix is Smoothing: blending tiny-sample streets back toward the citywide average based on how many examples you actually have. A busy street with 150 homes has strong real evidence, so its average barely moves; a rare 1-home street gets pulled calmly back toward the 30% citywide average. A single dial called Blending Strength (m) sets how much pull the citywide average has.

One safety rule is essential: always compute target averages on Practice (Training) rows only (specifically using other training rows, called out-of-fold encoding) so a row never peeks at its own answer!

Slide Blending Strength (m) below from 0 upward to watch the 1-home fluke settle safely toward the citywide average while the busy street holds firm.

Interactive Lab 4: Smoothed Target Encoding (Taming Rare Categories)
Citywide Average: 30%
Encoded ScoreRaw Street Average30% City Avg Marker
0%100%
30% City Avg
Rare Mews (1 home seen)Raw: 100% -> Encoded: 100%
Quiet Lane (5 homes seen)Raw: 80% -> Encoded: 80%
Busy High St (150 homes seen)Raw: 62% -> Encoded: 62%
Raw averages (no blending)
0 (Raw / Overfit)10 (Balanced)25 (Strong Pull)
No blending yet (m = 0): Rare Mews has only 1 observed home, so raw Target Encoding marks the entire street as 100% luxury! That memorizes a one-home fluke (overfitting). Drag Blending Strength up toward 10 to see smoothing tame it.
See Dummy Collinearity, Micci-Barreca Target Smoothing & Out-of-Fold RulesThesis / Reference

1. Exact Dummy Variable Collinearity: For a categorical feature with KK levels encoded via indicators d1,…,dK∈{0,1}d_1, \dots, d_K \in \{0,1\}, every row satisfies ∑k=1Kdk=1\sum_{k=1}^{K} d_k = 1, which is linearly dependent on the intercept column 1\mathbf{1}. In unregularized OLS, X⊤X\mathbf{X}^\top \mathbf{X} becomes singular (rank-deficient). Dropping one reference category (K−1K - 1 dummies) restores full column rank; in Ridge/Lasso or neural networks, regularization resolves the singularity automatically and keeping all KK columns treats all categories symmetrically under the penalty!

2. Empirical-Bayes Smoothed Target Encoding (Micci-Barreca, 2001): For category cc with ncn_c training examples, sample target mean yˉc\bar{y}_c, global training prior yˉ\bar{y}, and smoothing weight m>0m > 0:

e^(c)=nc yˉc+m yˉnc+m\hat{e}(c) = \frac{n_c \,\bar{y}_c + m \,\bar{y}}{n_c + m}

As nc→∞n_c \to \infty, e^(c)→yˉc\hat{e}(c) \to \bar{y}_c; when nc=0n_c = 0 (unseen category at test time), e^(c)=yˉ\hat{e}(c) = \bar{y} cleanly with zero crash!

3. Preventing Target Leakage (Out-of-Fold Encoding): Computing yˉc\bar{y}_c using a row’s own label yiy_i leaks target information directly into the feature. Modern tools (sklearn.preprocessing.TargetEncoder, CatBoost ordered target statistics) compute every training row’s encoding strictly from other cross-validation folds (out-of-fold) so validation performance stays honest.

See safe One-Hot & Out-of-Fold Target Encoding in PythonOptional Code
python
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, TargetEncoder
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import Ridge

preprocess = ColumnTransformer([
  ("borough", OneHotEncoder(handle_unknown="ignore", drop="if_binary"), ["borough"]),
  ("size", OrdinalEncoder(categories=[["Small", "Medium", "Large", "X-Large"]]), ["cup_size"]),
  ("postcode", TargetEncoder(smooth="auto", cv=5), ["postcode"]),
], remainder="passthrough")

pipe = make_pipeline(preprocess, Ridge(alpha=1.0))
pipe.fit(X_train, y_train)

Next step: putting every numeric feature on a fair scale

Now both your numbers and your text categories live cleanly in numeric columns. One crucial snag remains: if Age runs from 20 to 65 while Annual Salary runs from £20,000 to £120,000, Salary will bully every distance and gradient calculation. Next up in Feature Scaling & Normalization, we fix that visually.

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

You encode Car Brand as Audi = 1, BMW = 2, Ford = 3, Toyota = 4 and feed it into Linear Regression to predict resale price. What is the main flaw?

Pick an option first, or peek anytime
2

Which column is the best match for Ordinal Encoding (1, 2, 3, 4) rather than One-Hot Encoding?

Pick an option first, or peek anytime
3

In Target Encoding, why do we apply Smoothing to blend rare categories toward the citywide average?

Pick an option first, or peek anytime
4

One-Hot Encoding a column with 50,000 unique customer ZIP codes is a great default choice for a small tabular dataset.

Pick an option first, or peek anytime
Quick Reference

Common Questions

What is one-hot encoding in machine learning?
One-hot encoding turns a categorical column like City (London, Paris, Tokyo) into separate binary 0/1 columns (is_London, is_Paris, is_Tokyo) so models do not invent fake numerical rankings like Tokyo > Paris > London.
Does Random Forest or XGBoost need one-hot encoding?
Tree models can split on integer categories, but arbitrary integer codes still force deep, inefficient splits for unordered categories. For low-cardinality categories, one-hot encoding is safe and clear; for high-cardinality columns, smoothed target encoding or native categorical support in LightGBM and XGBoost works better.
Does one-hot encoding increase dimensionality?
Yes. Each unique category adds a new binary column, so a column with 500 postcodes adds 500 sparse columns. That is why high-cardinality features work better with smoothed target encoding, frequency encoding, or learned embeddings.
When should I use One-Hot Encoding vs. Ordinal Encoding?
Use One-Hot Encoding for nominal categories with no built-in ranking (cities, colours, payment types) when there are fewer than ~20 unique values. Use Ordinal Encoding only when categories carry a real order (Small < Medium < Large or Bronze < Silver < Gold).
What is the Dummy Variable Trap (and when should I use drop_first)?
When you one-hot encode K categories into K columns, every row sums to 1, making the final column 100% redundant from the others. Unregularized OLS regression cannot invert the collinear matrix unless you drop one reference column (drop_first=True). Regularized models (Ridge, neural nets) and trees work fine with all K columns.
Why does One-Hot Encoding fail on postcodes or user IDs?
High-cardinality columns with thousands of unique values explode into thousands of 99.9%-zero columns, wasting memory, slowing training, and starving decision tree splits. Use smoothed Target Encoding, Frequency Encoding, or learned neural embeddings instead.
How do you prevent data leakage when using Target Encoding?
Because Target Encoding uses the training label y to encode categories, computing it directly on the same rows you train on leaks the answer into the feature. Always compute Target Encoding out-of-fold inside cross-validation (like scikit-learn's TargetEncoder) and apply smoothing for rare categories.
What happens when an unseen category appears in production or test data?
Configure your encoder explicitly with handle_unknown='ignore' (all-zero One-Hot row) or fallback to the global training prior for Target Encoding so new cities or product codes never crash your live pipeline.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/one-hot-encoding/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026onehotencoding,
  author       = {Irshad, Muhammad Aashir},
  title        = {One-Hot Encoding & Categorical Encoding: Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/one-hot-encoding/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). One-Hot Encoding & Categorical Encoding: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/one-hot-encoding/