Sub topic 6
Baselines: know what to beat
This chapter assumes you can build a scikit-learn pipeline and that you already have a metric and a cross-validation scheme from the earlier chapters. Here you will add the last piece before comparing real models: a baseline, which is a simple reference model that any serious candidate must outperform.
Why a baseline comes first
A score has no meaning alone. An AUC of 0.78 could be excellent or useless. It depends on what a trivial method achieves on the same data and the same folds.
A baseline does three jobs:
- It gives you a floor. A model that does not beat the floor is not learning anything useful.
- It checks your evaluation setup. If a model that ignores every feature scores far from the expected chance level, the metric, the labels, or the split has a bug.
- It sizes the possible gain. If a one-rule model reaches 0.90 and gradient boosting reaches 0.91, the extra complexity may not be worth it.
Kinds of baselines
Use more than one. Each answers a different question.
| Baseline | What it does | What it tells you |
|---|---|---|
| Constant prediction | Predicts the majority class, the class prior, the mean, or the median | The score you get with no information from features |
| Simple rule | A hand-written rule such as "predict churn if no login in 30 days" | Whether a model beats current business practice |
| Single-feature or shallow model | A depth-1 tree, or a linear model on one column | How much one strong feature explains |
| Previous system | The model or process already in production | The real bar for replacement |
The constant baseline is the minimum. The previous system is often the one that matters in practice, so ask whether one exists before you start.
Dummy baselines in scikit-learn
DummyClassifier and DummyRegressor ignore the features and follow a fixed strategy.
DummyClassifier(strategy="prior")predicts the training class proportions. Itspredict_probareturns the same probabilities for every row, so ranking metrics such as ROC AUC land at 0.5.strategy="most_frequent"always predicts the majority class. Accuracy equals the majority share.strategy="stratified"and"uniform"guess at random. They are useful for sanity checks but noisier.DummyRegressor(strategy="mean")or"median"predicts one number. The mean minimizes squared error, and the median minimizes absolute error.
Put the dummy model inside the same pipeline as your real candidates. The preprocessing then runs on the same folds, and the comparison differs only in the final estimator.
A worked example
The code below builds a synthetic table with a missing-value column and a categorical column. It wraps the preprocessing in a pipeline so that it is fitted inside each fold. Then it scores a dummy baseline and a logistic regression on identical stratified folds.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 500
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(50000, 15000, n),
"city": rng.choice(["a", "b", "c"], n),
})
X.loc[rng.choice(n, 25, replace=False), "income"] = np.nan
y = ((X["age"] > 45) ^ (X["city"] == "a")).astype(int)
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["city"]),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
baseline = make_pipeline(preprocess, DummyClassifier(strategy="prior"))
logreg = make_pipeline(preprocess, LogisticRegression(max_iter=1000))
for name, model in [("baseline", baseline), ("logreg", logreg)]:
scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
print(name, scores.mean().round(3), scores.std().round(3))Reading the result
The baseline should print a mean AUC of 0.5 with a standard deviation of 0. That confirms the metric and the folds behave as expected.
The logistic regression is the more interesting case. The label is an XOR: it is 1 when exactly one of "older than 45" and "city is a" holds. A logistic regression adds up one effect per feature, so it cannot represent an interaction like this. Expect its AUC to land near the baseline, not far above it.
This is a useful outcome. A weak result from a model against the baseline signals one of two problems. Either the features carry little signal, or the model family cannot express the pattern. The next chapters on trees and boosting test the second explanation.
Regression baselines
For a numeric target, compare against the mean and median predictors. Report the error in the target's units so the gap is easy to read.
import numpy as np
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import Ridge
from sklearn.model_selection import KFold, cross_val_score
rng = np.random.default_rng(1)
X = rng.normal(size=(300, 3))
y = 3 * X[:, 0] + rng.normal(scale=1.0, size=300) + 10
cv = KFold(n_splits=5, shuffle=True, random_state=0)
models = [
("mean", DummyRegressor(strategy="mean")),
("median", DummyRegressor(strategy="median")),
("ridge", Ridge()),
]
for name, model in models:
mae = -cross_val_score(model, X, y, cv=cv, scoring="neg_mean_absolute_error")
print(name, mae.mean().round(3))Scikit-learn scorers follow a "higher is better" rule, so error metrics are negated. The leading minus sign turns neg_mean_absolute_error back into a normal error.
A rule or shallow-model baseline
A constant baseline is easy to beat. A stronger floor is a model that uses one idea. A depth-1 decision tree, called a stump, picks the single best split on a single feature. If your tuned ensemble barely beats the stump, most of the signal sits in that one split.
from sklearn.tree import DecisionTreeClassifier
stump = make_pipeline(preprocess, DecisionTreeClassifier(max_depth=1, random_state=0))
scores = cross_val_score(stump, X, y, cv=cv, scoring="roc_auc")
print("stump", scores.mean().round(3))Run this after the first example, since it reuses X, y, preprocess, and cv, and swap in a different X and y if you ran the regression example in between. On the XOR label a stump also stays near 0.5, because no single split separates the classes. That is the same lesson from another angle.
How baselines fit the workflow
Fix the metric and folds first, then build the baselines on them. Every later model reuses the same objects.
Common errors
- Different folds for different models. Scores from separate splits differ by noise alone. Reuse one
cvobject, and setrandom_statewhen shuffling. - Accuracy on imbalanced data. With 95% negatives, a model that always predicts "negative" scores 0.95 accuracy. Use the metric you chose earlier, and look at the dummy's score under it.
- Preprocessing outside the pipeline. If you impute or scale before splitting, the baseline and the models share leaked statistics. Keep the steps inside the pipeline.
- Ignoring the spread. A gap of 0.01 AUC with a fold standard deviation of 0.02 is not evidence of improvement. Compare the gap to the spread.
- Skipping the business baseline. Beating a dummy is easy. Beating the rule the team uses today is the real test.
Exercises
Exercise
A fraud dataset has 2% positive cases. A model scores 0.98 accuracy. Which baseline would you compute, and what does it likely show?
Show answer
Compute DummyClassifier(strategy="most_frequent"). It predicts "not fraud" every time and scores about 0.98 accuracy, so the model has shown no skill. Switch to a metric such as ROC AUC, average precision, or recall at a fixed precision, and compare the model with the dummy under that metric.
Exercise
Your DummyClassifier(strategy="prior") scores a ROC AUC of 0.5 with a standard deviation of 0 across five folds. Your gradient-boosted model scores 0.52 with a standard deviation of 0.03. What do you conclude, and what do you check next?
Show answer
The gain is smaller than the fold-to-fold spread, so there is no reliable evidence that the model beats the baseline. Check whether the features carry signal (for example, a stump on each feature), whether the labels are correct, and whether the pipeline is wired as intended. Confirm the dummy's 0.5 first, since it shows the metric and folds work as expected.