Applications of Machine Learning

Applicazioni Informatiche del Machine Learning

Lecture 1 Géron Ch. 1–2

What machine learning is, and how we will work

BSc Mathematics of Artificial Intelligence · Third year
23 lectures
Textbook: Géron, Hands-On Machine Learning with Scikit-Learn and PyTorch

06:30 Your phone waited to finish charging

A dark cosy bedroom at dawn, a smartphone charging on a bedside table with a small battery icon glowing, a tiny friendly moon-shaped character on the phone holding a pocket watch and waiting patiently next to a sleeping person under a duvet.

It sat at most of a charge all night and topped up just before your alarm, because it has learned when you usually get up.

06:58 Your watch knows you slept badly

A sleepy young student in bed at dawn, hair a mess, squinting at a glowing smartwatch on their wrist that projects a soft wavy hypnogram cloud above the bed, a cat sleeping on their feet, morning light through the curtains.

Before the alarm goes off, your wrist has already decided which parts of the night were deep sleep, which were dreaming, and which were you scrolling in the dark.

07:01 Your phone recognises you before coffee

A bleary-eyed person with wild bed hair holding up a smartphone in a dark bedroom.

Bed hair, no glasses, half asleep, in the dark — and the phone still unlocks for you, and not for your sibling.

07:05 Your inbox has a bouncer

A burly but friendly nightclub bouncer standing at the door of a cosy envelope-shaped club, holding back a queue of shady envelopes wearing sunglasses, fake crowns and fake moustaches, while letting through a cheerful ordinary envelope from mum.

The prince who wants to share his fortune with you never reaches your inbox. Billions of messages a day are turned away at the door.

07:12 “Sounds good, thanks!”

A person lying on a sofa lazily tapping one of three floating speech-bubble buttons that hover above their phone like little helpful robots offering choices, a pile of unanswered envelopes melting away behind them.

The three little replies under an email or a chat were not written by you, and somehow they are usually exactly what you were going to say.

07:15 Will it rain? Ask a neural network

A student at a kitchen window holding a phone and an umbrella, looking up at a sky where friendly cartoon clouds are arranged on a softly glowing grid, one cloud about to rain over the street below.

Some of the world’s big forecasting centres now run machine-learned forecasts alongside the physics, and they hold their own.

07:20 Your feed is not in chronological order

Two flatmates sitting side by side at breakfast, each looking at their own phone.

Out of everything your friends posted overnight, a few hundred things were chosen, and ordered, for you alone. Your flatmate sees a different feed.

07:45 The robot vacuum steers round the sock

A small round robot vacuum cleaner in a sunny living room carefully swerving around a striped sock and a tangled charging cable, a dotted path trail behind it, a dog on the sofa watching with interest.

It maps the flat, recognises the charging cable, the sock and the thing the dog left behind, and goes around all three.

08:00 Your car braked before you did

A city street seen from behind a small car, a cyclist suddenly emerging from behind a parked delivery van, a soft glowing protective bubble shield appearing in front of the car's bumper, the driver's surprised face in the mirror.

A cyclist appears from behind a parked van and the car stops on its own. Automatic emergency braking is required on every new car sold in the EU.

08:05 “You will arrive at 8:41”

A tiny scooter rider zipping along a winding road drawn on a giant smartphone map, glowing route line, a crystal ball shaped like a clock sitting at the destination pin, cars in the distance forming a small traffic jam the route avoids.

An arrival time is not a measurement. It is a prediction about traffic that has not happened yet, and it is usually right to the minute.

08:10 Why the ride costs more in the rain

A rainy city street at morning, many people under umbrellas holding up phones, a small fleet of cartoon cars converging on them from every direction like they were summoned, puddles reflecting city lights.

When you open a ride-hailing app, it has already guessed how many people are about to want a car, where, and how much they will pay.

08:12 Nobody in the driver’s seat

A futuristic but friendly white taxi with a small sensor dome on its roof driving down a city street, an empty driver's seat visible through the window, a relaxed passenger reading in the back seat, pedestrians waving.

