One-Hot Rows From a Fixed Category List

Feature EngineeringEasy+10 XP+10

One-Hot Rows From a Fixed Category List

Models do arithmetic, so a column of words has to become numbers. The lazy fix — red=0, green=1, blue=2 — accidentally claims that blue is bigger than red and that green sits exactly between them. None of that is true.

One-hot encoding avoids the lie. Give every category its own column, and switch on exactly one of them per row.

Task: write one_hot(labels, categories) returning one row per label — a list of 0s with a single 1 in the position that label occupies in categories.

  • The column order comes from categories, not from the order the labels happen to appear in.
  • A label not in categories lights nothing up: its row is all zeros. That's the behaviour you want in production, where a category nobody saw during training turns up at serving time and the pipeline must not crash.
  • labels may be empty, in which case you return an empty list.
  • Use plain 0 and 1 integers.

Every row ends up with the same width, and that width is fixed by categories alone — which is exactly why the training and serving pipelines have to share the same category list.

colourredgreenredblue
→
colour_redcolour_greencolour_blue

One column of words. A model only takes numbers, so these have to become some.

Examples

labels = ['red', 'blue', 'red']
categories = ['red', 'green', 'blue']
returns [[1, 0, 0], [0, 0, 1], [1, 0, 0]]
labels = ['yellow', 'red']
categories = ['red', 'green', 'blue']
returns [[0, 0, 0], [1, 0, 0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run