Sub topic 6
Baselines: know what to beat
A baseline is a simple model whose score sets the minimum bar for every other model. This chapter assumes you know scikit-learn's fit and predict, stratified cross-validation, and the idea of putting preprocessing in a pipeline. Earlier chapters covered metrics and validation. Here you use them to build a reference point.
Why a baseline comes first
A score has no meaning alone. An AUC of 0.78 may be excellent for one problem and poor for another. A baseline tells you how much of that score comes from the model and how much comes from the data's structure, such as class imbalance.
Two kinds of baseline are useful:
- Trivial baseline. It ignores the features and predicts from the target alone. For classification it predicts the most common class or the class proportions. For regression it predicts the mean or median.
- Simple model baseline. A regularized linear or logistic model on cleaned features. It shows how much signal is easy to extract.
Any model that cannot beat the trivial baseline has learned nothing. Any complex model that barely beats the simple one may not be worth its cost.
Building both baselines
The code below builds a small table with a missing-value column and a categorical column. It wraps preprocessing in a pipeline so the imputer, scaler and encoder are fitted inside each fold. It scores a dummy classifier and a logistic regression on the same 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))The dummy model uses strategy="prior", which outputs the class proportions as probabilities. Its ROC AUC is 0.5, because it ranks every row the same. That value is the floor for AUC, whatever the class balance. For accuracy, the dummy score depends on the balance, so it is the more informative floor there.
The target here is an XOR of two conditions: age over 45, and city equal to "a". A linear model can only add effects of each feature, so it cannot represent this interaction. Expect logistic regression to score close to the dummy. This is a deliberate trap. A weak baseline result can mean the data has little signal, or it can mean the model family cannot express the signal. The next chapters on trees and boosting test that second possibility.
Common errors
- Using different folds or metrics. Scores from different splits are not comparable. Create one
cvobject and reuse it for every model. - Fitting preprocessing on all the data. Fit it inside the pipeline so each fold learns its own statistics.
- Ignoring the spread. Compare the gap between models with the standard deviation across folds. A gain smaller than the spread is probably noise.
- Picking the wrong dummy strategy.
"most_frequent"suits accuracy."prior"or"stratified"suits probability metrics. For regression, useDummyRegressorwith"mean"or"median". - Treating a high baseline as a bug. If a logistic regression scores very high, check for leakage before celebrating.
Exercise
A fraud dataset has 2% positive cases. A DummyClassifier with strategy="most_frequent" scores 98% accuracy. A logistic regression scores 98.2%. What do you conclude, and what would you change in the evaluation?
Show answer
Accuracy is the wrong metric here. The dummy already reaches 98% by predicting "not fraud" every time, so the 0.2-point gain is not meaningful evidence of learning. Switch to a metric that responds to the rare class, such as ROC AUC, average precision, or recall at a fixed precision. Then compare the logistic regression with a baseline that uses the same metric, on the same stratified folds.