2.1.7 · D5Data Preprocessing & Feature Engineering

Question bank — Ordinal and target encoding

2,591 words12 min readBack to topic

This is a question bank for the parent topic — no heavy arithmetic, just the conceptual traps that snap shut on people. Each line hides its answer after the ::: . Cover the right side, commit to an answer out loud, then reveal.

Before you start, four things you must own, in plain language:


Picture the ideas first

Before the traps, three pictures. Every misconception below is easier to catch once you can see what these encodings do.

1 · Three encodings in feature space. The same three categories (S, M, L) become three very different geometries depending on the encoding you pick.

Look at the panels: One-hot Encoding spreads the categories to the corners of a cube — all equidistant, no order. Ordinal packs them onto one number line with a fixed spacing (a metric). Target encoding also uses one line, but the positions are the category's target means — so distances now mean "similar target behaviour."

2 · Ordinal encoding invents a fake metric on unordered features. When "City" has no natural order, mapping it to 1,2,3,4,5 silently claims City 5 is "four steps past" City 1 and that City 3 sits between City 2 and City 4.

The red brackets show gaps the model will treat as real distances — none of which exist between actual cities. This is the single most common ordinal-encoding trap.

3 · The smoothing weight . How much do we trust a category's own mean versus the global baseline? It depends entirely on how many observations back it up.

The curve climbs from (no data → trust the global prior completely) toward (lots of data → trust the category). Increasing (the second curve) drags the whole curve right: you demand more evidence before trusting a category.

4 · Empirical-Bayes shrinkage: raw means collapse toward the global mean. This is why the formula looks the way it does.

Each raw category mean (left) is pulled toward the global mean (dashed line). Rare categories move a lot; well-populated ones barely budge. The final smoothed value is where each arrow lands.


True or false — justify

Recall Ordinal encoding and label encoding are the same thing.

False — both map categories to integers, but ==ordinal encoding uses a meaningful, human-chosen order== (S<M<L), while plain label encoding assigns integers in whatever order the categories appear (often alphabetical), inventing a fake order. ::: False — both map categories to integers, but ordinal encoding uses a meaningful chosen order while label encoding assigns arbitrary integers, faking an order that isn't real.

Recall Applying ordinal encoding to an

unordered feature like "City" is harmless. False — you inject a phantom ordering (City3 > City1) the model will happily exploit as if it were real, distorting distances and splits (see figure s02). Use One-hot Encoding or target encoding instead. ::: False — it fabricates an order (City3 > City1) that doesn't exist, so the model learns fake magnitude relationships between arbitrary labels.

Recall Target encoding always reduces the number of columns compared to one-hot encoding.

True — target encoding produces exactly one numeric column regardless of cardinality, whereas one-hot produces one column per category, which is why it beats the Curse of Dimensionality on high-cardinality features. ::: True — it collapses any number of categories into a single numeric column, unlike one-hot which grows with cardinality.

Recall Smoothed target encoding with

equals the raw category mean. True — with the weight , so the global mean gets zero weight and you recover exactly. ::: True — gives weight 1 to the category mean and 0 to the global mean, so it collapses to the raw mean.

Recall As the smoothing parameter

, every category's encoding approaches the global mean. True — the weight , so all categories collapse toward ; infinite smoothing erases all category signal (right edge of figure s03). ::: True — large drives , so every category shrinks to the global mean and category-specific signal vanishes.

Recall Ordinal encoding requires

Feature Scaling before feeding it to a distance-based model. True (usually) — the integers 1..k are on an arbitrary scale, so for KNN / SVM / gradient descent you should scale them; but Tree-based Models split on thresholds and are scale-invariant, so scaling there is optional. ::: True for distance/gradient models — the raw integers are on an arbitrary scale; trees are scale-invariant so they don't need it.

Recall Target encoding is a form of

Bayesian shrinkage. True — the smoothed formula adds "pseudo-observations" sitting at the global mean, which is exactly an empirical-Bayes prior pulling small-sample estimates toward the population (figure s04). ::: True — it is empirical Bayes: pseudo-observations at the global mean act as a prior that shrinks noisy small-category means.

Recall Target encoding only works when the target is binary (0/1).

False — the mean of any numeric target works: continuous targets (house price) give the average value per category, and multi-class targets are handled by encoding one column per class (each holding ) or using the ordinal/regression target directly. ::: False — you take the mean of any numeric target; continuous targets give an average, and multi-class targets get one encoded column per class holding that class's probability.


Spot the error

Recall "I computed

df.groupby('city')['price'].mean() on the full dataset, then trained on it. Clean pipeline!" The error is target leakage: each row's own went into the mean used to encode that same row, so the model peeks at the answer. Fit the encoding on training folds only via Cross-Validation (or out-of-fold encoding). ::: Leakage — each row's own target contributed to its own encoding, letting the model see the answer. Encode using out-of-fold / cross-validation splits.

Recall "My rare category appeared once with

, so I encoded it as exactly 100." That single value is almost certainly noise, not signal; trusting it causes Overfitting. Apply smoothing to shrink it toward the global mean in proportion to how few observations you have. ::: One observation is noise, not a reliable mean — encoding it verbatim overfits. Use smoothing to pull rare categories toward the global mean.

Recall "Test set has a city I never saw in training, so I dropped that row."

