What learning is · lesson 13 of 13
Parts in this lesson
Atrain_test_split(..., stratify=y)2.5: one split, made first
Bmake_pipeline(StandardScaler(), KNeighborsClassifier())2.10: scaling inside the model
CGridSearchCV(pipe, {...}, cv=StratifiedKFold(...))2.9: choosing k without the test set
Dconfusion_matrix, classification_report2.8: what the test score is made of
E## Reportthe result, in a few honest sentences

Project: a penguin classifier

Last updated

Stage 0 ended with a question: can three species of penguin be told apart from four measurements? Now you answer it with a model, done properly from start to finish. Split off a test set and leave it alone, build a pipeline that scales and classifies, choose k with cross-validation, score on the test set once, and write a short report that claims no more than the numbers support.

By the end of this lesson you can

  • Split a dataset once, and keep the test set untouched until the end
  • Build a Pipeline of scaling and k-NN, and tune k with GridSearchCV and stratified folds
  • Score the chosen model once on the test set, and read its confusion matrix and classification report
  • Write a short, honest report of what the model can and can’t be trusted to do

Plan it

The question: given a penguin's bill length, bill depth, flipper length and body mass, which of the three species is it? And how often will the answer be right for penguins the model has never seen?

The data: the same penguins.csv as Stage 0's project: 344 penguins from Palmer Station, of which 342 have all four measurements.

What you'll make: one notebook that, run from the top,

  1. splits off a test set, stratified by species, and doesn't touch it again until the end,
  2. builds a pipeline of StandardScaler and k-NN,
  3. chooses k with 5-fold cross-validation on the training set,
  4. scores the chosen model on the test set, once, with a confusion matrix and a report per species,
  5. ends with a Markdown cell reporting the result honestly.

On your own computer, make it in the ml-course folder as 02-classifier.ipynb, with penguins.csv beside it. Here, the notebooks below run in the page.

Split first

The split comes before anything else, so nothing you do later can learn from the test penguins, even by accident (lesson 2.10):

02-classifier.ipynb

256 penguins to train and choose with, 86 to test with. stratify=y keeps each species' share the same in both (lesson 2.5); random_state=42 makes the split the same every run, so your numbers match these.

Choose k with cross-validation

Scaling goes inside the pipeline, so each cross-validation fold scales with its own training part (lesson 2.10). Then GridSearchCV tries every odd k from 1 to 31 with stratified 5-fold cross-validation, using only the 256 training penguins (lesson 2.9):

02-classifier.ipynb

Read the whole table, not just the winner. Every k scores between 0.973 and 0.984, so the choice hardly matters; the data is easy to separate once it's scaled. And three values tie at the top: k=1, 3 and 5 all score 0.984.

GridSearchCV breaks the tie by taking the first, k=1. But a tie is a decision for you, not for the order of a list. k=1 answers from a single neighbour, so one mislabelled or unusual penguin in the training data decides every answer near it (lesson 2.6). With the scores equal, the larger k is the safer bet: k=5. Make that choice now, and write down why, before looking at the test set. Choosing after would be tuning on the test set (lesson 2.9).

Score on the test set, once

Fit the chosen pipeline on all 256 training penguins and score it on the 86 test penguins:

02-classifier.ipynb
The test penguins’ confusion matrixtruth down the side, prediction across the top
predictedtruthAdelieAdelieChinstrapChinstrapGentooGentoo380001700031

86 of 86 on the diagonal (outlined) are right; every box off it is a kind of mistake.

All 86 right. The confusion matrix has nothing off the diagonal: 38 Adelie, 17 Chinstrap and 31 Gentoo, each called correctly. The report shows precision, recall and F1 of 1.000 for every species (lesson 2.8), with support, the number of test penguins of each species, beside them.

Pleasing, but read it carefully. 86 penguins is a small test: one mistake would have been 0.988, two 0.977. Cross-validation, which used 256 penguins five times over, said about 0.984. The honest estimate is about 98%, and 86 out of 86 is what this one test set happened to give. Nobody should expect a perfect score on the next 86 penguins.

Write the report

End the notebook with a Markdown cell. A good report says what the model does, how well, how you know, and where it would break. For example:

## Report

A k-NN classifier (k = 5, features standardised) tells Adelie,
Chinstrap and Gentoo penguins apart from bill length, bill depth,
flipper length and body mass.

- Cross-validation on 256 training penguins: 0.984 accuracy.
  Every k from 1 to 31 scored 0.973 or more.
- Test set, used once: 86 of 86 correct. With so few test penguins,
  I'd expect about 98% on new penguins, not 100%.
- k = 1, 3 and 5 tied in cross-validation; I chose 5, before testing,
  so no single training penguin decides an answer.

Limits: all the penguins come from three islands near Palmer Station,
measured between 2007 and 2009. Penguins from elsewhere, or measured
another way, might not look the same. And the model always names one
of these three species, even for a penguin that's none of them.

That last limit matters more than it looks. A classifier only knows the classes it was trained on, so an Emperor penguin would confidently be called one of the three. Saying what a model can't do is part of the result.

Finished

You've built and tested a classifier the way it should be done. Your notebook

  • splits once, first, and keeps the test set for the end,
  • scales inside a pipeline, so nothing leaks,
  • chooses k with stratified cross-validation, and breaks the tie for a stated reason,
  • scores on the test set once, and reads the confusion matrix and the report per species,
  • reports the result without claiming more than the numbers show.

Before you call it finished, restart the kernel and run every cell from the top. If it shows the same numbers, it's done.

Try next:

  • Use only the two bill measurements. Cross-validate again: how much is lost? (Stage 0's bill plot suggests not much.)
  • Leave out the scaler and cross-validate. How much worse is it, and why (lesson 2.4)?
  • Add island with one-hot encoding (lesson 2.3). You'll need a ColumnTransformer to scale the numbers and encode the island in one pipeline; look it up in the scikit-learn guide to pipelines.

k-NN keeps every training example and does all its work when asked. Stage 3 starts the other way round: linear regression, which learns a few numbers from the data and then forgets the data itself.

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning