Asiman Data School

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.

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. 1.Why a model must be judged on data it has not seen
  2. 2.How to split data into a training part and a test part with train_test_split
  3. 3.Why the score on the test data is the one that counts
  4. 4.What a normal difference between the training score and the test score looks like
  5. 5.Overfitting and underfitting: what they are, when they happen and how to recognise them
  6. 6.Cross-validation: several splits and their average, and why that is more reliable than one split
  7. 7.Bias and variance: the two sources of error, why they pull in opposite directions, and what to do about each
The words of this lesson
WordMeaning
training datathe rows the model learns from
test datathe rows that are put aside and used only to judge the finished model
training score, test scorethe R² of the model on the training data and on the test data
generalisationhow well a model works on data it has not seen
overfittingthe model has learned the training data too closely, noise included: high training score, much lower test score
underfittingthe model is too simple to find the pattern: low score on both parts
cross-validationsplitting the data several times, so that every row is test data once, and averaging the scores
foldone of the equal parts the data is cut into for cross-validation
biasthe error of a model that is too simple for the data
variancehow 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:

Training data: the model learns from itTest data: kept hidden until the end
Twenty pieces of data. Sixteen of them (80 percent) are the training data: the model learns from these rows. Four (20 percent) are the test data: they are locked away during the training and used only to judge the finished model.
  • The training data is what the model learns from. fit sees 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

A file has 500 rows. It is split so that 20 percent of the rows are test data. (a) How many rows are test data? (b) How many rows are training data? (c) Which part does fit see? (d) Which score is reported for the model?

Show a hint
20 percent of 500. The model learns from one part and is judged on the other.
Show the solution

Answer: (a) 100; (b) 400; (c) the training data; (d) the test score.

test rows=0.2×500=100training rows=500−100=400\begin{aligned} \text{test rows} &= 0.2 \times 500 = 100 \\[4pt] \text{training rows} &= 500 - 100 = 400 \end{aligned}

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.

Python
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:

Python, continues from the cells above
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
The data
ColumnMeaning
areathe area in m²
roomsthe number of rooms
agethe age of the building in years
floorthe floor
distance_kmthe distance to the city centre in km
photosthe number of photographs in the advertisement
listing_daythe day of the month on which the advertisement was posted
owner_agethe age of the owner
building_numberthe number of the building in its street
agent_idthe number of the estate agent
pricethe 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.

Download

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:

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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:

Python, continues from the cells above
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

  1. Read the data.
  2. Choose X (the features) and y (the target).
  3. Split: train_test_split(X, y, test_size=0.2, random_state=42).
  4. Create the model and fit it on X_train and y_train.
  5. Predict the test rows: y_pred = model.predict(X_test).
  6. Measure on the test data: R², MSE, RMSE, with y_test and y_pred.
  7. Compare the training score with the test score (Part 3).

Try it yourself

Train a model that knows only the 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
Python
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²:

What a normal difference looks like
Training score and test scoreWhat 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:

  1. Is the test score good enough for the purpose? That is the quality of the model.
  2. 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

Three models. Say what each pair of scores shows. (a) Training score 0.97, test score 0.62. (b) Training score 0.35, test score 0.33. (c) Training score 0.90, test score 0.88.

Show a hint
Look at the test score first, then at its distance from the training score.
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 same twelve points, three models. Left: so simple that it misses the pattern. Middle: it follows the pattern and leaves the noise alone. Right: so flexible that it bends towards every point, 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:

Python, continues from the cells above
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.

Python, continues from the cells above
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:

Python, continues from the cells above
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

The three models side by side
ModelTraining rowsFeaturesTraining scoreTest scoreDiagnosis
only the floor16010.000−0.021-0.021underfitting
the five columns of the flat16050.9530.952a good fit
all ten columns, 14 flats14100.9960.566overfitting
The training score and the test score of the three models of this part. Two short bars: underfitting. Two long bars of almost the same length: a good fit. A long bar and a much shorter one: 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

(a) A model has low scores on the training data and on the test data. Which helps more: better features, or more rows of the same kind? (b) A model has a training score of 0.99 and a test score of 0.60. Which helps more: more training rows, or more features? (c) A model with 10 features is trained on 12 rows. Which danger is larger?

Show a hint
Underfitting is cured by giving the model more to work with. Overfitting is cured by giving it less freedom or more rows.
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:

Python, continues from the cells above
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:

  1. The data is cut into 5 equal parts, called folds.
  2. The model is trained on 4 folds and tested on the fifth.
  3. This is done 5 times, and each time another fold is the test data.
  4. The result is 5 scores. Their mean is the cross-validation score.
5-fold cross-validation. The data is cut into five folds. In every round another fold is the test data (the highlighted block) and the other four are the training data. Five rounds give five scores, and their mean is the result.

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

Python, continues from the cells above
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:

Python, continues from the cells above
print(round(scores.mean(), 3))
print(round(scores.std(), 3))

Output

0.947
0.012
  • cross_val_score gets 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

Python, continues from the cells above
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:

Python, continues from the cells above
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:

Python, continues from the cells above
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