In some cities you can already call a taxi that drives itself, all day, every day, through ordinary traffic.

08:15 A mixtape from a stranger who knows you

A student on a city bus wearing big headphones, eyes closed and smiling, as colourful vinyl records and musical notes stream out of their phone and swirl around them.

Once a week a playlist appears of songs you have never heard, by artists you have never heard of, and you like most of them.

08:25 The gate that read your number plate

A narrow historic Italian street with ochre buildings, a small scooter and a little car passing under a camera gate mounted on a pole.

Drive into a restricted-traffic zone without a permit and a camera reads your plate, at speed, in the rain — and the fine finds you.

08:30 Name that tune in three seconds

A busy, noisy café with a hissing espresso machine and chatting customers.

Through café noise and a coffee machine, a few seconds of a song are enough for your phone to tell you exactly which recording it is.

09:00 Reading a menu you cannot read

A tourist in a narrow foreign street pointing a phone camera at a restaurant menu board covered in abstract unreadable squiggles.

Point your camera at a sign in a language you do not speak, and the words change on the screen into yours, in the same font, on the same wall.

09:20 The owl knows what you will forget

A large slightly menacing but cute green cartoon owl peering through a bedroom window at a student who is hiding under a blanket with a phone, word flashcards floating around the room like butterflies.

Language apps decide which word to ask you today based on when you are most likely to forget it — and they send the guilt-trip notification at the right moment too.

09:45 “Was this you?”

A student in a lecture hall looking at a phone showing a big friendly shield with a question mark, while in a thought bubble a hooded cartoon figure on a laptop in a faraway snowy place is stopped by a closed glowing door.

A sign-in to your account from a new country, on a new device, at an odd hour. The service asks you before it lets the stranger in.

10:00 Ten links, out of the whole web

A tiny person standing on top of a colossal mountain made of web pages and documents stretching to the horizon, holding up a single glowing page with a magnifying glass, as if they just found a needle in a haystack.

You type four words, misspell one of them, and of all the pages that exist, the one you wanted is in the first three.

10:15 It finishes your sentences

Close-up of thumbs typing on a smartphone keyboard.

The three words above your keyboard are a guess about what you are going to type next — and the guess is trained on how you write.

10:16 Autocorrect: hero and villain

A comic split scene: on the left a superhero smartphone in a cape catching a falling misspelled word block.

It fixes the typo you did not notice, and then, with complete confidence, turns your message to your professor into something else entirely.

10:30 Copying text out of a photo

A university classroom with a whiteboard full of abstract scribbled shapes and diagrams.

You photograph the whiteboard at the end of the lecture, and later you select the text in the photo and paste it into your notes.

11:00 “Hey, set a timer for ten minutes”

A person in a small kitchen with flour on their hands, talking to a round smart speaker on the counter.

Your voice, with your accent, over a running tap, becomes text, then an intention, then an action. In under a second.

11:30 Your pair programmer never sleeps

A student coding on a laptop at a library desk late at night.

You type the name of a function and the rest of it appears in grey. Most of the time it is right. This course is about the rest of the time.

12:00 You asked a machine to explain your homework

A student at a sunny canteen table chatting with a friendly glowing robot that pops out of their laptop like a genie, the robot juggling icons of a pencil, a globe, a math symbol and a suitcase, one of the juggled items slightly wobbly and cracked.

A chat assistant that drafts your emails, explains a proof, and plans a trip — and sometimes says something false with exactly the same confidence.

12:30 That picture never happened

A friendly robot painter at an easel in a bright studio painting a cheerful flat illustration of a person with a cat, while a student hands it a small slip of paper.

Type a sentence and get a picture. Every illustration in this lecture was made that way, from a one-paragraph description.

13:00 Subtitles nobody typed

A person watching a video on a tablet on a sunny park bench.

Live captions on a video, a lecture, or a call are written as people speak — including, if you are unlucky, a creative interpretation of your surname.

13:30 Describing a photo to someone who cannot see it

A person wearing dark glasses with a white cane sitting on a bench, smiling, listening through earphones to their phone.

