Machine Learning, FoundationsLesson 22 of 92

Module 3 · The data is the job

Turning categories into numbers without lying about them

In this lesson

  • 9 min read
  • 6 reading sections
  • Knowledge check
  • Lesson 3 of 12 in this chapter

This chapter’s goalTake a raw table with mixed types, missing values, high-cardinality categories, dates and free text, and produce a fitted preprocessing pipeline that leaks nothing from the held-out data, handles categories unseen at training time, and whose every transformation you can justify by what the downstream model requires.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:44Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 8Free · no account needed
Lesson steps

The mistake that gets made first

Given a city column, the obvious move is to map cities to integers: Mumbai 0, Delhi 1, Chennai 2, Kolkata 3.

A linear model now believes Chennai is twice Delhi and that Mumbai and Kolkata are three units apart. Those statements are meaningless, but the model cannot know that; it will fit a coefficient as though the ordering were real. This is called label encoding, it is the default in a lot of tutorial code, and it is wrong for any unordered category fed to a linear or distance-based model.

It is not wrong for trees, which is the source of much of the confusion. A tree can split “city in {0, 3}” versus “city in {1, 2}” and recover an arbitrary grouping given enough splits. Label encoding for LightGBM is common practice; label encoding for logistic regression is a bug.

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Every lesson here is open. Your progress is recorded once you pass the How a Language Model Actually Works exam.

Stuck on something?Ask Funke, your AI tutor

How to cite: Addaly (2026) ‘Turning categories into numbers without lying about them’, in Machine Learning, Foundations. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/machine-learning-foundations/categorical-encoding (Accessed: 29 November 2026).