Sub topic 6
A baseline to beat
A baseline is the simplest model you can build. Any model you train later has to score better than it. This chapter builds that reference score for the California housing project and explains how to read it.
Prerequisites
This chapter assumes you have these from earlier chapters:
- You can load the California housing data into a DataFrame with
fetch_california_housing(as_frame=True). - You know the target is
MedHouseVal, the median house value in units of $100,000. - You know why we split off a test set, and what MAE, RMSE and R² measure.
- You are comfortable with the scikit-learn pattern
fitthenpredict.
Why a baseline comes first
A score has no meaning alone. Suppose a model reports a mean absolute error (MAE) of 0.5. In this dataset the unit is $100,000, so that is an average miss of $50,000. Whether that is good depends on what a trivial guess would have achieved.
A baseline gives you three things:
- A floor. If a model cannot beat the baseline, it has learned nothing useful, or something is broken.
- A bug detector. If a complex pipeline scores worse than the baseline, you probably have a coding mistake, such as misaligned rows or the wrong target.
- A scale for improvement. "MAE dropped from 0.9 to 0.3" says more than "MAE is 0.3".
For regression, the standard baseline predicts one constant for every house. scikit-learn provides it as DummyRegressor.
Set up the data and the split
The baseline must be trained and scored on the same split as every later model. A different split would make the comparison unfair. Fixing random_state makes the split reproducible.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
housing = fetch_california_housing(as_frame=True)
df = housing.frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print(X_train.shape, X_test.shape)The split gives 16,512 training rows and 4,128 test rows, from 20,640 in total. Keep this cell at the top of your script. Later chapters reuse X_train, X_test, y_train and y_test.
Fit the mean baseline
DummyRegressor(strategy="mean") stores the average of y_train during fit. It returns that number for every row in predict. It never looks at the features.
from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_absolute_error
baseline = DummyRegressor(strategy="mean").fit(X_train, y_train)
print("Training mean:", baseline.constant_)
print("Baseline MAE:", mean_absolute_error(y_test, baseline.predict(X_test)))The fitted constant is stored in the constant_ attribute. It is about 2.07, or roughly $207,000. The baseline MAE is close to 0.9, so a model that guesses the average price for every neighborhood is off by about $90,000 on a typical house.
The constant comes from the training data only. The test set is used to score the prediction, never to compute it. That rule matters even for a model this simple, and later chapters return to it.
Look at more than one metric
MAE is the success metric chosen for this project. Reporting the other two metrics for the baseline shows what each one looks like for a model with no skill.
import numpy as np
from sklearn.metrics import mean_squared_error, r2_score
pred = baseline.predict(X_test)
mae = mean_absolute_error(y_test, pred)
rmse = np.sqrt(mean_squared_error(y_test, pred))
r2 = r2_score(y_test, pred)
print(f"MAE: {mae:.3f}")
print(f"RMSE: {rmse:.3f}")
print(f"R2: {r2:.3f}")Expect three patterns:
- RMSE is larger than MAE. RMSE squares each error before averaging, so a few very wrong predictions pull it up.
- R² is close to zero. R² compares a model to the "always predict the mean" strategy. The baseline is that strategy, so its R² on the test set is about 0. It can come out slightly negative, because the test mean differs a little from the training mean.
- R² has a built-in baseline. An R² of 0.8 means the model removes about 80% of the squared error that the mean-only guess leaves. MAE has no such built-in reference, which is why you compute the baseline MAE yourself.
Try other strategies
DummyRegressor supports several strategies. The right one depends on the metric you will report.
| Strategy | What it predicts | Minimizes |
|---|---|---|
| `"mean"` | Mean of the training target | Squared error (RMSE) |
| `"median"` | Median of the training target | Absolute error (MAE) |
| `"quantile"` | A chosen quantile, set with `quantile=` | Pinball loss for that quantile |
| `"constant"` | A value you supply with `constant=` | Nothing in particular |
The median is the constant that minimizes absolute error. When your project metric is MAE, the median baseline is the fairer reference to beat. House prices are skewed to the right, with a long tail of expensive areas. So the median sits below the mean, and the two baselines give different MAE values.
for strategy in ["mean", "median"]:
dummy = DummyRegressor(strategy=strategy).fit(X_train, y_train)
mae = mean_absolute_error(y_test, dummy.predict(X_test))
print(f"{strategy:>6}: constant={dummy.constant_.item():.3f} MAE={mae:.3f}")The median baseline gets a slightly lower MAE than the mean baseline. Use the lower of the two as the number to beat. A real model that only ties the mean baseline might still lose to the median.
The "constant" strategy is useful when a business rule gives a fixed guess, such as "last year's citywide average". It lets you test whether a model beats the rule currently in use.
rule = DummyRegressor(strategy="constant", constant=2.0).fit(X_train, y_train)
print("Rule-of-thumb MAE:", mean_absolute_error(y_test, rule.predict(X_test)))Score the baseline the way you will score models
Later chapters compare models with 5-fold cross-validation on the training set, using neg_mean_absolute_error. The baseline should be scored the same way. Otherwise you would compare a cross-validation score for a model against a test-set score for the baseline.
from sklearn.model_selection import cross_val_score
scores = cross_val_score(
DummyRegressor(strategy="median"),
X_train,
y_train,
cv=5,
scoring="neg_mean_absolute_error",
)
print("Median baseline CV MAE:", -scores.mean())Scikit-learn scorers follow the rule "greater is better". For error metrics it returns the negative value, so you flip the sign when printing.
Common errors
- Fitting on all the data. Calling
fit(X, y)on the full dataset lets the test targets influence the constant. Always fit onX_trainandy_train. - Changing the split between runs. If you omit
random_state, every run has a different test set. Baseline and model scores then differ partly from the split, so the comparison is no longer fair. - Comparing different metrics. A baseline RMSE tells you nothing about a model's MAE. Compare each metric with itself.
- Reading a tiny gain as success. A model that beats the baseline by 2% may not justify its complexity. Judge the gap against the cost of the extra model.
- Ignoring the target's limits. In this dataset,
MedHouseValis capped at about 5.0, which means $500,000. Many expensive areas share that value. Any model, including the baseline, will misjudge those rows, so some error cannot be removed.
What a good outcome looks like
After this chapter you should have these results saved in your notebook or script:
- The reproducible split, with
random_state=42. - The mean baseline: an MAE close to 0.9 and an R² close to 0.
- The median baseline, which scores a slightly lower MAE.
- The cross-validated baseline MAE, to compare against Ridge and gradient boosting in the next chapters.
Write the median baseline's MAE down. Each later model should beat it clearly, and the size of the gap is the main result of the project.
Exercise
A teammate fits DummyRegressor(strategy="mean") and reports a test R² of -0.0002. They say the model is broken. Is it? Which strategy would you use as the reference if the project metric is MAE, and why?
Show answer
The model is not broken. A mean-only predictor is exactly what R² uses as its reference, so its R² on the test set is about 0. It comes out slightly negative because the test-set mean differs a little from the training mean the baseline predicts. For an MAE project, use strategy="median". The median is the constant that minimizes absolute error, so it is the fairer number to beat. House prices are skewed, so the median MAE is lower than the mean MAE.
Exercise
Why should the baseline be scored with the same cross-validation setup (cv=5, neg_mean_absolute_error on the training data) that you will use for Ridge and gradient boosting?
Show answer
Models are compared on the same folds and the same metric. Scoring the baseline differently, for example on the test set while models use cross-validation, mixes two kinds of estimate. The gap you measure would then include differences in the evaluation method, not only differences in the models. The cross-validated baseline score is also computed without touching the test set.