A screen reader comes to a photo nobody captioned and says what is in it: two people smiling on a beach, at sunset.

14:00 The dog barked, and nobody heard it

A person on a laptop video call in a chaotic messy room with a loudly barking dog, a construction drill through the window and a pile of laundry.

On a video call, the barking dog, the drill next door and your messy bedroom all vanish, and only your voice and your face are left.

14:30 Select all images with traffic lights

A grid of nine square photo tiles floating in the air, some showing traffic lights, crosswalks and bicycles.

Proving you are not a robot has, at times, also meant labelling pictures for one — the early puzzles helped digitise old books.

15:00 People who bought this also bought…

A happy shopper walking out of a cartoon online-store doorway carrying one small charger, followed by a growing parade of floating boxes, a cable, a phone stand and a quirky desk lamp, all following like ducklings.

You came for a phone charger. You leave with a charger, a cable, a stand, and a lamp you did not know you needed.

15:05 Why your bank texted you at 3 a.m.

A sleepy person in pyjamas at night with a phone buzzing on the bedside table, the screen showing a big warning shield.

The card was used in another country, for an odd amount, at an odd hour, and someone — something — noticed within a second.

15:10 Your parcel was picked by a robot

A huge bright warehouse with tall shelves of boxes, a friendly robotic arm carefully picking a small parcel from a bin, small wheeled robots carrying shelves in the background, conveyor belts with cardboard boxes.

Somewhere in a warehouse, a machine that learned to grasp things it had never seen picked up your charger and put it in a box.

15:30 The ad that seems to read your mind

A person scrolling on a laptop, surrounded by floating billboards that all show running shoes in different colours.

You mention running shoes once, and for a week the internet is full of them. Every ad you see was chosen in the instant the page loaded.

15:45 A machine read your CV first

A tall stack of paper CVs being fed into a friendly but serious robot sitting at an interview desk with reading glasses, sorting them into two trays.

For many jobs, before any person sees your application, software has ranked it. The EU’s AI Act counts that as high-risk.

16:00 “What plant is this?”

A curious hiker crouching in a forest pointing a phone at a strange colourful plant.

Point your phone at a leaf, a dog, a pair of trainers or a maths problem, and it tells you what it is — or where to buy it.

16:30 Should the bank lend you money?

A young person sitting across a desk from a bank clerk, between them a large balance scale weighing a small house on one side and a stack of tidy papers on the other, a calm robot assistant adjusting the scale.

Whether you get the loan, and at what rate, is shaped by a score a model computes from your history. The AI Act calls this high-risk too.

17:00 “Show me dogs at the beach”

A person sitting on a sofa with a phone.

Thousands of photos, none of them labelled, and your gallery finds every dog, every beach, every birthday cake, and every photo of your grandmother.

17:30 Why your yoghurt was on the shelf

A friendly supermarket aisle with a dairy shelf perfectly stocked with yoghurt pots, a student reaching for one, a delivery truck in the window behind and a tiny crystal ball sitting on top of the shelf.

The supermarket ordered it days ago, store by store, because it predicted roughly how many people would buy it on a sunny afternoon.

18:00 Your watch noticed before you did

A runner jogging in a park at sunset, a glowing heart symbol rising from their smartwatch with a gentle wavy heartbeat line, trees and a river in the background.

On an evening run, a smartwatch can flag an irregular heart rhythm, or call for help if you fall and do not get up.

18:30 A second reader for your scan

A calm hospital room, a radiologist in a white coat looking at a large light screen with an abstract chest scan, a small friendly robot standing beside them pointing at one softly highlighted circle on the scan.

In some hospitals a model now reads screening images alongside the radiologist, and points at the spot worth a second look.

18:45 A protein, folded on a computer

A scientist in a lab coat looking with wonder at a large floating colourful ribbon-like 3D protein structure glowing above a laptop, test tubes and a small plant on the lab bench.

Predicting the shape of a protein from its sequence was a fifty-year-old problem. A neural network largely solved it, and its creators shared the 2024 Nobel Prize in Chemistry.

