Sub topic 5
Supervised learning: learning from labeled examples
This chapter assumes you can read basic Python, know what a NumPy array or table of numbers is, and have seen the terms feature and label from the earlier chapter on examples, features, and labels. It builds the working model of supervised learning that the next chapters on classification, regression, and loss functions refine.
The core idea
Supervised learning is a way of training a model from examples where the correct answer is already known. Each training example pairs an input with the output you want the model to produce. The model's job is to find a rule that maps inputs to outputs, so it can produce good outputs for inputs it has never seen.
The word "supervised" refers to the labels. They act as a teacher: for every training example, the learning algorithm can compare its prediction with the right answer and measure the error.
In notation, you have a dataset of pairs (x, y):
xis the feature vector, the measurable inputs for one example.yis the label (also called the target), the answer you want to predict.- The model is a function
fwith adjustable parameters, and it produces a predictionŷ = f(x).
Training adjusts the parameters until ŷ is close to y on the training examples. Success is judged by how close ŷ is to y on new examples.
The supervised workflow
Almost every supervised project follows the same sequence of steps. The details vary, but the shape does not.
- Collect labeled data. Someone or something must supply the correct answer for each example. This is often the most expensive step.
- Split the data. Keep a portion aside so you can test the model on examples it did not learn from.
- Fit the model. The algorithm adjusts parameters using only the training set.
- Predict. The fitted model maps features to predictions.
- Evaluate. Compare predictions with the true labels on the held-out set.
Later chapters explain why the split matters and how to choose metrics. For now, notice that labels are used in two different places: during fitting, to guide learning, and during evaluation, to grade the result.
A complete example
The following program trains a classifier on the iris dataset, which contains 150 flowers described by four measurements and labeled with one of three species. It follows the workflow above.
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))Read it with the workflow in mind:
Xhas shape(150, 4): 150 examples, 4 features each.yhas shape(150,): one label per example.train_test_splitholds out 25% of the data.stratify=ykeeps the species in the same proportions in both parts.random_state=0makes the split repeatable.model.fit(X_train, y_train)is the supervised step. It receives both features and labels.model.predict(X_test)receives only features. The model never seesy_testuntilaccuracy_scorecompares it with the predictions.
The final line prints the fraction of test flowers classified correctly, a number between 0 and 1.
What the fit/predict contract tells you
The asymmetry between fit(X, y) and predict(X) is the defining feature of supervised learning. At training time you need labels. At prediction time you do not, and in real use you usually cannot have them, because predicting the label is the whole point.
This leads to a practical rule: every feature must be available at prediction time. If a feature is only known after the outcome happens, the model will look excellent in testing and fail in production. This problem is called data leakage, and it is among the most common supervised-learning errors.
Two kinds of target
The type of the label determines the type of problem.
| Label type | Problem | Example label | Example task |
|---|---|---|---|
| Category from a fixed set | Classification | `"spam"` or `"not spam"` | Flag unwanted email |
| Continuous number | Regression | `212500.0` | Estimate a house price |
Both are supervised because both learn from labeled pairs. They differ in the form of the output and therefore in the loss functions and metrics they use. The next two chapters treat each in detail.
Some tasks blur the line. Predicting a star rating from 1 to 5 can be treated as classification with five classes or as regression on a number. Treating it as classification ignores that 4 is closer to 5 than to 1. Treating it as regression assumes the gaps between ratings are equal. Choose based on what the answer will be used for.
A baseline for comparison
A score has no meaning alone. An accuracy of 0.95 sounds strong, but if 95% of your examples belong to one class, a model that always predicts that class matches it. Always compare against a trivial baseline.
from sklearn.datasets import load_iris
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
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, test_size=0.25, random_state=0, stratify=y
)
baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(X_train, y_train)
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
print("baseline:", baseline.score(X_test, y_test))
print("model: ", model.score(X_test, y_test))DummyClassifier ignores the features and always predicts the most common training label. On iris the three species are balanced, so the baseline lands near one in three, and the real model should beat it by a wide margin. On an imbalanced dataset the gap would be much smaller, and the baseline shows you how much of the model's score is real learning.
Where labels come from, and why it matters
A supervised model can only be as good as its labels. Labels come from several sources, each with its own risks:
- Human annotation. People tag images, review documents, or grade outcomes. Annotators disagree, get tired, and apply guidelines inconsistently.
- Recorded outcomes. Whether a customer cancelled, or whether a loan was repaid. These labels are objective but arrive late, and they only exist for decisions that were actually made.
- Measurements. A sensor reading or a lab result. These carry measurement noise.
The model learns whatever relationship the labels contain, including their mistakes and biases. If past loan officers rejected qualified applicants from some group, a model trained on those decisions will reproduce the pattern. The model has no way to know the labels were wrong.
Common errors
These mistakes appear again and again in supervised projects.
Evaluating on training data
A model can score highly on the data it was fitted to simply by memorizing it. Only a held-out score estimates performance on new data. The chapters on generalization and evaluation cover this in depth.
Leaking information from the test set
Any step that learns from data, such as scaling features or choosing which features to keep, must be fitted on the training set only. If you compute the mean of the whole dataset before splitting, information from the test set has influenced training.
Confusing the label with a feature
If a column that is derived from the label ends up in X, the model will find it and appear nearly perfect. A column such as "refund issued" in a model that predicts "customer was unhappy" is an example.
Assuming the future looks like the past
Supervised learning assumes that new examples come from the same distribution as the training examples. When the world changes, accuracy drops, and nothing in the model warns you. Monitor performance after deployment.
Ignoring class balance
With rare categories such as fraud, plain accuracy rewards a model that never predicts the rare class. Check per-class results and use metrics suited to imbalance.
Summary of the model
Put together, the working model is short:
- You supply labeled pairs
(x, y). - An algorithm picks parameters that make predictions match labels on the training data.
- You judge the result on labeled data the model did not train on.
- You deploy it to predict labels where none exist.
Every step after the first depends on the quality and honesty of the labels and the split.
Exercise
A team builds a model to predict whether a hospital patient will be readmitted within 30 days. One feature in X is "number of follow-up appointments attended in the 30 days after discharge". The model scores very high on the test set but performs poorly when used at discharge time. Explain what went wrong, and state the rule that would have prevented it.
Show answer
The follow-up feature is data leakage. It is only known after the 30-day window ends, so it is not available at discharge, which is when the prediction must be made. The feature is also closely tied to the outcome, because patients who are readmitted often attend different follow-ups. The test set contained this feature, so the score looked excellent, but at prediction time it does not exist. The rule is that every feature must be available at prediction time. The team should remove the feature and rebuild the model with only information known at discharge.
Exercise
You train a classifier on a dataset where 90% of examples belong to class A. It reports 90% accuracy on the test set. What simple check would tell you whether it learned anything, and what would you expect to see if it had not?
Show answer
Fit a baseline that always predicts the most frequent class, such as DummyClassifier with strategy "most_frequent", and score it on the same test set. It would also reach about 90% accuracy. If the real model's score is no better than the baseline's, it learned nothing useful beyond the class proportions, and you should look at per-class results as well as overall accuracy.