Speed

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 {0,1,2}\{0, 1, 2\} alongside a target yy: [[0, 11], [0, 13], [1, 2], [1, 4], [2, 8], [2, 10]]. Category 00 averages 1212, category 11 drops to 33, and category 22 rebounds to 99.

If you feed raw integer codes 0,1,20, 1, 2 directly into a single-slope linear model y^=b+w⋅code\hat{y} = b + w \cdot \mathrm{code}, the line is forced to move monotonically across 00, 11, and 22. 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 c=[0,0,1,1,2,2]c = [0, 0, 1, 1, 2, 2] (mean 1.01.0) and targets y=[11,13,2,4,8,10]y = [11, 13, 2, 4, 8, 10] (mean 8.08.0). Centered codes [−1,−1,0,0,1,1][-1, -1, 0, 0, 1, 1] have sum of squares 4.04.0 and dot product −6.0-6.0 with centered yy, giving w=−6.0/4.0=−1.5w = -6.0 / 4.0 = -1.5 and b=9.5b = 9.5. On [0, 1, 2], the line predicts [9.5, 8.0, 6.5] with MSE 13.513.5, missing category 11's valley (33) by 55 points.

Now encode cc into the 6×36 \times 3 one-hot matrix XX over [0, 1, 2]. Column sums ∑iXi,k\sum_i X_{i,k} give category counts [2, 2, 2]. Multiplying XTyX^T y gives category target totals [24, 6, 18]. Dividing totals by counts yields [242,62,182]=[\frac{24}{2}, \frac{6}{2}, \frac{18}{2}] = [12, 3, 9], slashing mean squared error from 13.513.5 down to 1.01.0 (the irreducible within-group variance).

Adding cat1_shift =4= 4, 88, or 1212 to category 11's targets lifts its mean from 33 to 77, 1111, and 1515 ([12, 7, 9], [12, 11, 9], [12, 15, 9]) while categories 00 and 22 stay locked at 1212 and 99.

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 =0= 0, one-hot group means read [12, 3, 9] against the monotone line [9.5, 8.0, 6.5]. Drag cat1_shift up to 1212 to watch category 11 rise from a valley (33) to a peak (1515) with zero spillover into categories 00 or 22.

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].
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 0,1,20, 1, 2, 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 11 for codes [0, 1, 2] in column 00; 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.
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 (S<M<LS < M < L 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 KK columns satisfy ∑k=1KXi,k=1\sum_{k=1}^K X_{i,k} = 1, 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 XX.

Recap

  • Regressing linearly on nominal codes [0, 1, 2] forces monotone predictions ([9.5, 8.0, 6.5], MSE 13.513.5), whereas integer codes suit ordered levels (S<M<LS < M < L) and threshold-splitting trees.
  • One-hot encoding decouples categories so (XTy)k/nk(X^T y)_k / n_k recovers exact group means [12, 3, 9] (MSE 1.01.0).
  • Full one-hot tables add to 1\mathbf{1} (collinear with an unregularized intercept), and any target-mean feature ("target encoding") must be pinned on training rows alone to prevent target leakage.