19:30 Photographing the dark

Friends at a dim candlelit dinner table at night.

A phone camera with a lens the size of a lentil takes a sharp, bright picture of a candlelit dinner. Most of that picture was computed, not captured.

20:00 Dog ears, in real time

Two laughing friends taking a selfie, wearing perfectly fitted cartoon puppy ears and noses that sparkle.

The filter finds your eyes, nose and mouth, follows them as you move, and puts puppy ears exactly where they belong, thirty times a second.

20:15 The lights stay on at dinner time

A night-time city skyline where every window glows warmly as families cook dinner, electricity pylons with soft glowing lines leading to a wind farm and a power plant on the hill, a small friendly clock-shaped character on a pylon checking a chart.

Everyone cooks at once. The grid operator predicted the evening peak hour by hour, so the power plants were ready for it.

20:30 Who keeps the internet (mostly) clean

A huge waterfall of colourful video thumbnails pouring down.

Every minute, hours of video are uploaded to the big platforms. Most of what should never be seen is removed before anyone sees it.

20:45 Offside, decided by a skeleton

A football pitch at night under floodlights seen from above at an angle, players shown with glowing stick-figure skeletons overlaid on their bodies, a straight glowing line across the pitch at the last defender, a crowd in the stands.

In the big competitions, cameras track a stick-figure skeleton of every player, and the offside line is drawn in seconds.

21:30 Pixels your graphics card never drew

A gamer in a dark room with headphones, lit by a big monitor showing a lush fantasy landscape.

In many modern games, part of every frame on your screen is not rendered at all. It is invented, and you cannot tell which part.

22:00 Who appears on your dating app

Two young people in different flats at night, each holding a phone, with a playful glowing trail of little floating hearts and profile cards connecting the two phones across the rooftops between their windows.

The profiles you are shown, and the order you see them in, are a recommendation — just one where the items can also say no.

23:30 Just one more episode

A person curled up on a sofa at night in a blanket with popcorn, face lit by a TV showing a row of colourful show tiles.

Even the picture on each show was chosen for you. Someone who loves romance and someone who loves action see the same film with different artwork.

23:55 One last scroll: what is this flat worth?

A student lying in bed late at night scrolling a phone showing a tiny cartoon apartment building with a floating price-tag shaped bubble, a dreamy thought cloud of a sunny flat with a balcony and plants above their head.

Property sites show an estimated price for almost any home, one you are not even selling. That estimate is the model we start building right now.

Part one

The brief

You have just been hired

You are a data scientist at a real-estate investment company.

The task Use California census data to build a model of housing prices. The data gives population, median income and median housing price for each block group — the smallest unit the US Census publishes. We will call them districts.

Your model predicts a district’s median housing price from the other metrics.

The first question is never technical

What exactly is the business objective?

  • Building a model is not the goal
  • How will the company use the output?
  • The answer determines the framing, the algorithm, the metric, and how much effort is worth spending

What the output feeds

Your model’s prediction is fed to another machine learning system, together with other signals, to decide whether a district is worth investing in.

Terminology A piece of information fed to an ML system is called a signal — after Shannon’s information theory. You want a high signal-to-noise ratio.

Note the consequence: nobody downstream ever looks at your prediction. A component that quietly degrades inside a chain of components is not noticed by anyone — which is why the evidence has to come from you.

What is the current solution?

District prices are currently estimated manually by experts: a team gathers information and applies complex rules.

The number that matters When the team can check their estimates against the truth, they are typically off by more than 30%.

Remember this figure — and read it carefully. It is a relative criterion: 30% of the district’s price. The errors we will measure are in dollars, which is not the same thing, and we come back to this when we measure them.

It is also the stakeholder’s claim about their own team, not a measurement we made. We will treat it as an assumption and label it as one wherever it appears.

Frame the problem

Before writing any code, answer four questions:

  1. What kind of training supervision does this need?
  2. Is it classification, regression, or something else?
  3. Should we use batch or online learning?
  4. What assumptions are we making?

Pause here and answer them yourself before the next slide.

Questions 1–3, answered

