Lesson 10 of 12 · In Practice
Baselines
Build the baselines every model must beat: dummy models matched to the metric, one-question rules, seasonal forecasts, and how to report a model's real gain.
- 12 min read
- Intermediate
- Reviewed
- Explain why a score means little without a baseline to compare it with
- Build dummy baselines for regression and classification, matched to the metric
- Use a one-question rule as a stronger baseline
- Use the right baselines for forecasts: yesterday, and the same day last week
- Report a model's improvement as the share of the baseline's error it removes
The idea in plain words
Is an MAE of 44 good? Is an F1 score of 0.6 good? On their own, these numbers say nothing. They only mean something next to a baseline: the score of the simplest sensible way to solve the same problem. In Introduction to Machine Learning you compared models with "always predict the average" and "always predict the most common class". This lesson builds a ladder of stronger baselines, and shows how a weak baseline can make an ordinary model look brilliant.
- Dummy: predict a constant, such as the mean, the median or the most common class.
- Simple rule: one question about one feature, or a rule of thumb such as "same as last week".
- Simple model: logistic or linear regression with default settings.
- Current practice: what people or the existing system achieve today.
A new model has to beat the strongest baseline you can build cheaply. If it can't, it isn't worth the work of building, running and maintaining it.
Dummy baselines for numbers
DummyRegressor learns a single number from the training data and predicts it for everyone. The diabetes dataset records a measure of how far the disease progressed in a year, for 442 patients:
from sklearn.datasets import load_diabetes
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
X, y = load_diabetes(return_X_y=True) # disease progression after one year, 442 patients
for name, model in [("always the mean", DummyRegressor(strategy="mean")),
("always the median", DummyRegressor(strategy="median")),
("linear regression", LinearRegression())]:
mae = -cross_val_score(model, X, y, cv=5, scoring="neg_mean_absolute_error").mean()
print(f"{name:<18} MAE {mae:5.1f}")always the mean MAE 66.0 always the median MAE 65.2 linear regression MAE 44.3
The median baseline has a slightly lower MAE than the mean, as Loss Functions predicted: the median is the constant that minimises absolute error. Linear regression brings the error down to 44.3, so the features clearly carry information.
Why the minus sign? scikit-learn's scoring always treats higher as better, so it reports errors as negative numbers (neg_mean_absolute_error); the minus sign turns them back into ordinary errors.
Dummy baselines must match the metric
For classification, there are several dummy strategies, and each one is the right yardstick for a different metric. The data below has about 10% positives, such as customers who will leave:
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, f1_score, recall_score
from sklearn.model_selection import train_test_split
# About 10% positives, such as customers who will leave
X, y = make_classification(n_samples=2000, weights=[0.9], flip_y=0, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
dummies = {
"always the majority": DummyClassifier(strategy="most_frequent"),
"random, by class share": DummyClassifier(strategy="stratified", random_state=0),
"always positive": DummyClassifier(strategy="constant", constant=1),
}
print(f"{'baseline':<24} accuracy recall F1")
for name, dummy in dummies.items():
pred = dummy.fit(X_train, y_train).predict(X_test)
print(f"{name:<24} {accuracy_score(y_test, pred):8.2f} {recall_score(y_test, pred):7.2f} "
f"{f1_score(y_test, pred):5.2f}")baseline accuracy recall F1 always the majority 0.90 0.00 0.00 random, by class share 0.82 0.14 0.14 always positive 0.10 1.00 0.18
None of these "models" looks at the features, yet each wins something. Always predicting the majority scores 0.90 accuracy and finds nobody. Always predicting "positive" catches everyone (recall 1.00) and has the best F1 of the three (0.18). So if you report accuracy, the score to beat is 0.90; if you report F1 for the rare class, it is 0.18, not 0. Other strategies include "uniform" (random guessing with equal chances) and "prior", which predicts the class shares as probabilities: the right baseline for probability scores such as log loss.
A one-question rule
A stronger baseline is a rule a person could apply by hand. A decision tree allowed only one question (often called a decision stump) finds the best such rule:
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier, export_text
data = load_breast_cancer()
X, y = data.data, data.target
stump = DecisionTreeClassifier(max_depth=1, random_state=0) # a one-question rule
full = make_pipeline(StandardScaler(), LogisticRegression())
print(export_text(stump.fit(X, y), feature_names=list(data.feature_names)))
print(f"one-question rule: accuracy {cross_val_score(stump, X, y, cv=5).mean():.3f}")
print(f"logistic regression: accuracy {cross_val_score(full, X, y, cv=5).mean():.3f}")|--- worst radius <= 16.80 | |--- class: 1 |--- worst radius > 16.80 | |--- class: 0 one-question rule: accuracy 0.900 logistic regression: accuracy 0.981
The rule "benign (class 1) if the largest nuclei have a radius of at most 16.80, otherwise malignant" gets 90% right. The full model, using all 30 measurements, gets 98.1%. Its mistakes fall from about 10 in 100 to about 2 in 100, and that is what the extra complexity buys. If a one-question rule had come within a point of your model, the rule might be all you need: it is free to run and anyone can check it.
Baselines for forecasts
When predicting the future, the obvious baselines come from the past. The program below creates 400 days of sales with a slow upward trend and a weekly pattern (quiet Mondays, busy weekends), then predicts the last 70 days in four ways:
import numpy as np
from sklearn.ensemble import RandomForestRegressor
rng = np.random.RandomState(0)
days = np.arange(400)
weekly = np.array([0, 5, 8, 10, 25, 40, 30]) # quiet Monday, busy weekend
sales = 100 + 0.1 * days + weekly[days % 7] + rng.normal(0, 5, size=400)
test = np.arange(330, 400) # the last 70 days
def mae(pred):
return np.mean(np.abs(sales[test] - pred))
errors = {
"average of all earlier days": mae([sales[:d].mean() for d in test]),
"same as yesterday": mae(sales[test - 1]),
"same day last week": mae(sales[test - 7]),
}
# A model that uses the last 7 days' sales as features, trained on days before 330
X = np.array([sales[d - 7:d] for d in range(7, 400)])
target = sales[7:400]
train = np.arange(7, 330) - 7
forest = RandomForestRegressor(n_estimators=100, random_state=0).fit(X[train], target[train])
errors["random forest on last 7 days"] = mae(forest.predict(X[test - 7]))
for name, error in errors.items():
print(f"{name:<29} MAE {error:4.1f}")
model = errors["random forest on last 7 days"]
print(f"Error cut vs the average: {1 - model / errors['average of all earlier days']:.0%}")
print(f"Error cut vs the same day last week: {1 - model / errors['same day last week']:.0%}")average of all earlier days MAE 18.2 same as yesterday MAE 13.2 same day last week MAE 5.9 random forest on last 7 days MAE 5.4 Error cut vs the average: 70% Error cut vs the same day last week: 9%
"Same as yesterday" (a persistence forecast) beats the average, but it predicts a quiet Monday from a busy Sunday. "Same day last week" (a seasonal naive forecast) captures the weekly pattern and is far stronger: 5.9. The random forest reaches 5.4. Compared with the average, that sounds like a triumph, a 70% smaller error. Compared with the right baseline, it is a 9% improvement. Whether 9% is worth building and running a model is a business decision, but only the honest comparison lets you make it.
Reporting the improvement
A clear way to report a model is the share of the baseline's error that it removes:
error cut = 1 − (model error ÷ baseline error)
tumours: errors fall from 0.100 (one-question rule) to 0.019: 1 − 0.019 ÷ 0.100 = 0.81, about 81%
sales: MAE falls from 5.9 to 5.4: the program printed 9%Always state the baseline next to the number ("9% lower MAE than the same day last week"), measure both on the same test data with the same metric, and check that the model wins on most cross-validation folds, not just on average.
Common mistakes
Practice
Measure a churn model against the simplest baseline, and report how much of the baseline's error it removes.
actual = ["stay", "stay", "leave", "stay", "stay", "stay", "leave", "stay", "stay", "stay"]
model = ["stay", "stay", "leave", "stay", "leave", "stay", "leave", "stay", "stay", "stay"]
# 1. The baseline always predicts the most common label in actual.
# Find that label and the baseline's accuracy.
# 2. Work out the model's accuracy.
# 3. Error cut = 1 - (model error / baseline error), where error = 1 - accuracy.
# Print exactly:
# Baseline: always <label>, accuracy 0.00
# Model: accuracy 0.00, error cut 0%
majority = "?"
baseline_acc = 0
model_acc = 0
cut = 0
print(f"Baseline: always {majority}, accuracy {baseline_acc:.2f}")
print(f"Model: accuracy {model_acc:.2f}, error cut {cut:.0%}")
A new model forecasts daily sales with an MAE of 52. Predicting the same day last week gives an MAE of 50. What should you conclude?
Summary
- A score only means something next to a baseline: the simplest sensible way to solve the same problem.
- Climb the ladder: dummy predictions, a simple rule, a simple model, and current practice.
- Each metric has its own trivial baseline: always the majority for accuracy, always positive for F1 on a rare class.
- For forecasts, beat persistence ("same as yesterday") and seasonal naive ("same day last week") forecasts.
- Report the error cut against the strongest baseline, measured on the same data with the same metric.
Next: Handling Imbalanced Classes, when the class you care about is rare.
Finished reading? Tick it off to track your progress.