Paul's Python CoursePPC

Project 5 of 10, for Aaesha

Iris and Penguins Classifier

Name a penguin's species from its measurements, and an iris's with the same code, the way people are thought to name things: by the remembered examples most like it. k nearest neighbours from scratch, with k chosen on validation and tested once.

About an hour and a half, in 10 steps.

Sign up free to open itLog in

Act 6 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • AaeshaHow do you name a bird you've never seen? One theory is you remember the ones most like it and ask them.
  • AaeshaIn code that's called k nearest neighbours, and we'll try it on three kinds of penguin and Fisher's irises.
  • RiyaI've done it already with one nearest penguin, and it gets ninety-seven per cent on the penguins it learnt from.
  • AaeshaWell, every penguin it learnt from is its own nearest penguin, isn't it?

penguins.csv holds 342 real penguins of three species from Palmer Station in Antarctica, Adelie, Chinstrap and Gentoo, with bill length and depth, flipper length and body mass. iris.csv holds Fisher's 150 irises of three species, with four measurements each.

In classifier.py, name the species from the named animals most like it, from scratch:

  1. Load the MEASUREMENTS columns of DATASET. Lock a fifth of the rows away for testing, and split the rest into training and validation.
  2. Scale every measurement with the training rows' ruler.
  3. For each number of neighbours, k, let the k nearest training rows vote, and score the votes on the training rows and on the validation rows. Choose the k that does best on validation.
  4. Open the test rows once. Then name the species of NEW.

It starts with the penguins, by flipper length and body mass. The same code must work on the irises.

What it prints
penguins.csv: 342 rows, flipper_length, body_mass, 3 species
 k  training  validation
 1     0.966       0.721
 3     0.879       0.779
 5     0.854       0.838
 7     0.830       0.838
 9     0.796       0.868
11     0.796       0.853
15     0.796       0.853
21     0.791       0.809
Chosen k: 9
Test accuracy: 0.81
New: Gentoo, like 8 of the 9 nearest

What you learn

What's in it

  1. How alike is alike?
  2. Most like this one
  3. Ask the neighbours
  4. One neighbour or three
  5. Choosing k
  6. How Paul would do it
  7. Fix Yahya's version
  8. Make the classifier
  9. Ship it