Supervised Learning
Most machine learning in production is supervised: a model learns from examples where the right answer is known, then predicts the answer for new examples. It is called supervised because the labels act like a teacher who marks every training example.
The setting
The training data is a set of pairs : an input (a vector of features) and its label . The goal is a function such that for new pairs drawn from the same source, not just the training ones.
Two kinds of supervised problem cover almost everything:
| Regression | Classification | |
|---|---|---|
| Label | a number | a category from a fixed set |
| Examples | house price, temperature tomorrow, delivery time | spam or not, digit 0–9, disease present or absent |
| Typical loss | squared error | cross-entropy (log-loss) |
| Typical metrics | mean absolute error, | accuracy, precision, recall, F1 |
| Typical models | linear regression, trees, boosting, neural nets | logistic regression, trees, boosting, kNN, SVM, neural nets |
Classification with two classes is binary; with more it is multi-class. When each example can have several labels at once (a photo with a dog and a cat) it is multi-label.
The workflow
- Collect examples with labels.
- Split them: a training set to learn from and a test set kept aside to measure performance at the end (often also a validation set for choosing hyperparameters).
- Fit a model on the training set.
- Evaluate on the test set with a metric that fits the problem.
k-nearest neighbours from scratch
The simplest supervised method makes no assumptions at all: to classify a new point, find the training examples closest to it and take a majority vote of their labels. Closeness is the usual Euclidean distance,
The example implements it in a few lines of NumPy on the iris flowers, then checks the answer against scikit-learn.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
X, y = load_iris(return_X_y=True) # 150 flowers, 4 measurements, species label
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1, stratify=y)
def knn_predict(X_train, y_train, x, k=5):
dist = np.sqrt(((X_train - x) ** 2).sum(axis=1)) # distance to every labelled example
nearest = y_train[np.argsort(dist, kind="stable")[:k]]
return np.bincount(nearest).argmax() # majority vote of the k nearest labels
pred = np.array([knn_predict(X_train, y_train, x) for x in X_test])
print("from scratch: test accuracy", round(np.mean(pred == y_test), 3))
sk = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
print("scikit-learn: test accuracy", round(sk.score(X_test, y_test), 3))
print("same predictions:", bool(np.all(sk.predict(X_test) == pred)))from scratch: test accuracy 0.978
scikit-learn: test accuracy 0.978
same predictions: True
Both versions classify 44 of the 45 test flowers correctly (0.978) and agree on every prediction. kNN's "training" only stores the data; all the work happens at prediction time. Most other methods do the opposite: they compress the data into parameters during training, as in Models, Parameters and Loss.
Regression and classification side by side
The same scikit-learn interface handles both kinds of label. The diabetes data has a numeric label (a measure of disease progression one year later); the wine data has a class label (one of three cultivars).
from sklearn.datasets import load_diabetes, load_wine
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_absolute_error, accuracy_score
# Regression: the label is a number (disease progression one year later).
X, y = load_diabetes(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
reg = LinearRegression().fit(X_tr, y_tr)
print("regression first 3 predictions:", reg.predict(X_te[:3]).round(1), " true:", y_te[:3])
print(" mean absolute error:", round(mean_absolute_error(y_te, reg.predict(X_te)), 1))
# Classification: the label is a category (one of three wine cultivars).
X, y = load_wine(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)
clf = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr)
print("classification first 3 predictions:", clf.predict(X_te[:3]), " true:", y_te[:3])
print(" accuracy:", round(accuracy_score(y_te, clf.predict(X_te)), 3))regression first 3 predictions: [241.8 250.1 165. ] true: [321. 215. 127.]
mean absolute error: 45.1
classification first 3 predictions: [2 0 1] true: [2 0 1]
accuracy: 1.0
The regression predictions are numbers and are judged by how far off they are: on average 45.1 units (the label ranges from 25 to 346). The classifier's predictions are categories and are judged right or wrong: all 45 test wines are correct, an easy data set. A perfect score on a small test set is worth double-checking; it is more often a sign of an easy problem or of a leak than of a perfect model.
Where the labels come from
Labels are the expensive part of supervised learning. They come from:
- records of the outcome: the sale price, whether the loan was repaid, whether the customer churned;
- human annotation: people tagging images, transcribing audio, marking spam, often with guidelines and quality checks;
- experts: radiologists, lawyers, engineers, whose time is costly;
- implicit feedback: clicks, purchases, time spent, which are cheap but noisy and biased.
Label quality limits model quality. A model trained on labels with 10 % errors learns those errors too. When labels are scarce, the next lessons offer alternatives: semi-supervised, self-supervised and active learning. The Classical ML Algorithms course covers the supervised methods one by one.
Pitfalls
- Testing on training data. It measures memory. Keep a test set the model never sees.
- The label is not what you care about. Predicting "clicked" is not the same as predicting "satisfied". Choose labels that reflect the real goal.
- Leakage through features. A feature that is only known after the outcome (for example "account closed date" when predicting churn) makes the model look perfect in testing and useless in practice.
Practice
- Regression or classification? (a) the number of bikes rented tomorrow, (b) whether a review is positive, neutral or negative, (c) the age of a person in a photo, (d) which of 1000 object types appears in an image.
Answer
(a) regression (a count, usually treated as a number); (b) multi-class classification; (c) regression, though it is sometimes turned into classification by age band; (d) multi-class classification.
- In the kNN code, what does
kind="stable"innp.argsortguarantee, and why does it matter for matching scikit-learn?
Answer
A stable sort keeps equally distant training points in their original order. When several neighbours are tied in distance, the choice of which ones count among the nearest is then deterministic, and the vote matches a library that breaks ties the same way.
Test yourself
What makes a learning problem supervised?
- A person watches the training
- Every training example comes with its correct label
- The model is small
- The data is unlabelled
Predicting the number of minutes until a parcel is delivered is…
- classification
- regression
- clustering
- reinforcement learning
Where does kNN do most of its work?
- During training, by fitting weights
- At prediction time, by measuring distances to all stored examples
- During data collection
- It does no work
A churn model uses the feature 'date the account was closed'. Why is that a problem?
- Dates cannot be features
- The feature is only known after the outcome, so it leaks the label
- It makes the model too small
- It is a categorical feature