QuestionAnswerBecause
Supervisionsupervisedevery district carries its expected output
Taskmultiple, univariate regressionpredict one value, from several features
Learning modebatch, offlineno data stream, and 20,640 rows fit in memory
The alternatives, for reference Unsupervised (no labels) · semi-supervised (some labels) · self-supervised (labels from the data itself) · reinforcement (rewards). Predict several values per district and it becomes multivariate regression; add a data stream and it becomes online learning.

Three answers, one minute. The fourth question is the one that can sink the project.

4 · Check the assumptions

List and verify what everyone is assuming. This catches serious problems early.

The one that would sink us What if the downstream system converts our prices into categories — “cheap”, “medium”, “expensive” — and discards the numbers? Then this is a classification problem and we have built the wrong thing.

We asked. They need the actual prices. We may proceed.

Part two

The data

one look at everything, before anything is split

Automate the download


from pathlib import Path
import pandas as pd
import tarfile
import urllib.request

def load_housing_data():
    tarball_path = Path("datasets/housing.tgz")
    if not tarball_path.is_file():
        Path("datasets").mkdir(parents=True, exist_ok=True)
        url = "https://github.com/ageron/data/raw/main/housing.tgz"
        urllib.request.urlretrieve(url, tarball_path)
        with tarfile.open(tarball_path) as housing_tarball:
            housing_tarball.extractall(path="datasets", filter="data")
    return pd.read_csv(Path("datasets/housing/housing.csv"))

housing_full = load_housing_data()
  

Write a function, not a manual download: the data will change, and you will need this on another machine.

The structure

One row per district, ten attributes. Start with head() and info(), always, before anything else.


>>> housing_full.info()
RangeIndex: 20640 entries, 0 to 20639
Data columns (total 10 columns):
 #   Column              Non-Null Count   Dtype
---  ------              --------------   -----
 0   longitude           20640 non-null   float64
 1   latitude            20640 non-null   float64
 2   housing_median_age  20640 non-null   float64
 3   total_rooms         20640 non-null   float64
 4   total_bedrooms      20433 non-null   float64
 5   population          20640 non-null   float64
 6   households          20640 non-null   float64
 7   median_income       20640 non-null   float64
 8   median_house_value  20640 non-null   float64
 9   ocean_proximity     20640 non-null   object
  

Observation: 207 districts are incomplete

total_bedrooms has 20,433 non-null values, not 20,640.

207 districts are missing this feature.

Three options, all legitimate Drop those districts · drop the whole attribute · fill the gaps with a chosen value. We will return to this in the build.

One attribute is not numerical


>>> housing_full["ocean_proximity"].value_counts()
<1H OCEAN     9136
INLAND        6551
NEAR OCEAN    2658
NEAR BAY      2290
ISLAND           5
  

Repeated values from a small set: this is a categorical attribute, not free text.

Note ISLAND: five districts. Rare categories will cause trouble later.

Summary statistics


housing_full.describe()
  
  • count ignores nulls — that is why total_bedrooms reads 20,433
  • std is the standard deviation: how dispersed the values are
  • 25%, 50%, 75% are the quartiles and the median

For a bell-shaped distribution the 68–95–99.7 rule applies: about 68% of values fall within $1\sigma$ of the mean, 95% within $2\sigma$, 99.7% within $3\sigma$.

Plot everything


import matplotlib.pyplot as plt

housing_full.hist(bins=50, figsize=(12, 8))
plt.show()
  

A histogram shows how many instances fall in each value range. Four things should jump out.

Nine attributes, fifty bins

A 3x3 grid of histograms for the nine numeric attributes of the California housing dataset.

Take thirty seconds. What is wrong with the bottom two?

Observation 1 · The income is not in dollars

median_income ranges roughly 0.5 to 15. That is not a salary.

The data was scaled and capped: at 15 (actually 15.0001) at the top and 0.5 (0.4999) at the bottom. The numbers are roughly tens of thousands of dollars — 3 means about $30,000.

Preprocessed attributes are normal. Understanding how they were computed is not optional.

