Target Encoding

Hard
feature-engineering Stripe Capital One PayPal

Implement target encoding: replace each categorical value with the mean of the target variable for that category. Apply smoothing with a global mean.

Smoothed encoding = (count * category_mean + smoothing * global_mean) / (count + smoothing)

Example

categories = ["a", "a", "b", "b", "b"]
targets = [1, 0, 1, 1, 0]
target_encode(categories, targets, smoothing=1)
# For 'a': (2*0.5 + 1*0.6)/(2+1) = 0.5333...
# For 'b': (3*0.6667 + 1*0.6)/(3+1) = 0.65

Test Cases

Python Editor

Output

Click "Run" to see results...