BeginnerCoder

Lesson 8 — One-hot encoding

Turning categories into numbers

Models only understand numbers, but lots of data is categorical — words like "red", "green", "blue". One-hot encoding turns a category into a list of 0s with a single 1 in the position of that category. The list of all possible categories is called the vocabulary.

vocab = ["red", "green", "blue"]
# "green" -> [0, 1, 0]

Why not just red=1, green=2, blue=3? Because then the model would think blue is "bigger" than red, which means nothing.

Why it matters: almost every real dataset has categories (country, product type, weekday), and one-hot is the standard first way to feed them to a model.

Want it another way?
Task

Finish one_hot(value) with a list comprehension: 1 where the vocabulary item equals value, else 0.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.