Sub topic 10
Setting a baseline
A baseline is the simplest model you can build, and it gives every later score something to be measured against. This chapter assumes you can already split data, build a scikit-learn Pipeline, and read the metrics from the previous chapter (accuracy, F1, mean absolute error). It covers the kinds of baseline, how to compare against them fairly, and the mistakes that make a baseline meaningless.
Why a score needs a reference point
A cross-validated F1 of 0.62 means nothing alone. If predicting "no" for every row gives 0.60, your model adds almost nothing. If the current rule-based system gives 0.85, your model is a regression. A baseline answers one question: how much of the score comes from learning, and how much comes from the shape of the data?
The baseline also helps you early. It runs your whole evaluation path, including the split, the metric and the reporting, before you spend time on a complex model. Bugs in that path show up while the model is still trivial.
Two levels of baseline
Most projects need two baselines.
- A dummy baseline ignores the features entirely. It sets the floor that any model must clear.
- A simple model baseline is a basic model such as logistic regression, linear regression or a shallow decision tree, with minimal preprocessing. It sets the practical bar. A gradient-boosted ensemble that beats it by 0.002 is rarely worth its cost.
If a human or a legacy system already makes the decision, treat its output as a third baseline. For example, a rule such as "flag orders above 500 dollars" is a real baseline. Beating the dummy is easy. Beating the existing process is what makes the project worth shipping.
Dummy baselines in scikit-learn
DummyClassifier and DummyRegressor implement the common floors.
| Estimator | Strategy | Predicts |
|---|---|---|
| `DummyClassifier` | `most_frequent` | The most common training class every time |
| `DummyClassifier` | `prior` | The same class, with `predict_proba` returning class frequencies |
| `DummyClassifier` | `stratified` | Random labels drawn with the training class frequencies |
| `DummyRegressor` | `mean` | The training mean |
| `DummyRegressor` | `median` | The training median, which suits skewed targets and absolute error |
Choose the strategy that matches your metric. The mean minimizes squared error, and the median minimizes absolute error. Using the wrong one gives you a weaker floor than you should have.
Worked example: imbalanced classification
Accuracy is the usual trap. In this example about 5% of rows are positive, so a model that always predicts the majority class scores about 0.95 accuracy while finding no positives.
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score, make_scorer
from sklearn.model_selection import StratifiedKFold, cross_validate, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(
n_samples=5000, n_features=20, n_informative=5,
weights=[0.95, 0.05], flip_y=0.01, random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
# One fixed splitter, so every candidate sees identical folds.
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scoring = {
"accuracy": "accuracy",
"balanced_acc": "balanced_accuracy",
"f1": make_scorer(f1_score, zero_division=0),
}
candidates = {
"majority class": DummyClassifier(strategy="most_frequent"),
"stratified random": DummyClassifier(strategy="stratified", random_state=0),
"logistic regression": Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
]),
}
for name, model in candidates.items():
res = cross_validate(model, X_train, y_train, cv=cv, scoring=scoring)
summary = " ".join(
f"{metric}={res['test_' + metric].mean():.3f}" for metric in scoring
)
print(f"{name:20s} {summary}")Expect the majority-class row to show accuracy near 0.95, balanced accuracy of exactly 0.5 and F1 of 0. The accuracy column makes the useless model look excellent, while balanced accuracy and F1 expose it. The stratified-random dummy shows what pure chance produces on the positive class. Logistic regression should beat both by a clear margin on F1.
Two details matter here. The scaler sits inside the pipeline, so it is refit on each training fold and cannot leak. The test split is untouched: all baseline comparisons use the training data only.
Worked example: regression
For regression, the dummy predicts one constant. Its R² is close to 0 by construction (slightly negative on held-out data), so R² already contains a baseline. Error metrics such as MAE do not, so you must compute the floor yourself.
from sklearn.datasets import load_diabetes
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import Ridge
from sklearn.model_selection import KFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
cv = KFold(n_splits=5, shuffle=True, random_state=0)
models = {
"mean": DummyRegressor(strategy="mean"),
"median": DummyRegressor(strategy="median"),
"ridge": make_pipeline(StandardScaler(), Ridge(alpha=1.0)),
}
for name, model in models.items():
mae = -cross_val_score(
model, X_train, y_train, cv=cv, scoring="neg_mean_absolute_error"
)
print(f"{name:7s} MAE = {mae.mean():.1f} (+/- {mae.std():.1f})")Scikit-learn scorers follow a "higher is better" rule, so error metrics come back negated. The leading minus sign restores the usual MAE. Reading the output, the useful number is the gap between the dummy rows and the ridge row, expressed in the target's own units.
Comparing fairly
Follow these rules so the comparison means something.
- Same folds. Pass the same
cvobject, with a fixedrandom_state, to every candidate. Different folds add noise that looks like a difference between models. - Same metric and same preprocessing path. A baseline that sees differently cleaned data is not a baseline for your model.
- Look at the spread. Compare the gap to the fold-to-fold standard deviation. If the model beats the baseline by 0.01 and the standard deviation is 0.03, you have no evidence of improvement.
- Report several metrics for imbalanced data. Accuracy alone is misleading, as the first example showed.
Common errors
- Using the wrong dummy for the metric. A mean baseline for MAE overstates how good your model is. Use the median.
- Reading a dummy score of 0 as failure. For F1, a majority-class dummy scores 0 on the rare class. That is the expected floor, not a bug.
- Flipped class balance. On a dataset where the positive class is the majority, an "always positive" dummy gets a high F1. Check which class your metric treats as positive, and look at the baseline's confusion matrix once.
- Skipping the simple model. Going straight from the dummy to a complex model leaves you unable to say whether the complexity paid off.
- Tuning the baseline. Do not spend effort optimizing it. A baseline should be quick to build and easy to explain. If you tune it heavily, it becomes just another model.
- Ignoring time order. For forecasting, the right dummy is often "repeat the last observed value" or "repeat the value from the same day last week", not the overall mean. These are called naive baselines, and they are often hard to beat.
What to do with the result
Record the baseline scores next to your split and metric definitions, because later chapters refer back to them. If your best model barely clears the simple model, that is useful information. It often means the features carry little signal, the target is noisy, or the framing needs work, and none of these problems is solved by a larger model. If the model clears the baseline by a wide margin, you can proceed to training and tuning with some confidence that the gains are real.
Exercise
A fraud dataset has 1% positive rows. A model gets 0.985 cross-validated accuracy, and a DummyClassifier(strategy="most_frequent") gets 0.990. A colleague says the model is "98.5% accurate, so it's great." What do you tell them, and what would you check next?
Show answer
The model is worse than the dummy on accuracy, so the number proves nothing. The dummy already scores 0.99 by never flagging fraud. Next, compare both on metrics that depend on the rare class, such as recall, precision, F1 or average precision, using the same stratified folds. Also compare the model with the simple-model baseline and any existing rule-based system before judging it.
Exercise
You are predicting delivery times, which are strongly right-skewed, and your metric is mean absolute error. Which DummyRegressor strategy gives the fairer floor, and why?
Show answer
Use strategy="median". The median minimizes absolute error, and it is less affected by the long tail of slow deliveries than the mean. A mean-based dummy would produce a higher MAE and make your model look better than it is.