One-Hot Encoder with Unseen Categories

easy
Checkpoint challenge
Solve this to show you know the material and jump straight to Unit 3. Everything before it counts as cleared.

Models need numbers, so categorical features like "red", "green", "blue" get one-hot encoded: one column per category, with a 1 in the matching column.

The production trap is a category at prediction time that wasn't in the training data. Crashing takes your service down. Implement a class OneHotEncoder(handle_unknown="ignore"):

  • fit(values): learn the sorted list of distinct categories into self.categories_, and return self.
  • transform(values): return a float array of shape (len(values), n_categories). An unseen value gives an all-zeros row when handle_unknown="ignore", or raises ValueError when handle_unknown="error".
  • inverse_transform(matrix): turn rows back into categories, with None for all-zero rows.
#preprocessing#categorical#numpy2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
One-Hot Encoder with Unseen Categories · TechGradify