Dropping is wrong at prediction time — you can't drop real requests. Instead encode unseen categories with the global mean (or a validation-based fallback). ::: Don't drop unseen categories — at inference you can't discard live inputs. Fill them with the global mean or a sensible fallback.

Recall "I ordinal-encoded T-shirt sizes as S=1, M=2, L=3, XL=10 because XL is much bigger."

The error: ordinal encoding only guarantees order, not magnitude. The gap 3→10 falsely tells a linear model XL is 7 units past L; use consecutive integers unless you have a justified interval scale. ::: Wrong — ordinal encoding encodes order only, not calibrated distances. Non-consecutive integers invent a fake magnitude gap; use 1,2,3,4.

Recall "I one-hot encoded a Zip-code feature with 40,000 values to be safe."

That creates 40,000 sparse columns, triggering the Curse of Dimensionality and memory blow-up — the textbook case against one-hot. Target encoding compresses it to one informative column. ::: Wrong tool — 40k one-hot columns cause the curse of dimensionality and memory blow-up. High cardinality is exactly when target encoding wins.

Recall "I applied target encoding, then also standard-scaled it, and got the same tree model score. Something's broken."

Nothing's broken — Tree-based Models split on thresholds and are invariant to monotonic rescaling, so scaling a feature can't change their splits. Scaling only matters for distance/gradient models. ::: Not broken — trees are invariant to monotonic scaling, so standardizing an input can't change their splits or score.


Why questions

Recall Why does the smoothing weight use

instead of, say, always? Because confidence in a category mean grows with sample size; a fixed weight would trust a 1-sample and a 1000-sample category equally. makes big categories rely on their own mean and tiny ones lean on the global prior (figure s03). ::: Because confidence should scale with how much data a category has; trusts large categories and shrinks small, noisy ones — a fixed weight can't do that.

Recall Why start ordinal encoding at 1 rather than 0 — does the model care?

For order preservation the starting point is irrelevant (any strictly increasing integers work). Convention picks 1 to sidestep models/frameworks that treat 0 as "missing" or special; the differences between codes, not their absolute origin, carry meaning. ::: Order-preservation is unaffected by the start point; 1-indexing is just convention to avoid 0 being treated as "missing." Only the differences matter.

Recall Why is target encoding especially dangerous with the smoothing constant

set too low? Low means rare categories keep their raw, noisy means, so the encoded column memorizes training targets → severe Overfitting and inflated CV scores that don't generalize. ::: Low lets rare categories keep noisy raw means, so the feature memorizes training targets — classic overfitting with optimistic scores.

Recall Why can target encoding leak even when smoothed, if you don't use out-of-fold encoding?

Smoothing reduces the variance of the leak but doesn't remove it — each row's target still influences the mean applied to that row. Only computing the encoding on data excluding the current row/fold removes the leak. ::: Smoothing shrinks the leak's magnitude but the row's own target still enters its encoding; only out-of-fold computation truly removes it.

Recall Why does the smoothed formula equal "the average including

pseudo-rows at the global mean"? Because summing real rows () plus imaginary rows worth and dividing by the total count is the formula — the empirical-Bayes prior is literally those pseudo-rows (figure s04). ::: Because real rows plus pseudo-rows at the global mean, averaged, gives exactly — the prior is those pseudo-rows.


Edge cases

Recall What encoding does a category get if it appears in training with

count (never seen)? It has no category mean at all, so it falls back to the global mean (or a designated fallback). In the smoothed formula, plug : the result is exactly the global mean. ::: It defaults to the global mean — plug into the smoothed formula and the category term vanishes, leaving .

Recall A binary target

: what does the target encoding of a category actually represent? The mean of 0/1 labels is the fraction of positives, i.e. the empirical probability — target encoding becomes a per-category probability estimate. ::: It becomes the empirical probability , since the mean of 0/1 labels is just the positive rate.

Recall For a

multi-class target with 4 classes, how many target-encoded columns does one categorical feature produce? Four (one probability column per class, each ) — or three if you drop one to avoid redundancy since they sum to 1. Still far fewer than one-hot on a high-cardinality feature. ::: Four columns (one per class probability), or three if you drop the redundant one since they sum to 1 — still vastly fewer than one-hot.

Recall What happens if

every category has the same target mean equal to the global mean? The encoded column becomes a constant — it carries no information and the model can ignore it; target encoding only helps when categories genuinely differ in their target statistics. ::: The column is constant and useless — target encoding adds value only when categories differ in target behavior.

Recall Ordinal feature with a

single category (k=1): what's the encoding? Everything maps to 1, giving a constant column with zero variance — no ordinal or predictive information, safe to drop. ::: All rows become 1, a zero-variance constant column carrying no information; it can be dropped.

Recall You have a genuinely ordered feature but with

1000 levels (e.g., exam rank). Ordinal or target encoding? Ordinal encoding stays one column and preserves the real ordering, so it's fine — high cardinality only forces you away from One-hot Encoding, not away from ordinal encoding, which never expands columns. ::: Ordinal is fine — it stays one column and keeps the true order; high cardinality only rules out one-hot, not ordinal encoding.

Recall Two different categories happen to share the identical target mean after encoding. Is that a bug?

No — collisions are expected; target encoding maps to a target statistic, not to identity, so distinct categories with similar target behavior legitimately land on the same value. ::: Not a bug — encoding maps to a target statistic, so two categories with the same target mean collide by design, not by error.