Observation 2 · The target is capped

median_house_value is capped — and it is our label.

Why this is serious Your model will learn that prices never exceed the cap. If the client needs accurate predictions beyond $500,000, the model is unusable there.

Two honest fixes: collect proper labels for the capped districts, or remove them from both the training and the test set.

Animation

Both spikes, enlarged

median_income capped at 15.0001, and median_house_value with its districts piled up in one bar at the $500,001 cap.

965 districts — 4.7% of the dataset — sit at the cap, $500,001: a label that is not their price. It is a ceiling.

Observation 3 · The scales differ wildly

total_rooms runs from 2 to 39,320. median_income runs from 0.4999 to 15.0001.

Which matters for some methods and not others

Scaling is required for: gradient descent, logistic regression, SVMs, $k$-nearest neighbours, $k$-means, PCA, neural networks. Anything that measures a distance, penalises a coefficient, or takes a step.

Scaling does nothing for: decision trees, random forests, and ordinary least squares. Trees split on one feature at a time, so any monotone rescaling gives the same tree; least squares is equivariant under an invertible affine map of the features — the fit is identical and the coefficients simply absorb the change.

Linear regression, trees and forests — the models this dataset will be fitted with — are all in the second list. It is also exactly why scaling before the split, a classic leak, will cost nothing here: an invertible affine map, applied to an estimator that does not care. We will measure that rather than assert it.

Observation 4 · Many attributes are skewed right

They extend much further to the right of the median than to the left.

This makes patterns harder for some algorithms to detect. Later we will transform them toward something more symmetric — typically by taking a square root or a logarithm.

A feature following a power law is a good candidate for $\log$: districts of 10,000 people are ten times rarer than districts of 1,000, not exponentially rarer.

Stop. Before we look any closer

Four observations from four histograms, and we have not yet plotted one variable against another. That is exactly the moment to stop.

The only way to know how a model generalises is to try it on cases it has never seen.

  • Split the data: a training set and a test set
  • The error rate on new cases is the generalisation error
  • Low training error with high generalisation error means overfitting

Typically 80/20 — but with 10 million instances, holding out 1% is plenty.

The notebook for this lecture

Open Lecture 1 in Colab

  • Runs on free CPU
  • Everything on today’s data slides, in order: fetch, info(), the missing values and the categories, the histograms, the range of every column, and the cap — counted, not squinted at
  • Every code cell carries the specification that would produce it — read the box, predict the output, then run
What to do with it before the next lecture Run it top to bottom once. Then change one thing — bins=50 to the default bins=10 in the histogram cell — and look for the two spikes. One argument, and it decides whether you ever see the cap.

Design exercise · in the manner of an ML system-design interview

The task: a property marketplace’s instant home valuation

The brief A property marketplace — the app where homes are listed and searched — wants an instant valuation on every listing and on an owner’s own home page. Buyers read it before offering, owners before selling, and the agents who pay for leads get it with each lead. The business measures leads sold and owners who list; a wrong number costs a listing, a buyer, or a visit from the advertising regulator. The question: a model at all?
  • Given: the public record of past sales — address, date, price — joined to what is known of each home, and current asking prices
  • Scale: tens of millions of homes; tens of thousands of sales a month; a few a year in a small town, thousands in a city
  • Consumers of the output: the visitor who reads it, the search ranking, and the agents who buy the leads

Nine steps follow, each with the pitfall that catches a first attempt and what to do about it. The model at the centre is today’s: none yet — the framing, the baseline, the label, one look at the data and a held-out set, everything that comes before a model.

Step 1 — Frame it: what is the business objective?

  • Building a model is not the goal. The marketplace wants owners to list and buyers to enquire; the valuation is a means, and its use decides the framing, the metric and the effort worth spending
  • Four questions before any code: every sale carries its price, so supervised; one number out, so regression; sales arrive monthly and fit in memory, so batch; and what is everyone assuming?
  • Ask each consumer’s team how the number is used: as a price, or as a band — above or below asking?
