Problems
Loading...
1 / 1

Target Encoding

Feature Engineering
Easy

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.

Algorithm

  1. For each unique category c, compute the mean of all target values where the category equals c:
encoding(c)=1{i:cati=c}i:cati=ctargeti\text{encoding}(c) = \frac{1}{|\{i : \text{cat}_i = c\}|} \sum_{i : \text{cat}_i = c} \text{target}_i
  1. Replace each category in the input with its computed mean.
Loading visualization...

Examples

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.

Hint 1

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.

Hint 2

After building the means dictionary, create the output by mapping each category to its mean: [means[cat] for cat in categories].

Requirements

  • Compute the mean target value for each unique category
  • Replace each category with its computed mean
  • Return a list of floats with the same length as the input

Constraints

  • categories and targets have the same length (at least 1)
  • Categories are strings
  • Targets are numbers
  • Return a list of floats
  • Time limit: 300 ms
Try Similar Problems