Show contents
Chapter 1 of 7 · 20 min
Learning from data
By the end of this chapter, you'll be able to
- Explain the difference between programming rules and learning from examples
- Tell apart input variables, the label, regression and classification
- Write the k-nearest neighbours algorithm with numpy
- Measure a model's accuracy on test data
Examples rather than rules
In supervised learning, you have examples whose answer you know:
- the input variables (features), written
X: what you measure (the weight and length of a fruit, the area of a house…); - the label, written
y: the expected answer (the name of the fruit, the price of the house).
A model learns to predict y from X. If the label is a category, it is a classification; if it is a number, a regression.
We work with numpy, Python's computing library. Its arrays (np.array) are computed as a whole, like pandas columns:
import numpy as np
weights = np.array([310, 280, 900, 1100])
print(weights / 1000)
print(weights.mean(), weights.max())
X = np.array([[310, 11], [900, 22]])
print(X.shape, X[:, 0])
[0.31 0.28 0.9 1.1 ]
647.5 1100
(2, 2) [310 900]
X is a two-dimensional array: one row per example, one column per variable. X[:, 0] takes all the rows (:) of column 0.
A first model: k-nearest neighbours
A simple and formidable idea: to classify a new fruit, look at the k known fruits most alike, and vote. Likeness is measured by the distance between the points, as on a map.
import numpy as np
# Weight (g) and length (cm) of known fruits
X = np.array([[310, 11], [280, 10], [350, 12], [330, 11.5],
[900, 22], [1100, 25], [950, 23], [1200, 27]])
y = np.array(["mango"] * 4 + ["papaya"] * 4)
def predict(x, k=3):
distances = np.sqrt(((X - x) ** 2).sum(axis=1))
neighbours = np.argsort(distances)[:k]
values, counts = np.unique(y[neighbours], return_counts=True)
return str(values[np.argmax(counts)])
print(predict(np.array([400, 13])))
print(predict(np.array([1000, 24])))
mango
papaya
X - xsubtracts the new fruit from every row at once;.sum(axis=1)adds up along each row: you get one distance per known fruit;np.argsortgives the positions sorted from the smallest distance to the largest, and[:k]keeps the firstk;np.unique(…, return_counts=True)counts the votes for each label.
This model has not “learned” anything in the sense of a preliminary computation: it keeps the examples and consults them at each prediction. Other models, like the linear regression of the next chapter, summarise the examples in a few parameters.
The majority label becomes the prediction.
Text description of the animation
- We describe the new fruit with the same variables as the examples.
- We compute its distance to each of the 8 known fruits.
- We keep the 3 closest fruits.
- Each neighbour votes for its label.
- The majority label becomes the prediction.
Evaluate on test data
A model is only worth its predictions on cases it has never seen. So you set aside part of the examples, the test set, and measure the accuracy: the share of correct answers.
import numpy as np
rng = np.random.default_rng(seed=1)
mangoes = rng.normal([330, 11.5], [40, 1.2], size=(30, 2))
papayas = rng.normal([1000, 24], [150, 2.5], size=(30, 2))
X = np.vstack([mangoes, papayas])
y = np.array(["mango"] * 30 + ["papaya"] * 30)
order = rng.permutation(len(X))
test, train = order[:15], order[15:]
def predict(x, X_train, y_train, k=3):
distances = np.sqrt(((X_train - x) ** 2).sum(axis=1))
values, counts = np.unique(y_train[np.argsort(distances)[:k]], return_counts=True)
return values[np.argmax(counts)]
predictions = np.array([predict(x, X[train], y[train]) for x in X[test]])
print("Accuracy:", (predictions == y[test]).mean())
Accuracy: 1.0
rng.normal(means, deviations, size=…)generates simulated fruits around typical values. The seed (seed=1) makes the draw reproducible: you get the same numbers on every run;rng.permutationshuffles the positions, then 15 are set aside for testing and 45 for training;(predictions == y[test]).mean(): the mean of a boolean array is the share ofTrue.
The two fruits are easy to tell apart: the model never gets it wrong on this test. On real data, classes overlap and accuracy is lower.
Mini-lab: change kPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
The first run downloads numpy into your browser (a few megabytes, only once).
Your turn
Worked exercise
Worked exercise: the accuracy function
Write a function accuracy(predictions, truths) that returns the share of correct answers, rounded to 2 decimal places, then test it on the predictions ["A", "B", "A", "A", "A"] against the true labels ["A", "B", "A", "A", "B"]. What would be the accuracy of a model that always answers “A”?
Hint 1
Hint 2
np.full(5, "A") creates an array of 5 “A”.Show the solution and common mistakes
import numpy as np
def accuracy(predictions, truths):
return round(float((np.array(predictions) == np.array(truths)).mean()), 2)
truths = ["A", "B", "A", "A", "B"]
print(accuracy(["A", "B", "A", "A", "A"], truths))
print(accuracy(np.full(5, "A"), truths))
0.8
0.6
The tested model scores 0.8. The “always A” model scores 0.6 without learning anything, just because “A” is the majority. It is a baseline: a real model must do better, otherwise it is useless. Always compare your model with a baseline this simple.
Common mistakes:
- Comparing two Python lists with
==: you get a single boolean (are the lists identical?), not an element-by-element comparison. - Being satisfied with a high accuracy without a baseline: if 95% of cases are “A”, an accuracy of 95% is no better than always answering “A”.
Summary
- 1Supervised learning learns to predict a label y from input variables X, thanks to examples.
- 2Classification: the label is a category; regression: it is a number.
- 3k-nearest neighbours classifies a point by the vote of the k closest examples.
- 4A model is evaluated on a test set it has never seen, never on its training data.
- 5A simple baseline (always the majority class) tells whether a model really adds anything.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.