Pitfall The search team uses only whether the valuation is above or below the asking price, to badge a listing “good value”. For that consumer the system is a classifier, and every regression metric chosen from here on measures the wrong thing. We asked: the visitor needs the price, the badge needs the band, and a price can be turned into a band but not the reverse — so the output is the price, the band is derived downstream, and the answer is written down before any code.

Step 2 — What is the current solution, and what must be beaten?

  • Today the page shows the home’s last recorded sale price, moved by the region’s price index since that date; an agent’s valuation where one exists
  • That is the baseline: a lookup, no model, computed in a line. Any model is judged by how much it beats it, on sales neither has seen
  • The product manager says the current number is “usually within a tenth of the sale price”: a claim, a relative one, and not yet a measurement
Pitfall Without the baseline’s error on the held-out sales, any error the model reports looks like progress, the release is approved on it, and “within a tenth” becomes marketing copy. Measure the lookup first, on exactly the held-out sales the model will be measured on, and label the figure an assumption wherever it appears.

Step 3 — The label is a sale, not a wish

  • One row per sale: the price paid, the date, and what was known about the home on that date
  • Asking prices are plentiful — every listing has one — and they are not the label: a home listed at one price and sold at another has one price, the second
  • Homes that never sold have no label. The estimate for them is a prediction about a sale that has not happened, judged only when it does
Pitfall Training on asking prices, because there are ten listings for every sale. The model then learns what sellers hope for, which runs above what buyers pay by a margin that differs by town and by season; owners list too high on its advice, and the error against real sales is never seen, because the test set is wishes too. Label with recorded sales only; keep the asking price as a feature at most, never as the answer.

Step 4 — Look at the whole table once, before anything else

  • head(), info(), describe(), a histogram of every column: which columns are incomplete — floor area for old sales, year built for many — and which are categorical, with a rare level such as houseboat
  • The scales — area in square metres, price in hundreds of thousands — and the skew: a few palaces far to the right
  • The spikes: a price piled up at one value, an area recorded as zero where it was unknown
Pitfall — a capped label The public record truncates prices above a reporting threshold, so the most expensive sales all carry the same value. A model learns that prices never exceed it, and the error on exactly the homes with the richest leads is invisible, because the held-out sales are capped too. Count the spike; then obtain the true prices, or remove the capped sales from both the training and the test set, and say so.

Step 5 — Set the test set aside before looking any closer

  • The only way to know how a valuation generalises is to try it on sales it has never seen: split into a training set and a test set now, before one variable is plotted against another
  • The share held out follows the size: a fifth of a few thousand sales, far less of tens of millions
  • Low error on the training sales and high error on the held-out ones is overfitting, and the training error alone can never show it
Pitfall A home sold twice is in the record twice, and a random split puts one sale on each side. The second is not a case the model has never seen: same address, same area, nearly the same price, and the error the release rests on reads better than it is. Hold out homes, not sales, so that every address is on one side only, and check that it is.

Step 6 — How the error will be measured, and against what

  • The error is one number computed on the held-out sales: valuation against price paid, over every home there
  • Measured in money, a mistake of twenty thousand on a flat and on a mansion count the same; the owner of the flat does not agree
  • The product team’s criterion is relative — a share of the price — and an error in money is not the same thing
Pitfall The model is tuned on an error in money, dominated by the expensive homes, and reported to a team whose criterion is a share of each price. The two can move in opposite directions: better on the mansions, worse on the flats that are most of the traffic. Write the metric beside the criterion before anything is fitted, report the error in both forms, and report it by price band, so that nobody approves a release on the average.

Step 7 — When a rule or a lookup table is the better answer

SituationThe better answer
The home sold recently, or carries a fresh valuationshow the record, moved by the index: a rule
A small town with a handful of sales a yearthe area’s median price per square metre, by type and size band, refreshed monthly: a table
A city with thousands of sales and prices that change street by streeta model — if it beats the table on held-out sales by a margin the visitor can feel
Pitfall A model is built because the roadmap said so. In the towns with a handful of sales it is fitted on a dozen rows, overfits them, and loses to the table it replaced — and nobody sees it, because the error is averaged over the country, where the cities dominate; the owners there notice. Decide per area: the rule where a record exists, the table where sales are few, the model where it is measured to win.

