Classification · About 45 minutes
Classify flowers
A botanist measured 150 iris flowers: the length and width of the petals and of the sepals. Each flower is one of three species. You will predict the species from the four measurements.
- The data
- The Iris dataset that comes with scikit-learn: 150 flowers, 50 of each species.
- Before you start
- Do the bike demand project first, or make sure you know why a model needs a test set.
Open the notebook
The notebook has the data and an empty cell for each step. Keep it open next to this page.
Your own computer
Download the notebook, then open it with Jupyter.
Download notebook ↓uvx --with scikit-learn --with pandas --with matplotlib --from jupyter jupyter lab classify-flowers.ipynbStep 1
Split fairly and scale
Practice firstWrite Feature Scaling yourselfEasyWith three species, a random split can put too few of one species in the test set. A stratified split keeps the same share of each species in both sets.
Nearest-neighbor models use distances, so a feature with bigger numbers counts for more. Scaling puts every feature on the same range. Learn the scaling from the training data only. Otherwise information from the test set leaks into training.
Need more background? Read the lesson →In the notebook
Make a stratified 80/20 split. Put a StandardScaler in a pipeline so it learns from the training data only.
Step 2
Classify by nearest neighbors
Practice firstWrite K Nearest Neighbours yourselfMediumk-nearest neighbors (k-NN) does not learn weights. To classify a new flower, it finds the k training flowers closest to it and takes a vote.
It is simple and easy to inspect, so it is a good first classifier. Compare it with a baseline that always predicts the most common species.
Need more background? Read the lesson →In the notebook
Train a k-NN classifier with k = 5 and a most-frequent-class baseline. Predict the test set with both.
Step 3
Look at the mistakes
Practice firstWrite Confusion Matrix yourselfEasyAccuracy gives one number, but it does not show which species get mixed up.
A confusion matrix has one row for each true species and one column for each predicted species. The diagonal holds the correct answers. Every other cell is a mistake, and its position tells you which two species the model confused.
Need more background? Read the lesson →In the notebook
Compute accuracy and a confusion matrix. Print the measurements of each flower the model got wrong.
Check your work
Answer these in the last cell of the notebook.
- Which two species are hardest to tell apart?
- Does a different k help? Choose k without looking at the test set.
- How much better than the baseline is the model?