Run a cross-validation with 10 folds for the five columns of the flat (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
Python
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

A data set of 200 rows goes through a 5-fold cross-validation. (a) How many rows are test data in every round? (b) How many rows are training data in every round? (c) How often is each row test data? (d) The five scores are 0.90, 0.92, 0.94, 0.91 and 0.93. What is the cross-validation score?

Show a hint
Five equal folds. The cross-validation score is the mean of the five scores.
Show the solution

Answer: (a) 40; (b) 160; (c) once; (d) 0.92.

2005=40200−40=1600.90+0.92+0.94+0.91+0.935=4.605=0.92\begin{aligned} & \frac{200}{5} = 40 \qquad 200 - 40 = 160 \\[6pt] & \frac{0.90 + 0.92 + 0.94 + 0.91 + 0.93}{5} \\[4pt] & \quad = \frac{4.60}{5} = 0.92 \end{aligned}

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

Every dot is the result of training the model on one sample of data, and the centre of the target is the truth. Bias moves all the dots away from the centre in the same direction. Variance scatters them.
Four combinations
Low varianceHigh variance
Low biasthe goal: right on average, and steadyoverfitting: right on average, but every single model is far off
High biasunderfitting: steady, and steadily wrongthe 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
stiffthe best modelflexible
The error of nine models on the twelve points of the figure above, from the stiffest (a flat line, on the left) to the most flexible (on the right). The error on the training data falls with every step. The error on the test data falls at first, is lowest for the third model, and then rises again: from there on the model is learning noise. Left of the dashed line is underfitting (high bias), right of it overfitting (high variance).

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

What to do
The problemHow it showsWhy it happensWhat helps
High bias (underfitting)low training score, low test scorethe model is too simple; the features do not carry the answeradd better features; use a more flexible model
High variance (overfitting)high training score, much lower test score; cross-validation scores far aparttoo few rows for the number of features; a model that is too flexible; useless featuresget 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

(a) A model is too simple and misses the pattern in the same way on every sample. Is that bias or variance? (b) A model changes strongly when it is trained on other rows. Bias or variance? (c) What do more training rows mainly reduce? (d) What happens when a model is made more flexible?

Show a hint
Bias is the error of a model that is too simple. Variance is how much a model changes with its training rows.
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

Common mistakes
MistakeWhy it is wrongRight
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.

Python
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.

Python, continues from the cells above
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.

Python, continues from the cells above
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.

Python, continues from the cells above
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.

Python
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.

Python, continues from the cells above
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. 1.Import pandas and read flats.csv into df. Print the shape of df.
    Show a hint
    import pandas as pd, then df = pd.read_csv("flats.csv") and print(df.shape).
    Show one possible solution
    Python
    import pandas as pd
    
    df = pd.read_csv("flats.csv")
    
    print(df.shape)

    Output

    (200, 11)
  2. 2.Make X from the columns area, rooms, age and distance_km, and y from price. 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"]]. Then print(X.shape, y.shape).
    Show one possible solution
    Python, continues from the cells above
    X = df[["area", "rooms", "age", "distance_km"]]
    y = df["price"]
    
    print(X.shape, y.shape)

    Output

    (200, 4) (200,)
  3. 3.Split X and y into X_train, X_test, y_train, y_test: 25 percent for testing, random_state=7. Print the shapes of X_train and X_test on one line. This step continues from Step 2.
    Show a hint
    from sklearn.model_selection import train_test_split, then train_test_split(X, y, test_size=0.25, random_state=7). It returns four pieces.
    Show one possible solution
    Python, continues from the cells above
    from 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.

  1. 4.Create a LinearRegression called model and 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), then print(round(model.intercept_, 2)) and print(model.coef_.round(2)).
    Show one possible solution
    Python, continues from the cells above
    from 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]
  2. 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) and model.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 above
    print(round(model.score(X_train, y_train), 3))
    print(round(model.score(X_test, y_test), 3))

    Output

    0.948
    0.945
  3. 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), then print(y_pred[:5].round(1)) and print(y_test.values[:5]).
    Show one possible solution
    Python, continues from the cells above
    y_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.

  1. 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_error and root_mean_squared_error from sklearn.metrics, each with y_test first and y_pred second.
    Show one possible solution
    Python, continues from the cells above
    from 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
  2. 8.Run a 5-fold cross-validation of a linear regression on X and y. 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, then scores = cross_val_score(LinearRegression(), X, y, cv=5) and print(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 above
    from 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.

Question 1

1.Why is a part of the data put aside as test data?

Question 2

2.Which line trains the model correctly?

Question 3

3.A model has a training score of 0.94 and a test score of 0.92. What does that say?

Question 4

4.A model has a training score of 0.99 and a test score of 0.55. What is this called?

Question 5

5.A model has a training score of 0.21 and a test score of 0.19. What helps most?

Question 6

6.What does 5-fold cross-validation do?

Question 7

7.Why is the mean of five cross-validation scores more reliable than the score of one split?

Question 8

8.Which statement about bias and variance is right?

0 of 8 answered.

11Quick summary

Quick summary
IdeaIn one sentence
Train/test splitPut a part of the rows aside before training, and judge the model on that part
Test scoreThe score that counts: it estimates how the model does on new data
Normal gapThe test score is a little lower than the training score; a few hundredths of R² are normal
OverfittingHigh training score, much lower test score: the model learned the rows, not the pattern
UnderfittingLow score on both parts: the model is too simple or the features are too weak
Cross-validationCut the data into k folds, test on each fold once, report the mean of the k scores
BiasThe error of a model that is too simple: underfitting
VarianceHow much a model changes with its training rows: overfitting
The tradeoffMore flexibility lowers the bias and raises the variance; the best model is in between
Quick summary
CodeWhat 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

  1. Split first. fit sees the training data only.
  2. Report the test score, and compare it with the training score.
  3. A small gap is normal. A large gap is overfitting. Two low scores are underfitting.
  4. One split is one piece of luck. Cross-validation gives a steadier number.
  5. Underfitting: better features or a more flexible model. Overfitting: more rows, fewer features, a simpler model.
  6. 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.