Step 8 — After launch: a prediction about a market that moves

  • The held-out error was measured on last year’s sales. Prices drift, and the number shown this spring is judged by sales that close this summer
  • Batch learning, on a schedule: refit on the new sales each month, re-measure on the sales closed since, and only then go live; the data team is on call for the error by region
  • The number changes the market it predicts: owners set asking prices from it, and buyers anchor on it
Pitfall An error measured once, before launch, is quoted for years, while the site’s own number steers the asking prices that become the next sales. One marketplace bought homes on the strength of its own valuations, overpaid for thousands of them, and closed the business. Keep measuring on the sales that close after each release, record what the site showed on the day of each sale so that its pull can be seen, and report the error month by month, never once.

Step 9 — Ship it: the pipeline, and the pitfalls in one table

Objective agreed with each consumer → the lookup measured as the baseline → recorded sales as the label → one look at the whole table → homes held out before exploring → the metric written beside the criterion → rule, table or model per area → measured on the sales after launch → refit monthly.

PitfallAddress it by
The number consumed as a band, not a priceasking each consumer first; the price, then the band
No baseline; a claim taken as a measurementthe lookup measured on the same held-out sales
Asking prices used as labelsrecorded sales only; the asking price a feature at most
A label truncated at a reporting thresholdcounting the spike; true prices, or out of both sets
The same home on both sides of the splitholding out homes, not sales, before exploring
An error in money, a relative criterionthe metric written first; both forms, by price band
A model where a record or a table answersrule, table or model per area; the model where it wins
One error quoted for years, in a market it steersre-measuring after each release; the shown number kept

What we did

  1. Spent a day with machine learning: fifty-one applications you already use, from the phone that unlocks to the episode that plays next
  2. Framed the problem before touching the data — supervised, multiple univariate regression, batch
  3. Checked the assumptions with the downstream team, and found the output is consumed as a price, not as a category
  4. Looked at the whole dataset once: 207 incomplete districts, a categorical attribute with a five-district level, mismatched scales, skew
  5. Found two caps: an income that is not in dollars, and a target where 965 districts — 4.7% — sit at the cap, $500,001, a ceiling instead of a price
  6. Stopped before looking any closer: generalisation is measured on cases the model has never seen, so the test set comes before the exploration
  7. Asked whether a property marketplace’s instant home valuation should be machine learning at all, in nine steps — the objective agreed with each consumer, a lookup measured as the baseline, recorded sales as the label, one look at the table, homes held out before exploring, the metric written beside the criterion, a rule or a table where they win, and the error re-measured after launch — each step named for the pitfall it avoids

Not presented — for afterwards

Exercises
Lecture 1

five, in the style of the written paper

Exercises — Lecture 1

  • The brief says the output feeds a downstream system that expects a price. Name the one thing this fact settles about the problem framing, and one thing it leaves open. [4]
  • info() reports that 207 of the 20,640 districts have no value for total_bedrooms. Give the three legitimate ways of handling the incomplete districts, and say which of them still leaves a decision to make. [4]
  • total_rooms runs from single digits to tens of thousands, median_income from about 0.5 to 15. Name two methods for which this difference in scale matters and two for which it does not, and give the reason for one of the latter. [5]

Solutions on Lecture 2’s deck.

Exercises — Lecture 1 (continued)

  • The median income column is capped at 15. Give one consequence for the model and one for the evaluation, and say which of the two you would raise with the client first. [5]
  • A model’s error is low on its training set and high on new districts. Name the condition, and explain why the training error alone could never have revealed it. [4]

Solutions on Lecture 2’s deck.

Lecture 2 · Géron Ch. 2

The end-to-end project

Data snooping, and a stratified split — measured, not assumed
Exploring the training set: geography, a colour scale, correlations, ratios
Least squares: what fitting a linear model minimises, and why its stationary point is the minimum

Run the Lecture 1 notebook first