Working With Data Guide 4 of 8 · tap to switch
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.
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.
| Raw Text | is_Camden (redundant) | is_Croydon | is_Hackney | is_Mayfair | Row Sum |
|---|---|---|---|---|---|
| Camden | 1 | 0 | 0 | 0 | = 1 |
| Croydon | 0 | 1 | 0 | 0 | = 1 |
| Hackney | 0 | 0 | 1 | 0 | = 1 |
| Mayfair | 0 | 0 | 0 | 1 | = 1 |
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.
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.
See Dummy Collinearity, Micci-Barreca Target Smoothing & Out-of-Fold RulesThesis / Reference
1. Exact Dummy Variable Collinearity: For a categorical feature with levels encoded via indicators , every row satisfies , which is linearly dependent on the intercept column . In unregularized OLS, becomes singular (rank-deficient). Dropping one reference category ( dummies) restores full column rank; in Ridge/Lasso or neural networks, regularization resolves the singularity automatically and keeping all columns treats all categories symmetrically under the penalty!
2. Empirical-Bayes Smoothed Target Encoding (Micci-Barreca, 2001): For category with training examples, sample target mean , global training prior , and smoothing weight :
As , ; when (unseen category at test time), cleanly with zero crash!
3. Preventing Target Leakage (Out-of-Fold Encoding): Computing using a row’s own label 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
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.
Quick Intuition Check
Four quick real-world scenarios. No scores, just test your intuition.
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?
Which column is the best match for Ordinal Encoding (1, 2, 3, 4) rather than One-Hot Encoding?
In Target Encoding, why do we apply Smoothing to blend rare categories toward the citywide average?
One-Hot Encoding a column with 50,000 unique customer ZIP codes is a great default choice for a small tabular dataset.
Common Questions
What is one-hot encoding in machine learning?
Does Random Forest or XGBoost need one-hot encoding?
Does one-hot encoding increase dimensionality?
When should I use One-Hot Encoding vs. Ordinal Encoding?
What is the Dummy Variable Trap (and when should I use drop_first)?
Why does One-Hot Encoding fail on postcodes or user IDs?
How do you prevent data leakage when using Target Encoding?
What happens when an unseen category appears in production or test data?
Related Visual Guides
Feature Engineering and Selection
How turning raw columns into smarter clues and cutting redundant or noisy junk often beats switching to a bigger model.
Decision Trees & Split Impurity
Turn messy tables into crystal-clear flowcharts of yes/no questions, understand Gini Impurity vs. Entropy, and see why pruning stops overfitted boxes.
Gradient Boosting (XGBoost & LightGBM)
Build a relay team of small trees where every new tree fixes the leftover mistakes of the previous ones, dominating real-world tabular ML.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@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}
} Irshad, M. A. (2026). One-Hot Encoding & Categorical Encoding: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/one-hot-encoding/