Module 3, topic 23, week 12, Tuesday
Train/test split and cross-validation; overfitting, underfitting, and the bias-variance tradeoff
Why a model is judged on rows it has not seen, how to split the data and read the two scores, what overfitting and underfitting are, why several splits are better than one, and what bias and variance mean. A short lesson with code on one data file.
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example as a short cell on flats.csv, and the six solved problems.
topic-23-train-test-split-and-cross-validation.ipynb, 41 KB
Practice notebook
One small project in eight steps on flats.csv, from the first import to the last score, with a hint and a hidden solution for each step.
topic-23-practice.ipynb, 12 KB
Data file: the flats
200 invented flats with 11 columns, all numbers: the data of every example and of the practice.
flats.csv, 7 KB
Introduction: is the score fair?
The third lesson of Module 3. In Topic 22 you trained your first model and measured it with R² and RMSE. But every one of those numbers was calculated on the same points the model had learned from. This lesson asks whether that is a fair measure, and the answer is no. It shows the fair way: put a part of the data aside before training, and judge the model on that part.
The lesson is short and practical. It explains why the data is split into a training part and a test part, how to read the two scores side by side, what overfitting and underfitting are, why one split is not enough and how cross-validation repairs that, and what the words bias and variance mean. Everything is done on one small data file, flats.csv, with the linear regression of Topic 22.
You need: LinearRegression, fit, predict, R², MSE and RMSE (Topic 22), and reading a CSV file into a DataFrame (Topic 10).
What you will learn
- 1.Why a model must be judged on data it has not seen
- 2.How to split data into a training part and a test part with
train_test_split - 3.Why the score on the test data is the one that counts
- 4.What a normal difference between the training score and the test score looks like
- 5.Overfitting and underfitting: what they are, when they happen and how to recognise them
- 6.Cross-validation: several splits and their average, and why that is more reliable than one split
- 7.Bias and variance: the two sources of error, why they pull in opposite directions, and what to do about each
| Word | Meaning |
|---|---|
| training data | the rows the model learns from |
| test data | the rows that are put aside and used only to judge the finished model |
| training score, test score | the R² of the model on the training data and on the test data |
| generalisation | how well a model works on data it has not seen |
| overfitting | the model has learned the training data too closely, noise included: high training score, much lower test score |
| underfitting | the model is too simple to find the pattern: low score on both parts |
| cross-validation | splitting the data several times, so that every row is test data once, and averaging the scores |
| fold | one of the equal parts the data is cut into for cross-validation |
| bias | the error of a model that is too simple for the data |
| variance | how much a model changes when it is trained on other rows |
1Why split the data?
1.1The problem with one set of data
In Topic 22 the model was trained on five students and then measured on the same five students. That is like a teacher who gives the class twenty exercises with their answers, and then uses the same twenty exercises in the exam. A student who learned the twenty answers by heart gets full marks, and nobody finds out whether the student understood anything.
A model can do the same. It can adapt so closely to the rows it was given that it reproduces them, noise and accidents included, without having found the real pattern. Its score on those rows is then excellent, and it says nothing about new data.
But new data is the whole purpose. Nobody needs a model to tell the price of a flat that was already sold. The model is needed for the flat that comes on the market tomorrow. The ability to work on data it has not seen is called generalisation, and that is what must be measured.
1.2The solution: put a part aside
Before training, the rows are divided into two parts:
- The training data is what the model learns from.
fitsees only these rows. - The test data is locked away during the training. When the model is finished, it predicts the test rows, and its predictions are compared with the true answers.
For the model, the test rows are new: it has never seen them. So the score on the test data is an honest estimate of how the model will do on tomorrow's flats.
1.3How the split is made
- At random. The rows are shuffled before they are divided. If the file is sorted, for example by price, and the last 20 percent were simply cut off, the test data would contain only the most expensive flats, and it would not look like the training data.
- Usually 80 percent for training and 20 percent for testing. 75 to 25 and 70 to 30 are also common. More training rows give a better model; more test rows give a more reliable score. With very little data, the test part must not become too small: a score from 5 rows means almost nothing.
- Once, and before anything else. The test data is separated first and touched only at the very end.
1.4Why the test score is the one that counts
After the split, every measure exists twice: on the training data and on the test data.
- The training score says how well the model reproduces what it has already seen. It is always flattering.
- The test score says how well the model predicts what it has not seen. That is the question we care about.
So the rule of this lesson: a model is reported and compared by its score on the test data. The training score is not thrown away. It is useful as the second half of a comparison, as Part 3 shows.
The 200 flats, one square each. Choose the share of the test data, and shuffle again.
Training data: 160 flats. Test data: 40 flats.
The squares are in the order of the file, and the test rows are spread all over it: the split is random. "Shuffle again" is what another random_state does: the same sizes, other rows.
Try it yourself
fit see? (d) Which score is reported for the model?Show a hint
Show the solution
Answer: (a) 100; (b) 400; (c) the training data; (d) the test score.
The model learns from the 400 training rows only. The 100 test rows are new for it, so the score on them is the honest one.
2The split in Python
2.1The data
The file flats.csv describes 200 invented flats. Every column is a number, so the data can go into a model as it is.
import pandas as pd
df = pd.read_csv("flats.csv")
print(df.shape)
print(df.columns.tolist())Output
(200, 11) ['area', 'rooms', 'age', 'floor', 'distance_km', 'photos', 'listing_day', 'owner_age', 'building_number', 'agent_id', 'price']
The six columns that matter most here, for the first five flats:
print(df[["area", "rooms", "age", "floor", "distance_km", "price"]].head())Output
area rooms age floor distance_km price 0 43 1 14 12 12.5 76 1 117 3 27 13 7.9 169 2 86 2 1 15 11.2 149 3 111 3 22 8 18.3 148 4 69 2 6 15 8.6 112
| Column | Meaning |
|---|---|
area | the area in m² |
rooms | the number of rooms |
age | the age of the building in years |
floor | the floor |
distance_km | the distance to the city centre in km |
photos | the number of photographs in the advertisement |
listing_day | the day of the month on which the advertisement was posted |
owner_age | the age of the owner |
building_number | the number of the building in its street |
agent_id | the number of the estate agent |
price | the price in thousands: the target |
The first five columns describe the flat. The next five have nothing to do with its price. They will be useful later, to show how a model goes wrong.
The data file: flats.csv
200 flats, 11 columns, all numbers. A cell marked "empty" has no value in the file: pandas shows it as NaN.
Loading the table ...
2.2Step 1: X and y
The features are the five columns that describe the flat, and the target is the price:
X = df[["area", "rooms", "age", "floor", "distance_km"]]
y = df["price"]
print(X.shape, y.shape)Output
(200, 5) (200,)
2.3Step 2: the split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(X_train.shape, X_test.shape)
print(y_train.shape, y_test.shape)Output
(160, 5) (40, 5) (160,) (40,)
Change it and run: change test_size to 0.3 and run: 60 flats become test data and 140 stay for the training.
test_size=0.2: 20 percent of the rows, 40 flats, become the test data. The other 160 are the training data.random_state=42: the rows are shuffled at random before they are divided. This number fixes the shuffle, so that the same rows land in the test data every time the code runs, on your computer and on this page. Any whole number works; another number gives another split.- The function returns four pieces, always in this order: the training features, the test features, the training target, the test target.
2.4Step 3: train on the training data
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train, y_train)
print(round(model.score(X_train, y_train), 3))
print(round(model.score(X_test, y_test), 3))Output
0.953 0.952
fit gets the training data and nothing else. score is R² (Topic 22): the first line is the training score, the second the test score.
2.5Step 4: the errors on the test data
R² says how much of the variation is explained. MSE and RMSE say how large the errors are. For them, the model first predicts the test rows:
from sklearn.metrics import mean_squared_error, r2_score, root_mean_squared_error
y_pred = model.predict(X_test)
print(round(r2_score(y_test, y_pred), 3))
print(round(mean_squared_error(y_test, y_pred), 2))
print(round(root_mean_squared_error(y_test, y_pred), 2))Output
0.952 164.69 12.83
The three functions get the true answers of the test rows, y_test, and the predictions for the test rows, y_pred. The R² is the test score of Step 3. The RMSE says that the price of a flat the model has never seen is predicted with a typical error of about 13 thousand, for prices between 20 and 294 thousand.
2.6The whole recipe
- Read the data.
- Choose
X(the features) andy(the target). - Split:
train_test_split(X, y, test_size=0.2, random_state=42). - Create the model and
fitit onX_trainandy_train. - Predict the test rows:
y_pred = model.predict(X_test). - Measure on the test data: R², MSE, RMSE, with
y_testandy_pred. - Compare the training score with the test score (Part 3).
Try it yourself
area and the distance_km of a flat. Split with test_size=0.2 and random_state=42. Print the training score, then the test score, each rounded to 3 decimals.Show a hint
X = df[["area", "distance_km"]], y = df["price"], then the split, fit on the training data, and model.score for each part.Show the solution
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
df = pd.read_csv("flats.csv")
X = df[["area", "distance_km"]]
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
print(round(model.score(X_train, y_train), 3))
print(round(model.score(X_test, y_test), 3))Output
0.928 0.926
3Reading the two scores
3.1What a normal difference looks like
The model of Part 2 has a training score of 0.953 and a test score of 0.952. The two numbers are almost equal, and that is the picture of a healthy model: it does on new flats what it does on the flats it learned from.
In general the test score is a little lower than the training score. The model was fitted to the training rows, so it has a small advantage there. A small gap is normal and nothing to repair.
There is no exact law for "small", but these rules of thumb are used in practice for R²:
| Training score and test score | What it says |
|---|---|
| both high, the test score lower by a few hundredths (0.95 and 0.93) | normal: a good model |
| both high, the test score slightly higher (0.94 and 0.95) | also normal: the test rows happened to be a little easier |
| training score high, test score lower by 0.1 or more (0.98 and 0.70) | overfitting: the model learned the training rows, not the pattern |
| both low (0.30 and 0.28) | underfitting: the model is too simple, or the features do not carry the answer |
So two questions are asked about every model, in this order:
- Is the test score good enough for the purpose? That is the quality of the model.
- How far is it from the training score? That is the diagnosis: a large gap means overfitting, two low scores mean underfitting.
The same reading works for the errors, with the direction turned round: a test RMSE that is much larger than the training RMSE is the sign of overfitting.
Read the two scores. What do they say?
1 of 8
Training score 0.95, test score 0.93
Try it yourself
Show a hint
Show the solution
Answer: (a) overfitting; (b) underfitting; (c) a good fit.
In (a) the gap is 0.35: the model does far worse on new rows than on the rows it learned from. In (b) both scores are low: the model is bad everywhere. In (c) both are high and two hundredths apart, which is a normal gap.
4Overfitting and underfitting
4.1Three models of the same data
Underfitting
too simple: misses the pattern
A good fit
follows the pattern, ignores the noise
Overfitting
follows the points, noise included
The three pictures show the same points. On the left the model is so simple that it misses the pattern. On the right the model is so flexible that it passes through every point: it has learned the noise. In the middle the model follows the pattern and leaves the noise alone.
4.2Underfitting
A model underfits when it is too simple to find the pattern in the data.
- How to recognise it: the training score is low, and the test score is low too. The model is bad everywhere, even on the rows it learned from.
- When it happens: the model is too simple for the data (a straight line for a clear curve); the features do not carry the answer (predicting a price from the floor alone); too few features are used.
- What helps: better or more features; a more flexible model. More rows do not help: a model that cannot describe the pattern cannot describe it with more data either.
On the flats, a model that knows only the floor:
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
X = df[["floor"]]
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
print(round(model.score(X_train, y_train), 3))
print(round(model.score(X_test, y_test), 3))Output
0.0 -0.021
Change it and run: replace "floor" by "area" and run: with a column that carries information, both scores rise to about 0.8.
Both scores are near 0: the floor alone says almost nothing about the price. (A test score slightly below 0 means that the model is a little worse than always predicting the mean price, as Topic 22 explained.)
4.3Overfitting
A model overfits when it learns the training data too closely: the noise and the accidents of those rows, and not only the pattern behind them.
- How to recognise it: the training score is very high, and the test score is much lower.
- When it happens: there are too few training rows for the number of features; the model is too flexible for the amount of data; features are used that have nothing to do with the target, and the model finds accidental patterns in them.
- What helps: more training rows; fewer features (leave out the ones that carry no information); a simpler model; regularization, the subject of Topic 26.
On the flats, a model that gets all ten columns, the five useless ones included, and only 14 flats to learn from:
First the data: all ten columns, the usual split, and then only the first 14 training flats.
from sklearn.model_selection import train_test_split
X = df.drop(columns="price")
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_small = X_train.iloc[:14]
y_small = y_train.iloc[:14]
print(X_small.shape, X_test.shape)Output
(14, 10) (40, 10)
Fourteen flats with ten features each, and the same 40 test flats as before. Now the model:
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_small, y_small)
print(round(model.score(X_small, y_small), 3))
print(round(model.score(X_test, y_test), 3))Output
0.996 0.566
Change it and run: change both 14 in the cell above to 100 and run the two cells again: with enough flats the gap closes.
df.drop(columns="price") is the table without the target: all ten features. iloc[:14] keeps the first 14 training rows.
The training score is almost perfect: with ten weights and only 14 flats, the model can bend to fit nearly every one of them. On the 40 test flats the score falls to about 0.57. The model did not learn how prices work. It learned those 14 flats.
4.4The three models side by side
| Model | Training rows | Features | Training score | Test score | Diagnosis |
|---|---|---|---|---|---|
| only the floor | 160 | 1 | 0.000 | underfitting | |
| the five columns of the flat | 160 | 5 | 0.953 | 0.952 | a good fit |
| all ten columns, 14 flats | 14 | 10 | 0.996 | 0.566 | overfitting |
Only the floor (underfitting)
The five columns of the flat (a good fit)
All ten columns, 14 flats (overfitting)
Without test data, the third model would look like the best of the three. Only the test score shows that it is the worst of the two models that learned anything.
Try it yourself
Show a hint
Show the solution
Answer: (a) better features; (b) more training rows; (c) overfitting.
(a) is underfitting: the model cannot describe the pattern, and more rows of the same kind do not change that. (b) is overfitting: more rows leave the model less room to follow accidents, and more features would give it even more freedom. (c) With almost as many weights as rows, the model can bend to fit nearly every row.
5Cross-validation
5.1One split is a matter of luck
Which 40 flats land in the test data is decided by chance. With another random_state the same model gets another test score:
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
X = df[["area", "rooms", "age", "floor", "distance_km"]]
y = df["price"]
for state in [1, 2, 3, 4, 5]:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=state)
model = LinearRegression()
model.fit(X_train, y_train)
print(state, round(model.score(X_test, y_test), 3))Output
1 0.948 2 0.918 3 0.951 4 0.958 5 0.941
The same data, the same model, the same code: five different scores. None of them is wrong. Each is the answer for one particular set of 40 test flats. A single split can be lucky (easy test rows) or unlucky, and from one number you cannot tell which.
5.2The idea: every row is test data once
Cross-validation removes the luck by repeating the split in an organised way. In 5-fold cross-validation:
- The data is cut into 5 equal parts, called folds.
- The model is trained on 4 folds and tested on the fifth.
- This is done 5 times, and each time another fold is the test data.
- The result is 5 scores. Their mean is the cross-validation score.
5.3Why this is better than one split
- Every row is used for testing exactly once, and for training four times. No row is wasted, and no row is tested by a model that saw it.
- The mean of five scores is steadier than one score. A lucky fold and an unlucky fold balance each other, just as the mean of five measurements is more reliable than a single one (Topic 17).
- The spread of the five scores is information too. Five scores close together: the model behaves the same whatever rows it gets. Five scores far apart: the model depends strongly on its training rows, and no single number describes it well.
The price is time: the model is trained five times, not once. For linear regression on 200 rows that is nothing. For a large model on millions of rows it matters.
5.4How many folds?
5 and 10 are the usual choices. More folds mean more training data in every round (with 10 folds, 90 percent) and more rounds to wait for. With little data, 10 folds use it better; with a lot of data, 5 are enough. There is nothing magic in the numbers: they are habits that work well.
5.5Cross-validation in Python
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
X = df[["area", "rooms", "age", "floor", "distance_km"]]
y = df["price"]
model = LinearRegression()
scores = cross_val_score(model, X, y, cv=5)
print(scores.round(3))Output
[0.927 0.946 0.947 0.948 0.966]
The five scores have a mean and a spread:
print(round(scores.mean(), 3))
print(round(scores.std(), 3))Output
0.947 0.012
cross_val_scoregets the model (not yet trained), the features, the target and the number of folds,cv=5. It does the five rounds of splitting, training and testing by itself.- For a regression model the score is R². The result is an array with the five scores.
scores.mean()is the number to report: R² is about 0.947.scores.std()is the spread: 0.012 is small, so the model is stable.
The five rounds of the cross-validation of the flats. Go through them one after the other.
Round 1: trained on 160 flats (the other four folds), tested on the 40 flats of fold 1. R² = 0.927
Scores so far: 0.927. Their mean: 0.927
One round is one split. Its score alone could be lucky or unlucky; the mean becomes steadier with every round.
A report then reads: "R² = 0.947 ± 0.012 in 5-fold cross-validation." That says more than "0.952 on one test set".
5.6What cross-validation shows about the three models
good = cross_val_score(LinearRegression(), df[["area", "rooms", "age", "floor", "distance_km"]], y, cv=5)
weak = cross_val_score(LinearRegression(), df[["floor"]], y, cv=5)
few = cross_val_score(LinearRegression(), df.drop(columns="price").iloc[:20], y.iloc[:20], cv=5)
print(good.round(2), round(good.mean(), 3))
print(weak.round(2), round(weak.mean(), 3))
print(few.round(2), round(few.mean(), 3))Output
[0.93 0.95 0.95 0.95 0.97] 0.947 [-0.04 -0.04 -0.04 -0.03 -0.02] -0.033 [-0.64 0.55 0.34 0.53 0.61] 0.276
- The good model: five scores close together, with a high mean.
- The model with only the floor: five scores close together, all bad. Stable, and stably wrong: underfitting.
- All ten columns on only 20 flats: the scores jump from below zero to 0.6. In every round the model is trained on 16 flats and learns something different. That is overfitting, seen through cross-validation.
5.7Where cross-validation fits in the recipe
Cross-validation is used to choose: which features, which model, which settings. The test data stays locked away during all of that, and is used once at the end for the final, honest number:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
scores = cross_val_score(model, X_train, y_train, cv=5)
print(round(scores.mean(), 3))Output
0.947
The cross-validation used the training data only. Now the model is trained on all of the training data and meets the test data for the first and only time:
model.fit(X_train, y_train)
print(round(model.score(X_test, y_test), 3))Output
0.952
The cross-validation score, calculated on the training data only, already predicted what the test data then confirmed.
Try it yourself
area, rooms, age, floor, distance_km). Print the mean of the ten scores, rounded to 3 decimals.Show a hint
cross_val_score(LinearRegression(), X, y, cv=10) gives ten scores; take their .mean().Show the solution
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
df = pd.read_csv("flats.csv")
X = df[["area", "rooms", "age", "floor", "distance_km"]]
y = df["price"]
scores = cross_val_score(LinearRegression(), X, y, cv=10)
print(round(scores.mean(), 3))Output
0.944
Try it yourself
Show a hint
Show the solution
Answer: (a) 40; (b) 160; (c) once; (d) 0.92.
Every fold is the test data in exactly one round, so every row is tested once and used for training four times.
6The bias-variance tradeoff
Underfitting and overfitting have a second pair of names, which explains why they happen. The error of a model on new data comes from two different sources.
6.1Bias
Bias is the error of a model that is too simple for the data. Such a model makes a strong assumption ("the price depends only on the floor", "the relationship is a straight line"), and when the assumption is wrong, the model is wrong in the same way whatever rows it is trained on. More data does not help: the model keeps missing the pattern, steadily.
High bias is underfitting.
6.2Variance
Variance is how much a model changes when it is trained on other rows. A very flexible model with little data fits every accident of its training rows. Train it on another sample and you get a clearly different model with clearly different predictions. Each of these models fits its own rows well and new rows badly.
High variance is overfitting.
6.3Four combinations
Think of every dot as the result of training the model on one sample of data, and of the centre of the target as the truth:
Low bias, low variance
the goal
High bias, low variance
underfitting
Low bias, high variance
overfitting
High bias, high variance
the worst case
| Low variance | High variance | |
|---|---|---|
| Low bias | the goal: right on average, and steady | overfitting: right on average, but every single model is far off |
| High bias | underfitting: steady, and steadily wrong | the worst case: wrong on average, and unsteady |
6.4Why it is a tradeoff
The two errors pull in opposite directions.
- A simple model (few features, a rigid shape) cannot follow the pattern closely: high bias. But it hardly changes from one sample to the next: low variance.
- A flexible model (many features, a shape that bends easily) can follow the pattern: low bias. But it also follows the noise of its training rows: high variance.
Making a model more flexible lowers the bias and raises the variance. Making it simpler does the opposite. The best model is in between: flexible enough to find the pattern, and not so flexible that it learns the noise.
- error on the training data
- error on the test data
One model, made more flexible step by step. Round dots: training points. Squares: test points, which the model does not see.
Flexibility 0: error on the training points 0.91, error on the test points 0.591
Too stiff: the curve misses the pattern. Both errors are large: underfitting, high bias.
The picture is the most important one of the lesson. As a model becomes more flexible, its error on the training data keeps falling. Its error on the test data falls at first, reaches a lowest point, and then rises again: from there on, the model is learning noise. The gap between the two curves is what Part 3 taught you to read.
6.5What to do
| The problem | How it shows | Why it happens | What helps |
|---|---|---|---|
| High bias (underfitting) | low training score, low test score | the model is too simple; the features do not carry the answer | add better features; use a more flexible model |
| High variance (overfitting) | high training score, much lower test score; cross-validation scores far apart | too few rows for the number of features; a model that is too flexible; useless features | get more training rows; remove features; use a simpler model; regularization (Topic 26) |
Two cures are often mixed up:
- More data cures high variance, not high bias. With more rows, a flexible model has less room to follow accidents. A model that is too simple stays too simple.
- More features cure high bias, and can cause high variance. Every feature gives the model more freedom. Useful features lower the bias; useless ones only add room for overfitting.
Try it yourself
Show a hint
Show the solution
Answer: (a) bias; (b) variance; (c) variance; (d) the bias falls and the variance rises.
A model that is too simple is wrong steadily: that is bias, and more rows do not repair it. A flexible model with little data follows its own rows: that is variance, and more rows calm it. Flexibility trades one error for the other, which is why the best model lies in between.
7Common mistakes
| Mistake | Why it is wrong | Right |
|---|---|---|
| Judging the model by its training score. | The training score is always flattering: the model was fitted to those rows. | Report the test score, or the cross-validation score. |
model.fit(X, y) with all rows, then model.score(X_test, y_test). | The model has seen the test rows; the test is no longer honest. | model.fit(X_train, y_train) |
model.fit(X_test, y_test) | The test data is never used for training. | fit on the training data only. |
| Mixing up the four results of the split. | The order is fixed: training features, test features, training target, test target. | X_train, X_test, y_train, y_test = train_test_split(X, y, ...) |
r2_score(y_train, y_pred) when y_pred was made from X_test. | The true answers and the predictions must belong to the same rows. | r2_score(y_test, y_pred) |
Leaving out random_state. | Every run gives another split and other numbers; results cannot be repeated or compared. | Set random_state to a fixed number. |
Trying many values of random_state and keeping the best score. | That is choosing the luckiest test set, not the best model. | Use cross-validation and report the mean. |
| "The training score is 0.99, so the model is excellent." | A very high training score with a much lower test score is overfitting. | Always look at both scores. |
| "The test score is lower than the training score, so the model overfits." | A small gap is normal. | Worry when the gap is large (about 0.1 or more for R²). |
| Trying to cure underfitting with more rows. | A model that is too simple stays too simple. | Better features, or a more flexible model. |
| Adding every available column as a feature. | Columns without information add nothing and give the model room to overfit. | Use the columns that can sensibly influence the target. |
| Using the test data again and again to choose features and settings. | After many looks, the choices are fitted to the test data, and its score becomes flattering too. | Choose with cross-validation on the training data; use the test data once at the end. |
8Solved problems
Six short problems, all in Python, all on flats.csv. Problems 2, 3 and 4 continue from the cell of Problem 1, and Problem 6 from Problem 5.
Problem 1: X and y
Read flats.csv. Take the area and the number of rooms as features and the price as the target. Print the shapes of X and y.
import pandas as pd
df = pd.read_csv("flats.csv")
X = df[["area", "rooms"]]
y = df["price"]
print(X.shape, y.shape)Output
(200, 2) (200,)
Why: X is a table: a list of column names in double brackets gives a DataFrame with 200 rows and 2 columns. y is one column: 200 values.
Problem 2: A split of 80 to 20
Split the X and y of Problem 1 into training and test data: 20 percent for testing, random_state=42. Print the four shapes.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(X_train.shape, X_test.shape)
print(y_train.shape, y_test.shape)Output
(160, 2) (40, 2) (160,) (40,)
Why: 20 percent of 200 rows are 40 test rows, and 160 remain for training. The features and the target are cut in the same places: row 17 of X_train and row 17 of y_train belong to the same flat.
Problem 3: Another size
Split the same data so that 30 percent of the rows are test data, with random_state=0. Print how many rows each part has.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
print(len(X_train), len(X_test))Output
140 60
Why: test_size=0.3 gives 60 test rows and 140 training rows. len of a table is its number of rows.
Problem 4: The same split every time
Split the data twice with random_state=42 and once with random_state=1. Each time print the row numbers (the index) of the first five test flats.
for state in [42, 42, 1]:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=state)
print(state, X_test.index[:5].tolist())Output
42 [95, 15, 30, 158, 128] 42 [95, 15, 30, 158, 128] 1 [58, 40, 34, 102, 184]
Why: the same random_state gives the same test flats, and another number gives others. The index shows that the rows were shuffled: the test data is not simply the end of the file.
Problem 5: Train on one part, judge on the other
Use the area, the rooms and the distance to the centre as features. Split 80 to 20 with random_state=42, train a linear regression on the training data, and print the training score and the test score.
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
df = pd.read_csv("flats.csv")
X = df[["area", "rooms", "distance_km"]]
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
print(round(model.score(X_train, y_train), 3))
print(round(model.score(X_test, y_test), 3))Output
0.94 0.927
Why: the two scores are high and close together: a good fit, without overfitting. They are a little lower than with five features in Part 2, because the age and the floor carry information too.
Problem 6: Five folds
For the features of Problem 5, run a 5-fold cross-validation. Print the five scores and their mean.
from sklearn.model_selection import cross_val_score
scores = cross_val_score(LinearRegression(), X, y, cv=5)
print(scores.round(3))
print(round(scores.mean(), 3))Output
[0.903 0.935 0.933 0.924 0.96 ] 0.931
Why: cross_val_score does the five splits itself, so no train_test_split is needed here. The five scores lie close together, and their mean is the number to report.
9Practice
One small project in eight steps, from the first import to the last score, on flats.csv. The steps continue from one another, like the cells of a notebook: every step uses what the steps before it created. Under every step there is a hint and a solution.
The task: predict the price of a flat from its area, rooms, age and distance to the centre, and judge the model fairly.
Steps 1 to 3: the data and the split
Read the file, choose the features and the target, put the test data aside.
- 1.Import pandas and read
flats.csvintodf. Print the shape ofdf.Show a hint
import pandas as pd, thendf = pd.read_csv("flats.csv")andprint(df.shape).Show one possible solution
Pythonimport pandas as pd df = pd.read_csv("flats.csv") print(df.shape)Output
(200, 11)
- 2.Make
Xfrom the columnsarea,rooms,ageanddistance_km, andyfromprice. Print both shapes on one line. This step continues from Step 1.Show a hint
A list of column names in double brackets:X = df[["area", "rooms", "age", "distance_km"]]. Thenprint(X.shape, y.shape).Show one possible solution
Python, continues from the cells aboveX = df[["area", "rooms", "age", "distance_km"]] y = df["price"] print(X.shape, y.shape)Output
(200, 4) (200,)
- 3.Split
XandyintoX_train,X_test,y_train,y_test: 25 percent for testing,random_state=7. Print the shapes ofX_trainandX_teston one line. This step continues from Step 2.Show a hint
from sklearn.model_selection import train_test_split, thentrain_test_split(X, y, test_size=0.25, random_state=7). It returns four pieces.Show one possible solution
Python, continues from the cells abovefrom sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7) print(X_train.shape, X_test.shape)Output
(150, 4) (50, 4)
Steps 4 to 6: the model
Train on the training data, compare the two scores, predict the test rows.
- 4.Create a
LinearRegressioncalledmodeland train it on the training data. Print the intercept (rounded to 2 decimals), then the weights (rounded to 2 decimals). This step continues from Step 3.Show a hint
model.fit(X_train, y_train), thenprint(round(model.intercept_, 2))andprint(model.coef_.round(2)).Show one possible solution
Python, continues from the cells abovefrom sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train, y_train) print(round(model.intercept_, 2)) print(model.coef_.round(2))Output
44.35 [ 1.34 9.73 -0.52 -3.48]
- 5.Print the training score, then the test score, each rounded to 3 decimals. Is the gap normal? This step continues from Step 4.
Show a hint
model.score(X_train, y_train)andmodel.score(X_test, y_test). Two high scores that are almost equal are a good fit.Show one possible solution
Python, continues from the cells aboveprint(round(model.score(X_train, y_train), 3)) print(round(model.score(X_test, y_test), 3))Output
0.948 0.945
- 6.Store the predictions for the test rows in
y_pred. Print the first five predictions (rounded to 1 decimal), then the first five true prices,y_test.values[:5]. This step continues from Step 4.Show a hint
y_pred = model.predict(X_test), thenprint(y_pred[:5].round(1))andprint(y_test.values[:5]).Show one possible solution
Python, continues from the cells abovey_pred = model.predict(X_test) print(y_pred[:5].round(1)) print(y_test.values[:5])Output
[274. 103.7 178.2 236. 240.1] [272 108 185 262 238]
Steps 7 and 8: the measures
The errors on the test data, and a cross-validation to confirm them.
- 7.Print R², MSE and RMSE on the test data, on three lines: R² rounded to 3 decimals, the other two to 2 decimals. This step continues from Step 6.
Show a hint
r2_score,mean_squared_errorandroot_mean_squared_errorfromsklearn.metrics, each withy_testfirst andy_predsecond.Show one possible solution
Python, continues from the cells abovefrom sklearn.metrics import mean_squared_error, r2_score, root_mean_squared_error print(round(r2_score(y_test, y_pred), 3)) print(round(mean_squared_error(y_test, y_pred), 2)) print(round(root_mean_squared_error(y_test, y_pred), 2))Output
0.945 227.89 15.1
- 8.Run a 5-fold cross-validation of a linear regression on
Xandy. Print the mean of the five scores, rounded to 3 decimals. Does it agree with the test score of Step 7? This step continues from Step 4.Show a hint
from sklearn.model_selection import cross_val_score, thenscores = cross_val_score(LinearRegression(), X, y, cv=5)andprint(round(scores.mean(), 3)). When the mean agrees with the test score of Step 7, the model is good and the one split was not a lucky accident.Show one possible solution
Python, continues from the cells abovefrom sklearn.model_selection import cross_val_score scores = cross_val_score(LinearRegression(), X, y, cv=5) print(round(scores.mean(), 3))Output
0.94
10Check yourself
Eight questions. Every question has one right answer.
0 of 8 answered.
11Quick summary
| Idea | In one sentence |
|---|---|
| Train/test split | Put a part of the rows aside before training, and judge the model on that part |
| Test score | The score that counts: it estimates how the model does on new data |
| Normal gap | The test score is a little lower than the training score; a few hundredths of R² are normal |
| Overfitting | High training score, much lower test score: the model learned the rows, not the pattern |
| Underfitting | Low score on both parts: the model is too simple or the features are too weak |
| Cross-validation | Cut the data into k folds, test on each fold once, report the mean of the k scores |
| Bias | The error of a model that is too simple: underfitting |
| Variance | How much a model changes with its training rows: overfitting |
| The tradeoff | More flexibility lowers the bias and raises the variance; the best model is in between |
| Code | What it does |
|---|---|
train_test_split(X, y, test_size=0.2, random_state=42) | returns X_train, X_test, y_train, y_test |
model.fit(X_train, y_train) | trains on the training data only |
model.score(X_test, y_test) | R² on the test data |
y_pred = model.predict(X_test) | the predictions for the test rows |
r2_score(y_test, y_pred) | R² |
mean_squared_error(y_test, y_pred) | MSE |
root_mean_squared_error(y_test, y_pred) | RMSE |
cross_val_score(model, X, y, cv=5) | the five scores of a 5-fold cross-validation |
Rules to keep
- Split first.
fitsees the training data only. - Report the test score, and compare it with the training score.
- A small gap is normal. A large gap is overfitting. Two low scores are underfitting.
- One split is one piece of luck. Cross-validation gives a steadier number.
- Underfitting: better features or a more flexible model. Overfitting: more rows, fewer features, a simpler model.
- The test data is used once, at the end.
What comes next
In this lesson every column was already a number on a scale the model could use. Real tables are not so kind: an area in tens stands next to a price in thousands. Topic 24, feature engineering with the scaling of numerical values, brings features to the same scale, and it will use the split of this lesson from its first example on.