LearnPy Hub
Machine LearningAdvancedLesson 30 of 32

Machine Learning: scikit-learn

Watch the ideaLearning from examples
X = [[150, 3], [160, 3], [140, 8], [130, 9]]
y = ["apple", "apple", "orange", "orange"]
X (features) | y (label)
weightsweetlabel
1503apple
1603apple
1408orange
1309orange

Each row is one example: its features (X) and the right answer, its label (y).

1Level 1 · BasicsBasics

So far you've told the computer exactly what to do. In machine learning you show it examples instead, and it works out the rule itself. scikit-learn (imported as sklearn) is Python's most popular library for this. In this lesson you'll build a classifier: a model that looks at measurements and decides which group something belongs to.

The first run downloads scikit-learn into your browser (about 30 MB), so it can take up to a minute. After that it's quick.

Features and labels

Every example has features (the measurements, called X) and a label (the answer, called y). To sort fruit, the features might be weight and sweetness, and the label is "apple" or "orange".

WordMeaningIn code
Featureswhat we measure, one row per exampleX (a 2-D list or array)
Labelthe right answer for each rowy (a 1-D list or array)
Modellearns the rule from X and yKNeighborsClassifier()
Classificationpredicting a group (a category)model.predict(...)

The scikit-learn pattern: create, fit, predict

Every model in scikit-learn is used the same three steps:

from sklearn.neighbors import KNeighborsClassifier

model = KNeighborsClassifier(n_neighbors=3)   # 1. create
model.fit(X, y)                               # 2. learn from examples
model.predict([[150, 7]])                     # 3. answer new questions

k-nearest neighbours (KNN) is a simple, friendly first model: to classify a new point it finds the k closest training examples and takes a vote.

Train/test split: don't mark your own homework

A model that's tested on the same examples it learned from will look better than it really is. So we hide some data: the model learns from the training set and is marked on the test set it has never seen.

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=42, stratify=y)

test_size=0.25 keeps a quarter for testing. random_state makes the shuffle the same every run, so your results can be repeated. stratify=y keeps the same mix of classes in both parts.

Accuracy

Accuracy is the share of test examples the model got right: accuracy_score(y_test, predictions), or simply model.score(X_test, y_test). 0.95 means 95% correct.

The confusion matrix

Accuracy is one number; the confusion matrix shows which mistakes were made. Each row is the true class and each column is the predicted class. Numbers on the diagonal are correct answers; anything off the diagonal is a mix-up.

from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_test, predictions))

See it in actionWhat a classifier does

Before using any library, here is the idea by hand. To label the new fruit we find the closest known fruit and copy its label. That is 1-nearest-neighbour.

Step-by-step

Try it yourselfExample 1: Your first model

The same fruit, now with scikit-learn. fit() learns from the examples and predict() labels new fruit. Try changing the weights and sweetness of the new fruit.

example_1.py
Output appears here
Fill in the blanks

Learn, then answer

Fill the blanks so the model learns from the examples and then labels a new fruit. The program prints orange.

blanks.py
from sklearn.neighbors import KNeighborsClassifier
X = [[150, 3], [160, 3], [140, 8], [130, 9]]
y = ["apple", "apple", "orange", "orange"]
model = KNeighborsClassifier(n_neighbors=1)
model.(X, y)
print(model.([[135, 9]])[0])
Fix the bug

One fruit, two brackets

This should print the label for one new fruit, apple, but it crashes. predict wants a list of rows, even for a single fruit. Fix the last line.

buggy.py

Example 2: A real dataset

The iris dataset has 150 flowers, 4 measurements each, and 3 species. It comes with scikit-learn, so there's nothing to download.

example_2.py
Output appears here

Example 3: Splitting into train and test

A quarter of the flowers are held back for the test. stratify=y keeps all three species in both parts.

example_3.py
Output appears here
Fill in the blanks

Hold some back

Fill the blanks so a fifth of the 150 flowers go to the test set and the split is the same every run. It prints 120 30.

blanks.py
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, =0.2, =0)
print(len(X_train), len(X_test))

Example 4: Train, predict and measure accuracy

The model learns from the training flowers and is marked on flowers it has never seen. Change n_neighbors and watch the accuracy.

