What Encoding Is and Is Not
Contrast naive straight-line regression on raw category codes against exact one-hot group means, and trace where one-hot encoding stops helping.
The problem
Suppose six observations record a category code in alongside a target : [[0, 11], [0, 13], [1, 2], [1, 4], [2, 8], [2, 10]]. Category averages , category drops to , and category rebounds to .
If you feed raw integer codes directly into a single-slope linear model , the line is forced to move monotonically across , , and . Replacing that scalar code with a three-column one-hot matrix grants each category its own parameter and recovers exact per-category group means.
Work through the numbers
Start with the straight-line fit on raw codes (mean ) and targets (mean ). Centered codes have sum of squares and dot product with centered , giving and . On [0, 1, 2], the line predicts [9.5, 8.0, 6.5] with MSE , missing category 's valley () by points.
Now encode into the one-hot matrix over [0, 1, 2]. Column sums give category counts [2, 2, 2]. Multiplying gives category target totals [24, 6, 18]. Dividing totals by counts yields [12, 3, 9], slashing mean squared error from down to (the irreducible within-group variance).
Adding cat1_shift , , or to category 's targets lifts its mean from to , , and ([12, 7, 9], [12, 11, 9], [12, 15, 9]) while categories and stay locked at and .
The live model
Three vertical bars show predicted targets for categories [0, 1, 2], overlaid with an amber trend line for the raw-code straight-line fit. At default cat1_shift , one-hot group means read [12, 3, 9] against the monotone line [9.5, 8.0, 6.5]. Drag cat1_shift up to to watch category rise from a valley () to a peak () with zero spillover into categories or .
![Three vertical category bars at [12, 3, 9] capturing the non-monotonic valley at category 1 while the raw-code trend line slopes [9.5, 8.0, 6.5].](../assets/ml/what-encoding-is-and-is-not--demo.png)
let cat1_shift = scene.parameter("cat1_shift", 0.0, 0.0, 12.0, 4.0);
let codes = input.select(1, 0).unsqueeze(1);
let vocab = torch.tensor("[0.0, 1.0, 2.0]", DType.F64).unsqueeze(0);
let enc = codes.eq(vocab).to(DType.F64);
let y = input.select(1, 1) + enc.select(1, 1) * cat1_shift;
let sums = (enc * y.unsqueeze(1)).sum(0);
let counts = enc.sum(0);
let answer = sums.div(counts);
out.set("group_means", answer);
{
"group_means": [
12,
3,
9
]
}Watch the parameter change
Your turn
The starter program fits a monotone line directly on raw codes , returning [9.5, 8.0, 6.5] instead of [12, 3, 9]. Set answer to [mean_0, mean_1, mean_2] — the exact per-category mean of target column for codes [0, 1, 2] in column ; Check evaluates both balanced tables and unbalanced tables where categories have unequal row counts.
![Starter monotone bars at [9.5, 8.0, 6.5] from fitting a straight line directly on raw category codes 0, 1, 2.](../assets/ml/what-encoding-is-and-is-not--exercise.png)
let c = input.select(1, 0);
let y = input.select(1, 1);
let cc = c - c.mean();
let yc = y - y.mean();
let w = (cc * yc).sum().div(cc.square().sum());
let b = y.mean() - w * c.mean();
let grid = torch.tensor("[0.0, 1.0, 2.0]", DType.F64);
let answer = b + w * grid;
out.set("group_means", answer);
{
"group_means": [
9.5,
8,
6.5
]
}Encode column 0 of input over [0, 1, 2] and return exact per-category mean targets [mean_0, mean_1, mean_2] from column 1.
Read the result carefully
One-hot encoding removes false ordering between nominal labels in linear and distance-based models, yet an integer code IS right in two common cases: genuinely ordered categories ( or severity tiers) where spacing reflects rank, and decision-tree models that split on thresholds rather than multiplying codes by a slope.
One-hot encoding also carries structural limits: its columns satisfy , creating exact collinearity with an unregularized intercept unless one baseline column is dropped or penalized, and high-cardinality IDs memorize sparse noise. Replacing a high-cardinality ID with per-category target means as an input feature ("target encoding") must compute those means on training rows only (ideally out-of-fold), or the target leaks directly into .
Recap
- Regressing linearly on nominal codes
[0, 1, 2]forces monotone predictions ([9.5, 8.0, 6.5], MSE ), whereas integer codes suit ordered levels () and threshold-splitting trees. - One-hot encoding decouples categories so recovers exact group means
[12, 3, 9](MSE ). - Full one-hot tables add to (collinear with an unregularized intercept), and any target-mean feature ("target encoding") must be pinned on training rows alone to prevent target leakage.