Sub topic 5
Supervised learning: learning from labeled examples
This chapter assumes you can read basic Python, know what an array or table of numbers is, and remember high-school algebra and the idea of a function. You should also know what a mean and a variance are. Earlier chapters introduced examples, features, and labels. Here we use them to build a supervised model.
The working model
Supervised learning is learning a mapping from inputs to outputs using examples where the correct output is already known. Each training example has features (the inputs, often written X) and a label (the known answer, often written y). The model finds a pattern that links the two. Then it predicts labels for new examples whose answers it has not seen.
The word "supervised" refers to the labels. They act like a teacher that supplies the right answer for every training example.
The workflow is the same for almost every supervised model:
- Collect labeled examples.
- Split them into a training set and a test set.
- Fit the model on the training set.
- Predict on the test set and compare the predictions with the true labels.
A first example: classifying irises
The iris dataset has 150 flowers. Each flower has four measurements (the features) and a species (the label). The code below trains a classifier and scores it on data it never saw during training.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(accuracy_score(y_test, predictions))Three details matter here:
test_size=0.25keeps a quarter of the data out of training.stratify=ykeeps the species proportions the same in both sets.random_state=0makes the split repeatable.
The call model.fit(X_train, y_train) is where learning happens. The call model.predict(X_test) uses only the features. The labels y_test are used afterward, only to score the predictions.
A second example: predicting a number
The labels do not have to be categories. In the next example the label is a number. The data is synthetic and follows the line y = 3x + 2 with some random noise added.
import numpy as np
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(100, 1))
y = 3 * X[:, 0] + 2 + rng.normal(0, 1, size=100)
model = LinearRegression().fit(X, y)
print(model.coef_, model.intercept_)
print(model.predict([[5.0]]))The model recovers a slope close to 3 and an intercept close to 2. It was never told those numbers. It estimated them from the examples. Predicting for x = 5 should give a value near 17.
The next chapters cover the two task types in detail. Classification predicts a category, as with the species above. Regression predicts a number, as with this line.
Common errors
| Error | What goes wrong | Fix |
|---|---|---|
| Scoring on the training data | The score looks excellent, but it measures memorization, not performance on new data. | Always score on a held-out test set. |
| Leaking labels into features | A column that is derived from the label gives unrealistic accuracy. | Check that every feature would be available at prediction time. |
| Skipping stratification on a classification split | A rare class can end up missing from the test set. | Use `stratify=y`. |
| Passing a 1-D array as `X` | scikit-learn expects a 2-D array of shape `(n_examples, n_features)`. | Reshape with `X.reshape(-1, 1)` for a single feature. |
Exercise
In the iris example, which arguments does model.fit receive, and which does model.predict receive? Why must the test labels y_test stay out of both calls?
Show answer
fit receives the training features and training labels (X_train, y_train). predict receives only features (X_test). The test labels are kept out so the score measures how well the model handles examples it has not learned from. If they were used in training, the score would no longer show how the model performs on new data.
Exercise
A teammate trains a regression model, then reports its error measured on the same data it was trained on. What is wrong, and what would you change?
Show answer
The error on training data only shows how well the model fits examples it has already seen, so it is usually too optimistic. Split off a test set before training, fit on the training portion, and report the error on the test portion.