example_4.py
Output appears here
Fix the bug

Marking its own homework

This program reports an accuracy of 1.0 because it tests the model on the flowers it learned from. Score it on the test set instead. It should print 0.947.

buggy.py
Your turn

Swap the model

Every scikit-learn model uses fit and predict. Train a DecisionTreeClassifier(max_depth=2, random_state=0) on the training flowers and print its test accuracy rounded to 3 places: 0.921.

my_code.py

Example 5: The confusion matrix

Rows are the true species, columns are the predicted species. One virginica was mistaken for a versicolor. The chart below draws the same matrix.

example_5.py
Output appears here
Your turn

Count the right answers

The starter builds a confusion matrix for the iris test set. Print how many test flowers were predicted correctly: the sum of the matrix's diagonal. The answer is 37.

my_code.py

2Level 2 · IntermediateBeyond accuracy: precision, recall and choosing k

When accuracy fools you

Imagine 95 healthy patients and 5 sick ones. A lazy model that always says "healthy" is 95% accurate, yet it misses every sick patient. For one class we look closer:

MeasureQuestion it answers
PrecisionOf the ones the model called positive, how many really were?
RecallOf the ones that really were positive, how many did the model find?

precision_score(y_true, y_pred) and recall_score(y_true, y_pred) compute them for a yes/no (binary) problem. classification_report prints precision, recall and the F1 score (a balance of the two) for every class at once.

Choosing k

n_neighbors is a hyperparameter: a setting you choose, not something the model learns. A tiny k follows every quirk of the training data; a huge k ignores detail. Try several values and compare their test scores.

Example 6: Precision and recall

1 means "sick". The model found 3 of the 4 sick patients (recall 0.75), and 3 of its 4 "sick" calls were right (precision 0.75).

example_6.py
Output appears here

Example 7: Comparing values of k

Every k is trained on the same split and scored on the same test set, so the comparison is fair. Then a full report for the chosen model.

example_7.py
Output appears here

3Level 3 · AdvancedOverfitting, other models and cross-validation

Overfitting

A model overfits when it memorises the training data instead of learning the pattern. The warning sign: a high training score but a lower test score. A decision tree with no depth limit can score 100% on its training data.

Swapping models

Because every scikit-learn model uses fit and predict, you can try a different one by changing a single line: DecisionTreeClassifier, LogisticRegression, KNeighborsClassifier...

Cross-validation

One split can be lucky or unlucky. k-fold cross-validation splits the data into, say, 5 parts, trains 5 times and tests on each part once. cross_val_score(model, X, y, cv=5) returns the 5 scores; their mean is a steadier estimate than a single test score.

Scaling features

KNN measures distance, so a feature in grams (hundreds) swamps one on a 1-10 scale. StandardScaler puts every feature on a similar scale. Join it to the model with make_pipeline(StandardScaler(), KNeighborsClassifier()) so the scaling is learned only from the training data.

Example 8: Spotting overfitting

The breast cancer dataset has 569 tumours with 30 measurements each. The unlimited tree is perfect on its training data but drops on the test set. Limiting the depth to 4 narrows the gap and here scores better on unseen tumours.

example_8.py
Output appears here

Example 9: Cross-validation and a pipeline

Five scores, one per fold, and their mean. The pipeline scales the features inside each fold, so no test data leaks into training.

example_9.py
Output appears here
Always test on unseen dataNever judge a model on the data it learned from. Split first, fit only on the training set, and score on the test set. Set random_state so you (and your teacher) get the same split every time.
Exercise · predict the output

The model got these 5 test answers. What accuracy does the program print?

from sklearn.metrics import accuracy_score
y_true = [0, 1, 1, 0, 1]
y_pred = [0, 1, 0, 0, 1]
print(accuracy_score(y_true, y_pred))
Quick quiz · 5 questions
1. In scikit-learn, what are X and y?
2. Which method makes a model learn from examples?
3. Why do we split data into a training set and a test set?
4. A model gets 45 of 50 test examples right. What is its accuracy?
5. In a confusion matrix, where are the correct predictions?
Ready to practice machine learning: scikit-learn?

10 graded problems are waiting in Topic Practice.

Practice this topic →
Python Machine Learning: scikit-learn · LearnPy Hub