Exercises — Ordinal and target encoding
This page tests everything from the parent note with graded problems. Each climbs a rung: L1 Recognition (spot the right tool) → L2 Application (turn the crank) → L3 Analysis (why it breaks) → L4 Synthesis (combine ideas) → L5 Mastery (design & defend). Solutions are hidden inside collapsible callouts so you can self-test first.

Level 1 — Recognition
Goal: recognise which encoder fits a feature, and read a mapping without doing arithmetic.
Exercise 1.1
You have four features. For each, say whether ordinal encoding, target encoding, or one-hot is the natural first choice, and why.
| Feature | Unique values | Notes |
|---|---|---|
education |
High School, Bachelor, Master, PhD | clear rank |
us_state |
50 states | no order, many categories |
blood_type |
A, B, AB, O | no order, few categories |
zip_code |
30 000 codes | no order, huge cardinality, predicting income |
Recall Solution 1.1
education→ ordinal. It has a natural progression (each level requires the previous), so integers 1–4 encode real "distance".us_state→ one-hot or target. 50 columns is borderline but survivable; if you're predicting a target and want compactness, target encoding works. No inherent order → never ordinal.blood_type→ one-hot. Only 4 unordered categories — cheap, safe, no order to exploit.zip_code→ target encoding. 30 000 categories would make one-hot explode into 30 000 sparse columns (see Curse of Dimensionality); target encoding compresses each zip into one number: the mean income there.
Rule of thumb: order present → ordinal; no order, low cardinality → one-hot; no order, high cardinality with a target → target.
Exercise 1.2
Given the mapping S→1, M→2, L→3, XL→4, encode [L, S, XL, M, L]. No smoothing, no arithmetic tricks — just lookup.
Recall Solution 1.2
Replace each value by its rank: L→3, S→1, XL→4, M→2, L→3.
Level 2 — Application
Goal: compute encodings by hand, including the smoothing formula.
Exercise 2.1 (basic target encoding)
Training data:
| Row | city |
price (k$) |
|---|---|---|
| 1 | NYC | 500 |
| 2 | NYC | 600 |
| 3 | NYC | 550 |
| 4 | Seattle | 400 |
| 5 | Seattle | 450 |
| 6 | Portland | 300 |
Compute the raw target encoding for each city and the global mean.
Recall Solution 2.1
Global mean over all 6 rows: (Note: this is not the same as averaging the three city means, because NYC has more rows and pulls the row-level global mean up.)
Exercise 2.2 (smoothed target encoding)
Using the counts above, global mean (the parent note's rounded value), and smoothing , compute the smoothed encoding for Portland () and NYC ().
Recall:
Recall Solution 2.2
Portland (, ): NYC (, ): Portland (1 sample) is dragged far toward 475; NYC (3 samples) is dragged less. The weight on the category mean is : Portland , NYC .
Exercise 2.3 (unseen category at test time)
At test time you see [Boston, NYC, Seattle] using the raw encodings from 2.1. Boston never appeared in training. Produce the encoded vector, treating unseen categories with the (rounded) global mean .
Recall Solution 2.3
Boston unseen → global mean . NYC → . Seattle → .
Level 3 — Analysis
Goal: reason about failure modes, leakage, and limiting behaviour.
Exercise 3.1 (limiting behaviour of smoothing)
For fixed and , what does approach as (a) , and (b) ? Interpret each.
Recall Solution 3.1
Write , so . (a) : , so . With infinite data the category mean is trustworthy — no shrinkage needed. (b) : , so . With no data we fall back to the population's best guess. This is exactly the empirical-Bayes behaviour: the estimate slides continuously between "trust the category" and "trust the prior."
Exercise 3.2 (why acts like pseudo-observations)
Show algebraically that equals the plain mean of the category's real observations plus fictitious observations each equal to .
Recall Solution 3.2
The mean of real values (summing to ) together with fake values each (summing to ) is: which is identical to the smoothing formula. So literally counts imaginary "prior" rows pinned at the global mean — larger = stronger pull toward the prior. This is why is called the smoothing strength.
Exercise 3.3 (leakage)
A student computes target encoding on the entire dataset (train + the rows they'll later score), then trains a model and reports 0.99 validation accuracy. Explain precisely why this number is a lie, and give the fix.
Recall Solution 3.3
Why it's a lie: each row's price (the target) helped compute the encoding for its own category. So the encoded feature secretly contains the answer for that row — the model "peeks" at through 's encoding. Validation rows encoded with statistics that include themselves inflate accuracy — this is target leakage, a species of Overfitting.
The fix: encode using only data the row didn't contribute to. Practically: use out-of-fold encoding (K-fold) — for each fold, compute encodings from the other folds. A validation row's encoding then never sees its own target.
Level 4 — Synthesis
Goal: combine encoders with other pipeline stages and models.
Exercise 4.1 (order + scale interaction)
You ordinal-encode size as S=1,M=2,L=3,XL=4 and feed it to a distance-based model (k-NN). Alongside it is income ranging 20 000–200 000. What goes wrong, and which parent-linked technique repairs it?
Recall Solution 4.1
Distances are dominated by income because its numeric range (~180 000) dwarfs size's range (3). The ordinal ranks, though meaningful, contribute almost nothing to any distance. Fix: apply Feature Scaling (e.g. standardisation) so both features live on comparable scales after ordinal encoding. Ordinal encoding preserves order; scaling makes that order count in a distance metric.
Exercise 4.2 (does a tree care?)
Would a decision tree be affected by the magnitude gap in 4.1 the same way k-NN is? What about by the spacing choice 1,2,3,4 vs 1,2,4,8?
Recall Solution 4.2
Magnitude gap: no. Trees split on thresholds ("income ?"), which are invariant to monotonic rescaling — so trees don't need scaling for magnitude reasons.
Spacing 1,2,3,4 vs 1,2,4,8: also (almost) irrelevant for a tree, because any monotonic relabelling produces the same possible split points in the same order. A tree only uses the ordering, not the exact gaps. (Contrast: a linear model does care — it multiplies the encoded number by a coefficient, so 1,2,4,8 would let it treat XL as 8× S.) This is why ordinal encoding pairs especially naturally with trees.
Exercise 4.3 (pick the encoder for a pipeline)
A dataset for predicting loan default has: grade (A>B>C>D, ordered), state (50 values), employer (12 000 values). Design the encoding for each column and justify in one sentence each.
Recall Solution 4.3
grade→ ordinalA=4,B=3,C=2,D=1(or reverse) — the rank is the credit quality signal.state→ one-hot — 50 unordered columns is affordable and leak-proof, though smoothed target encoding is a valid compact alternative.employer→ smoothed target encoding with out-of-fold CV — 12 000 categories make one-hot infeasible (Curse of Dimensionality), and most employers have few rows, so smoothing + OOF prevents both noise and leakage.
Level 5 — Mastery
Goal: design a leak-free encoder and defend every choice quantitatively.
Exercise 5.1 (out-of-fold encoding by hand)
Two folds. Target is binary default (1 = defaulted).
| Row | Fold | employer |
default |
|---|---|---|---|
| 1 | A | X | 1 |
| 2 | A | X | 0 |
| 3 | A | Y | 1 |
| 4 | B | X | 0 |
| 5 | B | Y | 0 |
| 6 | B | Y | 1 |
Compute the out-of-fold raw target encoding for every row (each row encoded using only the other fold's data). For a category absent from the other fold, use that other fold's global mean.
Recall Solution 5.1
Encoding fold A using fold B's stats. Fold B rows: X→{0}, Y→{0,1}. Fold B global mean .
- Fold B: X mean ; Y mean .
- Row 1 (X):
- Row 2 (X):
- Row 3 (Y):
Encoding fold B using fold A's stats. Fold A rows: X→{1,0}, Y→{1}. Fold A global mean .
- Fold A: X mean ; Y mean .
- Row 4 (X):
- Row 5 (Y):
- Row 6 (Y):
Final encoded column (rows 1–6): Every value came from the opposite fold, so no row saw its own target — leak-free.
Exercise 5.2 (choosing under a noise budget)
A rare category has , category mean , global mean . You want the smoothed encoding to sit at most above the global mean (i.e. ) so a 2-sample fluke can't dominate. Find the smallest integer achieving this.
Recall Solution 5.2
We need Numerator . Require . Smallest integer: . Check: ✓ (exactly the cap).
Exercise 5.3 (defend the whole design)
In two sentences each, justify: (a) why smoothing is a Bayesian prior, (b) why out-of-fold is a form of Cross-Validation, and (c) why ordinal encoding would be wrong for employer.
Recall Solution 5.3
(a) The pseudo-rows pinned at act as a prior belief that "before seeing data, every category behaves like the population"; observed rows update that belief, and the posterior is the weighted average — textbook empirical Bayes.
(b) Out-of-fold encoding computes each fold's feature from the held-out remaining folds, exactly the train/validate split logic of K-fold Cross-Validation, applied to feature construction instead of scoring.
(c) employer has no natural order, so assigning ranks 1,2,3,… would invent a false "employer 8 is twice employer 4" relationship, injecting a fictitious ordinal signal a linear model would happily (and wrongly) exploit.
Recall
Which encoder for a 12 000-value unordered feature with a target? ::: Smoothed target encoding computed out-of-fold. As , ? ::: The category mean . A tree only uses the order of an ordinal encoding, not the exact spacing. ::: True The global mean is the mean over all rows, not the mean of the category means. ::: correct