Supervised Learning
Supervised learning is training a model on labeled examples: inputs, called features, paired with the correct answer, called the label. The model learns the pattern linking them, then predicts labels for new inputs it has never seen. It is the most widely used kind of machine learning, behind spam filters, price estimates and fraud alerts.
This chapter uses scikit-learn (pip install scikit-learn), the standard Python library for classical machine learning, and one running question: will a family pay a school fee late?
Regression and Classification
| Kind | Predicts | Examples | Algorithms in this chapter |
|---|---|---|---|
| Classification | A category | Late or on time; spam or not | Logistic regression, trees, forests, k-NN, SVMs |
| Regression | A number | A house price; tomorrow's temperature | Linear regression (and regression versions of the others) |
Creating the Data
This program creates 1,000 made-up families' payment histories, with a fixed seed so everyone gets the same data. The comment describes the pattern hidden in it, which the models have to discover:
import numpy as np
import pandas as pd
rng = np.random.default_rng(24) # a fixed seed, so everyone gets the same data
n = 1000
families = pd.DataFrame({
"amount": rng.choice([15, 30, 45, 60, 250], n), # the fee being paid, in dollars
"past_late": rng.poisson(0.8, n), # late payments in the last year
"autopay": rng.random(n) < 0.35, # pays automatically
"months_enrolled": rng.integers(1, 60, n),
"opened_reminder": rng.random(n) < 0.6, # opened the reminder email
})
# Made-up rule behind the data, with randomness: past lateness raises the risk; autopay and reminders lower it,
# and large tuition payments are much riskier for families not on autopay
score = (-2.0 + 1.3 * families["past_late"] - 2.5 * families["autopay"] - 1.2 * families["opened_reminder"]
- 0.02 * families["months_enrolled"] + 2.2 * ((families["amount"] == 250) & ~families["autopay"]))
families["late"] = rng.random(n) < 1 / (1 + np.exp(-score))
families.astype({"autopay": int, "opened_reminder": int, "late": int}).to_csv("payments_history.csv", index=False)
print("Saved", n, "families;", int(families["late"].sum()), "paid late")Saved 1000 families; 143 paid lateExample: Train, Test, Predict
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
data = pd.read_csv("payments_history.csv")
X = data.drop(columns="late") # features: what we know before the due date
y = data["late"] # label: 1 if the fee was paid late
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
print("Training examples:", len(X_train), "| test examples:", len(X_test))
print(f"Always guessing 'on time': {1 - y_test.mean():.1%} correct")
print(f"Model accuracy on unseen families: {model.score(X_test, y_test):.1%}")
new_family = pd.DataFrame([{"amount": 250, "past_late": 2, "autopay": 0,
"months_enrolled": 6, "opened_reminder": 0}])
print("New family:", "likely late" if model.predict(new_family)[0] == 1 else "likely on time")Training examples: 750 | test examples: 250
Always guessing 'on time': 85.6% correct
Model accuracy on unseen families: 89.6%
New family: likely lateExplanation: X holds the five features and y the label. train_test_split() keeps 250 families aside as a test set the model never sees during training. A model that always guessed "on time" would already be right 85.6% of the time, because most families pay on time; the trained model reaches 89.6% on the unseen families. predict() then judges a new family as likely late.
The Supervised Learning Steps
| Step | scikit-learn |
|---|---|
| Split the data | train_test_split(X, y, test_size=0.25) |
| Choose a model | LogisticRegression(), DecisionTreeClassifier(), ... |
| Train | model.fit(X_train, y_train) |
| Evaluate | model.score(X_test, y_test) |
| Predict | model.predict(new_examples) |
Common Mistakes
Testing on the training data. A model can memorize what it has seen; judge it on unseen data.
Ignoring the baseline. High accuracy on an imbalanced label can mean nothing.
Using features you won't have at prediction time. Only use what is known before the due date.
Interview Corner
What is supervised learning?
Learning a mapping from features to labels using labeled examples, then predicting labels for new examples. Classification predicts categories; regression predicts numbers.
Why split data into training and test sets?
To measure how well the model works on data it hasn't seen, which is what matters in real use; training accuracy alone overstates performance.
Practice
Exercise: a different family. Predict for a family with a $45 fee, no late payments, autopay on, 24 months enrolled, reminder opened. Then change one feature at a time until the prediction flips to "likely late". Which feature mattered most?
Check your understanding:
- What is the difference between a feature and a label?
- Why was 85.6% the number to beat?
- Is predicting a house price classification or regression?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Split | train_test_split(X, y, test_size=0.25, stratify=y) |
| Train | model.fit(X_train, y_train) |
| Accuracy | model.score(X_test, y_test) |
| Predict | model.predict(new) |
Was this tutorial helpful?