Target-encode a category with smoothing

High-cardinality categories, like a user's city, are often replaced by the average target for that category. Rare categories get noisy averages, so the average is smoothed toward the global mean.

Write target_encode(cats, y, m) that returns one float per row:
encoded = (sum_y_in_cat + m * global_mean) / (count_in_cat + m)

Here sum and count use all rows of that category, and global_mean is the mean of y.

Signaturedef target_encode(cats, y, m)

Understand the idea

Target encoding replaces a category with the average target value seen for it. Rare categories have noisy averages, so you blend each one toward the global mean. The smoothing m acts like m extra imaginary rows that sit exactly at the global mean. Like judging a new shop by its few reviews plus the city average. Worked example: cats [A, A, B], y [1, 1, 0], m = 1. Global mean = 2/3 = 0.667. For A: sum 2, count 2, so (2 + 1 x 0.667) / (2 + 1) = 0.889. For B: sum 0, count 1, so (0 + 0.667) / (1 + 1) = 0.333. Output per row: [0.889, 0.889, 0.333]. Without smoothing B would be exactly 0, an overconfident guess from one row. Rule: encoded = (sum_y_in_cat + m x global_mean) / (count_in_cat + m), using all rows of that category. It is common in tabular models for fields like city or product ID.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: smoothing pulls rare toward meantarget_encode(['a', 'a', 'a', 'b'], [1, 1, 0, 1], 2)
  • Sample 2: m = 0 is the plain meantarget_encode(['x', 'y', 'x'], [1.0, 0.0, 0.0], 0)