Target encoding (also called mean encoding) is a feature engineering technique that replaces categorical values with the mean of the target variable for each category. This converts categorical features into numeric features that capture the relationship between the category and the target, making them usable by models that require numeric input.
Given a list of categorical values and corresponding target values, replace each category with the mean target value for that category.
Input:
categories = ["cat", "dog", "cat", "dog"], targets = [1, 2, 3, 4]
Output:
[2.0, 3.0, 2.0, 3.0]
Mean target for "cat" = (1+3)/2 = 2.0. Mean target for "dog" = (2+4)/2 = 3.0. Each category is replaced by its mean.
Input:
categories = ["a", "b", "c", "a", "b", "c"], targets = [1, 2, 3, 4, 5, 6]
Output:
[2.5, 3.5, 4.5, 2.5, 3.5, 4.5]
Mean for "a" = (1+4)/2 = 2.5, "b" = (2+5)/2 = 3.5, "c" = (3+6)/2 = 4.5.
Use two dictionaries: one for sums and one for counts. Loop through categories and targets together, accumulating sum and count per category. Then compute mean = sum/count for each category.
After building the means dictionary, create the output by mapping each category to its mean: [means[cat] for cat in categories].
Sign in to take notes on this problem
Accepts: array
Accepts: array
Target encoding (also called mean encoding) is a feature engineering technique that replaces categorical values with the mean of the target variable for each category. This converts categorical features into numeric features that capture the relationship between the category and the target, making them usable by models that require numeric input.
Given a list of categorical values and corresponding target values, replace each category with the mean target value for that category.
Input:
categories = ["cat", "dog", "cat", "dog"], targets = [1, 2, 3, 4]
Output:
[2.0, 3.0, 2.0, 3.0]
Mean target for "cat" = (1+3)/2 = 2.0. Mean target for "dog" = (2+4)/2 = 3.0. Each category is replaced by its mean.
Input:
categories = ["a", "b", "c", "a", "b", "c"], targets = [1, 2, 3, 4, 5, 6]
Output:
[2.5, 3.5, 4.5, 2.5, 3.5, 4.5]
Mean for "a" = (1+4)/2 = 2.5, "b" = (2+5)/2 = 3.5, "c" = (3+6)/2 = 4.5.
Use two dictionaries: one for sums and one for counts. Loop through categories and targets together, accumulating sum and count per category. Then compute mean = sum/count for each category.
After building the means dictionary, create the output by mapping each category to its mean: [means[cat] for cat in categories].
Sign in to take notes on this problem
Accepts: array
Accepts: array