Sub topic 5
The predict-the-mean baseline
This chapter assumes you can compute MAE and RMSE from residuals and that you know what a train/test split is. It also assumes basic NumPy. Here you will learn what the simplest possible regression model is, how to score it, and why every later R squared number depends on it.
Why a metric needs a reference point
Suppose a model for house prices has an RMSE of 30,000. Is that good? It depends on the data. If prices range from 100,000 to 120,000, an error of 30,000 is terrible. If prices range from 100,000 to 5,000,000, it is excellent.
MAE and RMSE are expressed in the units of the target, so they cannot answer this alone. You need a second number to compare against: the error of a model that uses no information about each row. The standard choice is the predict-the-mean baseline.
What the baseline predicts
The baseline ignores every feature. For every row, it outputs the same value: the mean of the target values it was given.
$$\hat{y}_i = \bar{y} \quad \text{for every } i$$
This is the best constant prediction when you measure error by squared differences. No other single number gives a lower mean squared error on the data it was computed from. That makes it a fair opponent. If your model with all its features cannot beat one constant, the features are adding nothing, or the model is using them badly.
The baseline needs no features, so it is also the "model" you fall back on when you know nothing about a new row except the overall history of the target.
Scoring the baseline by hand
Use the same four-point example as earlier in this tutorial:
- Actual values: 3.0, 5.0, 2.5, 7.0
- Mean: (3.0 + 5.0 + 2.5 + 7.0) / 4 = 4.375
The baseline predicts 4.375 for every row. The residuals (actual minus predicted here, so that they read as deviations from the mean) are:
| Row | Actual | Baseline | Deviation | Squared deviation |
|---|---|---|---|---|
| 1 | 3.0 | 4.375 | -1.375 | 1.890625 |
| 2 | 5.0 | 4.375 | 0.625 | 0.390625 |
| 3 | 2.5 | 4.375 | -1.875 | 3.515625 |
| 4 | 7.0 | 4.375 | 2.625 | 6.890625 |
The squared deviations sum to 12.6875. This number has a name, the total sum of squares, written ss_tot. It is the same ss_tot that appeared in the R squared code earlier in this tutorial. It is simply the squared error of the baseline, summed over all rows.
From it you get the baseline's metrics:
- Baseline MSE: 12.6875 / 4 = 3.171875
- Baseline RMSE: the square root of 3.171875, about 1.7810
- Baseline MAE: (1.375 + 0.625 + 1.875 + 2.625) / 4 = 1.625
The model from earlier had MAE 0.75 and RMSE 0.9354 on the same four points. Its RMSE is about half of the baseline's. That statement is far more informative than "RMSE is 0.9354".
The baseline is the standard deviation in disguise
The mean squared error of the baseline on its own data is the variance of the target. Its RMSE is the standard deviation. Here, np.std with its default ddof=0 divides by n, just as MSE does, so the two agree exactly.
This gives you a useful reading of RMSE: it is a prediction error expressed on the same scale as the target's natural spread. An RMSE well below the target's standard deviation means the model explains much of the variation. An RMSE near the standard deviation means the model is barely better than guessing the mean.
import numpy as np
y_true = np.array([3.0, 5.0, 2.5, 7.0])
y_model = np.array([2.5, 5.0, 4.0, 8.0])
baseline = np.full_like(y_true, y_true.mean())
print(baseline) # [4.375 4.375 4.375 4.375]
def rmse(actual, predicted):
return np.sqrt(np.mean((actual - predicted) ** 2))
def mae(actual, predicted):
return np.mean(np.abs(actual - predicted))
print(f"baseline MAE = {mae(y_true, baseline):.4f}") # 1.6250
print(f"baseline RMSE = {rmse(y_true, baseline):.4f}") # 1.7810
print(f"np.std(y) = {np.std(y_true):.4f}") # 1.7810
print(f"model MAE = {mae(y_true, y_model):.4f}") # 0.7500
print(f"model RMSE = {rmse(y_true, y_model):.4f}") # 0.9354np.full_like builds an array with the same shape and type as y_true, filled with the mean. The baseline RMSE and np.std match, which confirms the link between the two.
From baseline to R squared
The baseline gives the next chapter its central idea. Compare the model's mean squared error to the baseline's:
$$\frac{\text{model MSE}}{\text{baseline MSE}} = \frac{0.875}{3.171875} \approx 0.2759$$
The model keeps about 27.6 percent of the baseline's squared error. The remaining share, 1 - 0.2759 = 0.7241, is the R squared you computed earlier. So R squared is "one minus the model's squared error as a fraction of the baseline's squared error". The next chapter develops it fully. For now, hold onto the picture that the baseline is the denominator.
Two anchor points follow directly:
- A model identical to the baseline has a squared-error ratio of 1, so R squared is 0.
- A perfect model has a ratio of 0, so R squared is 1.
Which mean? Use the training mean
On the four-point example, the baseline used the mean of the same values it was scored on. That is fine for explaining the idea, but it is not how you evaluate a real model.
A model is trained on one set of data and judged on another. The baseline must follow the same rule. It learns its single parameter, the mean, from the training targets only. You then score it on the test targets. Using the test mean would give the baseline information from the test set that no real model has at prediction time.
scikit-learn provides this baseline as DummyRegressor. With strategy="mean", it stores the mean of y_train during fit and returns it for every row in predict.
import numpy as np
from sklearn.datasets import make_regression
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
X, y = make_regression(n_samples=200, n_features=3, noise=10.0, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
baseline = DummyRegressor(strategy="mean").fit(X_train, y_train)
model = LinearRegression().fit(X_train, y_train)
for name, estimator in (("baseline", baseline), ("linear", model)):
pred = estimator.predict(X_test)
print(
f"{name:8s} "
f"MAE={mean_absolute_error(y_test, pred):.2f} "
f"RMSE={np.sqrt(mean_squared_error(y_test, pred)):.2f} "
f"R2={r2_score(y_test, pred):.3f}"
)When you run this, the baseline's R squared on the test set will be near 0 and usually slightly negative. The linear model's scores should be far better on every metric. In practice, print the baseline next to your model's numbers every time. It costs one line and makes the report self-explanatory.
Why the baseline's test R squared is never positive
There is a precise reason the baseline's held-out R squared falls at or below 0. Let m_train be the training mean and m_test the test mean. Over the n test rows, the baseline's squared error splits into two parts:
$$\sum (yi - m{\text{train}})^2 = \sum (yi - m{\text{test}})^2 + n\,(m{\text{test}} - m{\text{train}})^2$$
The first term on the right is ss_tot for the test set. The second term is never negative. So the baseline's squared error is at least ss_tot, and R squared is at most 0. It equals 0 only if the two means happen to match exactly.
This has a practical consequence. A model with a negative test R squared is worse than the baseline would be if it could see the test mean, and often worse than the real baseline too. The size of the gap between the two means shows how much the target's average shifted between training and test data. If the baseline's test R squared is far below 0, the split is not representative, and you should look at how the data was divided before trusting any model comparison.
Edge cases
The baseline for MAE is the median
The mean is the best constant for squared error. For absolute error, the best constant is the median. When you quote MAE, the matching baseline is "predict the training median". Using the mean is still a valid baseline. The median can score lower on MAE, especially for skewed targets.
Take targets 1, 1, 1, 1, 21. The mean is 5. Predicting 5 everywhere gives MAE (4 + 4 + 4 + 4 + 16) / 5 = 6.4. Predicting the median, 1, gives MAE (0 + 0 + 0 + 0 + 20) / 5 = 4.0. DummyRegressor(strategy="median") provides this version.
A target with no variation
If every target value is identical, the baseline predicts it perfectly. Then ss_tot is 0, and R squared divides by zero. scikit-learn's r2_score handles this case by returning 1.0 for a perfect prediction and 0.0 otherwise. Treat such a result as a sign that the test set is too small or degenerate, and do not read it as a meaningful score.
Very small test sets
The baseline's score is only as stable as the data it is computed on. With a handful of test rows, ss_tot is tiny and noisy, and R squared swings widely. Prefer larger held-out sets or cross-validation when the data is limited.
Targets that change over time
For data ordered in time, such as sales or temperatures, the overall training mean can be a weak baseline. A trend makes it poor, and a model that beats it may still be unremarkable. Time-series work usually adds a second baseline, such as "predict the last observed value". The mean baseline remains the reference that R squared uses, but it is not the only fair opponent.
Common mistakes
- Computing the baseline from the test targets. This leaks information and makes the baseline look better than any real model could have it.
- Reporting a model's RMSE without the baseline's RMSE. The reader cannot tell whether the number is good.
- Forgetting that the baseline is fit on training data. A pipeline that calls
fiton all data before splitting contaminates the comparison. - Assuming a model that beats the baseline is useful. Beating a constant is the minimum bar, not proof of value.
Exercise
The test targets are 10, 12, 14, 16, 18. A model predicts 11, 12, 13, 17, 19, which gives an RMSE of about 1.0954. Compute the baseline RMSE using the mean of these five values, then compute the model's MSE, the ratio of model MSE to baseline MSE, and R squared.
Show answer
The mean is 14. The squared deviations are 16, 4, 0, 4, 16, which sum to 40. Baseline MSE is 40 / 5 = 8, so baseline RMSE is about 2.828. The model's squared errors are 1, 0, 1, 1, 1, which sum to 4, so model MSE is 4 / 5 = 0.8 and RMSE is about 0.894. The ratio is 0.8 / 8 = 0.1, so R squared is 1 - 0.1 = 0.9. (The stated RMSE of 1.0954 in the question is incorrect for these predictions; the correct value is about 0.894.)
Exercise
A DummyRegressor with strategy="mean" is fit on training targets with mean 50. The test targets have mean 55 and ss_tot of 2000 over 100 rows. What is the baseline's R squared on the test set?
Show answer
The baseline's squared error equals ss_tot plus n times the squared gap between the means: 2000 + 100 * (55 - 50)^2 = 2000 + 2500 = 4500. R squared is 1 - 4500 / 2000 = -1.25. The model that ignores all features scores below zero because the target's average moved between training and test data.