Skip to main content
Module 6 · Lesson 2 of 528/56 in the course~18 min
Module lessons (2/5)

Encoding categorical features

Lesson preview5 hands-on exercises readyMachine Learning: from first principles to practice · Module 6 — Data preparation and pipelines

One-hot and ordinal encoding, and categories unseen in training.

What you'll learn in this lesson

  • Explain why categories must be encoded and why plain integer codes can mislead.
  • One-hot encode with numpy and with OneHotEncoder.
  • Handle categories that appear only after training.

Overview

A column of cities cannot be multiplied by a weight. We must turn categories into numbers, but the way we do it matters. Giving Milan = 0, Naples = 1 and Rome = 2 tells a linear model that Rome is "twice" Naples and that cities have an order. They do not.

One-hot encoding avoids that: it creates one 0/1 column per category, and exactly one of them is 1 in each row. No order is invented.

Sections covered in this lesson

  1. 1The hook: models only do arithmetic
  2. 2Try it: one-hot versus ordinal codes
  3. 3Comparing categorical encoders
  4. 4Progressive examples: safe categorical encoding
  5. 5Practice
  6. 6Check your understanding
Pro Lesson · Module 6 — Data preparation and pipelines

Unlock "Encoding categorical features" and the full Machine Learning: from first principles to practice curriculum

One-hot and ordinal encoding, and categories unseen in training.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Machine Learning: from first principles to practice plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.