Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 03 · 35 minutes

Split your data and score a model honestly

After this lesson you can
  • Split a dataset into a training part and a test part
  • Train a model on digits and predict labels it has not seen
  • Explain why a score on training data cannot be trusted
Lab files of this lesson (8)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A vendor offers a detector and says: "99 percent accurate." Your manager asks you one question: "Is that good?" Your first question back is: on which data? If the vendor scored the detector on the same data that trained it, the number says nothing about the real world. You will learn the one habit that makes a score worth reading, then you will apply it to a split of your own and report the honest number.

Recall

What is a class, and why did lesson 2 count the classes before any training?

A class is one possible label. The counts show whether the data is balanced. With a rare class, a model can score high by always guessing the common one.

In lesson 2, the overall score fell from 0.973 to 0.918 after the labels of one class were spoiled, but the score on that class fell much more. What did that show?

A single average can hide the damage in one class. You must read the score of each class that matters.

The idea

A model can memorise its training examples. If you test it on them, it looks perfect. To find out what it does on new data, you keep some examples hidden during training.

Split first, then train, then test
All labelled dataModelTest set75 percent to learn from: fit25 percent, hidden from the modelpredict on it, then score onceAlllabelleddataModelTest set123
  1. All labelled data → Model: 75 percent to learn from: fit
  2. All labelled data → Test set: 25 percent, hidden from the model
  3. Model → Test set: predict on it, then score once
PartUse
Training setThe model learns from it.
Test setThe model never sees it. You score on it once, at the end.

Accuracy is the share of right answers: 0.96 means 96 right in 100. Stratify means that each class keeps the same share in both parts. A random seed (random_state) fixes the random choice, so that you and everyone else get the same split and the same numbers.

The rule has no exception: the test set must not take part in any decision about the model.

Worked example

1. Split the data

Go to the lab folder and activate the environment. Create train_test.py. The function train_test_split cuts X and y into four parts: the training inputs, the test inputs, the training labels and the test labels, in this order. test_size=0.25 keeps a quarter of the examples for the test. random_state=42 is the seed: it is a number that you choose, and any fixed number works. stratify=y keeps the class shares equal in both parts.

The call of train_test_split
train_test_split(cut X and y into four partsX, y,inputs and labelstest_size=0.25,a quarter for the testrandom_state=42,the seedstratify=yequal class sharestrain_test_split(cut X and y into four partsX, y,inputs and labelstest_size=0.25,a quarter for the testrandom_state=42,the seedstratify=yequal class shares
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)
print("train:", X_train.shape, "test:", X_test.shape)

2. Train and score

model.score(X, y) predicts the labels of X and returns the share that match y. round(number, 4) keeps four decimals. max_iter=2000 gives the training program enough steps to finish. Add the following lines to the file.

model = LogisticRegression(max_iter=2000)
model.fit(X_train, y_train)

print("train accuracy:", round(model.score(X_train, y_train), 4))
print("test accuracy: ", round(model.score(X_test, y_test), 4))
cd ~/krlab/how-ai-works
source .venv/bin/activate
python train_test.py
train: (1347, 64) test: (450, 64)
train accuracy: 1.0
test accuracy:  0.9622
Accuracy of one model on two parts
Training part1.0Test part0.9622Training part1.0Test part0.9622

The model gets every training example right. On new examples it gets 96.2 percent. The honest number is the second one. The gap between them is small here, but it is never zero, and in lesson 7 you will see it grow.

3. Look at single predictions

predict returns a label for each row you give it. X_test[:10] is a slice: the first ten rows. Add these lines.

pred = model.predict(X_test[:10])
print("predicted:", pred)
print("real:     ", y_test[:10])
predicted: [8 0 9 1 5 6 7 8 1 5]
real:      [1 0 9 1 5 6 7 9 1 5]

Eight of ten are right. Two are not: a 1 read as an 8, and a 9 read as an 8. Which mistakes a model makes is as useful to know as how many. Lesson 6 counts them.

4. Change the seed and watch the number move

A test set of 450 examples is a sample. A different split gives a slightly different score. A for loop repeats its block once for each value in the list (0, 1, 2, 3, 4). Create seeds.py.

seeds.py

from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
for seed in (0, 1, 2, 3, 4):
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.25, random_state=seed, stratify=y
    )
    model = LogisticRegression(max_iter=2000).fit(X_train, y_train)
    print("random_state", seed, "-> test accuracy", round(model.score(X_test, y_test), 4))
python seeds.py
random_state 0 -> test accuracy 0.9578
random_state 1 -> test accuracy 0.9644
random_state 2 -> test accuracy 0.9578
random_state 3 -> test accuracy 0.9689
random_state 4 -> test accuracy 0.9756

The scores run from 0.958 to 0.976. None of them is the "true" accuracy. Report one score as "about 0.96", not as 0.9622, and never pick the seed that gives the best number.

5. The finished file

This is the whole file train_test.py as it stands after the steps above. The lab files of the course hold it.

The finished file: train_test.py

train_test.py

from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)
print("train:", X_train.shape, "test:", X_test.shape)

model = LogisticRegression(max_iter=2000)
model.fit(X_train, y_train)

print("train accuracy:", round(model.score(X_train, y_train), 4))
print("test accuracy: ", round(model.score(X_test, y_test), 4))

pred = model.predict(X_test[:10])
print("predicted:", pred)
print("real:     ", y_test[:10])

Your turn

Score the model on a split that is not the one above. There is no code here: adapt train_test.py.

  1. Split the digits with test_size=0.3, random_state=7 and stratify=y.
  2. Train a LogisticRegression(max_iter=2000) on the training part.
  3. Predict the whole test part. Count the examples that the model got wrong.
  4. Count how many examples of the digit 8 are in the test part.

Last, print the training accuracy too. Write one sentence that tells the vendor of the scenario which of the two numbers you want to see, and why.

Check yourself

A model scores 1.0 on its training data. Is it a perfect model?

No. It may have memorised the examples. Only the score on data that it has not seen tells you how it works in use.

Why do you fix random_state?

So that the split, and therefore every number, is the same on every run and on every machine. Without it you cannot tell a real change in the model from a change in the random split.

You try ten model settings and keep the one with the best test score. What is wrong?

You used the test set to make a decision, so it is no longer unseen. The best score is partly luck that you selected. Lesson 7 shows the fix: a third part of the data, called validation, for such choices.

Why use stratify=y?

It keeps the share of each class equal in the training and the test part. Without it, a rare class can be nearly missing from one part by chance.

Field notes

  • Data leakage is any path by which test information reaches training. Duplicates across the split, a scaler fitted on all the data, and features built from the label are common ones. Leakage gives scores that fail in production.
  • Split data in the way the world will split it. For logs, split by time (train on January to March, test on April), not at random. Random splits of time data let the model see the future.
  • If the same user, host or malware family appears on both sides of the split, the model can recognise the entity instead of the behaviour. Split by group.
  • Report the seed, the split and the library versions together with a score. A result that others cannot repeat is a claim, not a result.
  • Without max_iter=2000, scikit-learn prints a ConvergenceWarning on this data. Read such warnings: they say that the training did not finish.