Sub topic 9
R squared pitfalls: negative values, added features, and adjusted R squared
This chapter assumes you can compute MAE, RMSE, and R squared with NumPy and scikit-learn. It also assumes you know the predict-the-mean baseline and the idea of a train/test split. Here we look at where R squared gives misleading answers and how to guard against them.
Recap: what R squared compares
R squared is defined as:
R² = 1 − SSres / SStot
- SS_res is the sum of squared residuals of your model.
- SS_tot is the sum of squared distances of the true values from their own mean.
SS_tot is the squared error of the predict-the-mean baseline. R² therefore answers one question: how much of the baseline's squared error does the model remove?
- R² = 1 means no squared error remains.
- R² = 0 means the model does no better than the baseline.
- Any value below 0 means the model does worse than the baseline.
Every pitfall below comes from a detail of this definition.
Pitfall 1: R squared can be negative
The name suggests a square, which would never be negative. R² is not the square of anything in general. It is one minus a ratio, and the ratio can exceed 1.
SSres exceeds SStot whenever your predictions are, in total, farther from the truth than a flat line at the mean. Here is a four-point example with deliberately poor predictions:
import numpy as np
from sklearn.metrics import r2_score
y_true = np.array([3.0, 5.0, 2.5, 7.0])
y_pred = np.array([6.0, 2.0, 7.0, 3.0])
ss_res = np.sum((y_true - y_pred) ** 2) # 54.25
ss_tot = np.sum((y_true - y_true.mean()) ** 2) # 12.6875
print(1 - ss_res / ss_tot) # about -3.2759
print(r2_score(y_true, y_pred)) # same valueSSres is about 4.3 times SStot, so R² is about −3.28. The model is much worse than ignoring the features and predicting 4.375 for everything.
Negative values on held-out data
On training data, a least-squares linear model with an intercept cannot score below 0. The fit minimizes SS_res, and the mean-only model is one of the candidates it could have picked. On held-out data there is no such guarantee, because the model was not fitted to those points. Negative test R² appears in three common situations:
- Overfitting. The model memorized noise, and its predictions on new points are scattered.
- Distribution shift. The test targets sit in a different range than the training targets.
- Mismatched baselines. The baseline inside the metric is the mean of the test targets, not the training mean. A model that only predicts the training mean can therefore score below 0.
The third case is easy to demonstrate:
import numpy as np
from sklearn.metrics import r2_score
y_train = np.array([10.0, 12.0, 11.0, 13.0])
y_test = np.array([20.0, 22.0, 21.0, 23.0])
# The "model" predicts the training mean for every test point.
pred = np.full_like(y_test, y_train.mean()) # 11.5 everywhere
print(r2_score(y_test, pred)) # -80.0Here SSres is 405 and SStot is 5, so R² = 1 − 81 = −80. The test targets barely vary around their own mean (SS_tot is tiny). Any constant that sits far from that mean looks terrible by comparison.
A negative R² is not a bug in the metric. Treat it as a sign that the model, the split, or the data needs inspection.
Pitfall 2: adding features never lowers training R squared
Suppose you fit ordinary least squares with an intercept and then add one more feature column. The new model can always reproduce the old one by giving the new column a coefficient of zero. Least squares finds the minimum of SSres, so the new SSres is at most the old one. Training R² can only stay the same or rise, even if the new column is pure random noise.
This experiment makes it visible. It adds columns of random noise to a dataset that has three real features:
import numpy as np
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
X, y = make_regression(n_samples=100, n_features=3, noise=20.0, random_state=0)
rng = np.random.default_rng(0)
noise_cols = rng.normal(size=(100, 55))
print("noise_cols train_R2 test_R2")
for k in (0, 10, 20, 40, 55):
X_k = np.hstack([X, noise_cols[:, :k]])
X_tr, X_te, y_tr, y_te = train_test_split(
X_k, y, test_size=0.4, random_state=0
)
model = LinearRegression().fit(X_tr, y_tr)
train_r2 = r2_score(y_tr, model.predict(X_tr))
test_r2 = r2_score(y_te, model.predict(X_te))
print(f"{k:10d} {train_r2:8.3f} {test_r2:7.3f}")The split is identical in every iteration, because the sample count and random_state do not change. The feature sets are nested, so the training R² column never decreases. With 58 features and only 60 training rows it approaches 1. The test R² column typically falls as noise columns accumulate, and it can go negative. Exact values depend on your library versions, but the pattern holds.
This is the main reason to evaluate on held-out data. Training R² rewards complexity regardless of whether the complexity carries signal.
Fix 1: adjusted R squared
Adjusted R² charges a penalty for each predictor. For n samples and p predictors (not counting the intercept):
adjusted R² = 1 − (1 − R²) × (n − 1) / (n − p − 1)
The factor (n − 1) / (n − p − 1) grows as p grows. A new predictor therefore has to reduce the residual error by more than chance would to raise the adjusted value.
def adjusted_r2(r2: float, n_samples: int, n_predictors: int) -> float:
if n_samples <= n_predictors + 1:
raise ValueError("Need n_samples > n_predictors + 1")
return 1 - (1 - r2) * (n_samples - 1) / (n_samples - n_predictors - 1)
# 30 samples. A 3-predictor model and a 10-predictor model.
print(round(adjusted_r2(0.80, 30, 3), 4)) # 0.7769
print(round(adjusted_r2(0.82, 30, 10), 4)) # 0.7253The second model has the higher raw R² (0.82 against 0.80). Its adjusted R² is lower (0.7253 against 0.7769), so the extra seven predictors did not pay for themselves.
Properties to keep in mind:
- Adjusted R² is never larger than R².
- It can fall below 0 even on training data, and it can decrease when you add a weak predictor.
- It is undefined when n ≤ p + 1, because the denominator reaches zero or goes negative.
- scikit-learn has no built-in function for it. You compute it from
r2_score, as above. - It is still an in-sample correction based on a formula. It does not replace a held-out evaluation or cross-validation, and it is mainly justified for linear models fitted by least squares.
Pitfall 3: a high R squared does not mean a good model
R² measures only the share of variance explained. Several things can make it look better or worse than the model deserves.
| Situation | What happens to R² | What to do |
|---|---|---|
| Curved relationship fitted with a straight line | Can still be high, because the line follows the overall trend | Plot residuals against predictions and look for a pattern |
| Narrow range of target values in the sample | R² drops, because SS_tot is small and the same errors look larger | Compare against RMSE in target units |
| Wide range of target values in the sample | R² rises, even if the absolute errors are the same | Do not compare R² across datasets with different spread |
| Time series with a trend | Any model that follows the trend scores high | Compare against a naive forecast such as "same as last period" |
| Few test samples | R² is unstable, and one point can swing it | Use cross-validation and report the spread |
| Linear model with no intercept | Training R² can be negative or misleading | Keep the intercept unless you have a reason not to |
The second and third rows matter when you compare models across datasets. The same RMSE of 5 units can produce R² = 0.95 on a target that ranges over hundreds of units and R² = 0.20 on a target that ranges over ten. The model did not change. The baseline did.
Constant targets
If every value in y_true is the same, SStot is 0 and the ratio is undefined. In recent scikit-learn versions, `r2score has force_finite=True by default. It returns 1.0 for perfect predictions and 0.0 otherwise, rather than nan or -inf`. That is convenient for automated search, but it hides a degenerate case. If you see exactly 0.0 on a small test fold, check whether that fold has any variation in its targets. Scoring on fewer than two samples also makes R² undefined.
A practical workflow
- Split the data before looking at the metric. Fit only on the training portion.
- Score both splits with
r2_score. A large gap between training and test R² points to overfitting. - If the test R² is negative, run the checks in the diagram above before changing the model.
- When comparing models with different feature counts, use cross-validated R² or adjusted R², and keep RMSE next to them in target units.
- Report the baseline you used (training mean or test mean) when you quote R², especially if the target distribution may shift.
Summary
- R² is 1 − SSres / SStot. It goes below 0 whenever the model does worse than a constant at the mean of
y_true. - Negative values appear on held-out data from overfitting, distribution shift, or a mismatch between the training mean and the test mean.
- Training R² for nested least-squares models never decreases when you add features, even useless ones. Rely on held-out scores.
- Adjusted R² penalizes extra predictors and can show that a higher raw R² is not an improvement. It is an in-sample correction, not a substitute for a test set.
- R² depends on the spread of the target. Do not compare it across datasets without also looking at an error in target units.
Exercise
A linear model fitted on 40 samples has R² = 0.90 with 12 predictors. Compute the adjusted R² and say whether the model is clearly better than a 2-predictor model with R² = 0.87 on the same data.
Show answer
For the 12-predictor model, (1 − 0.90) × (40 − 1) / (40 − 12 − 1) = 0.10 × 39 / 27 ≈ 0.1444, so adjusted R² ≈ 0.8556. For the 2-predictor model, (1 − 0.87) × 39 / 37 = 0.13 × 1.0541 ≈ 0.1370, so adjusted R² ≈ 0.8630. The simpler model has the higher adjusted R², so the 12-predictor model is not clearly better despite its higher raw R².
Exercise
A model trained on house prices from one city scores R² = 0.78 on a held-out split of the same city and R² = −0.6 on data from a different city. Give two possible explanations and one check for each.
Show answer
First, distribution shift: the second city has a different price range or feature relationships, so the model's predictions sit far from the true values. Check by comparing the target histograms and feature distributions of the two datasets. Second, a narrow target range in the second city: if its prices vary little, SS_tot is small and even modest errors push R² below 0. Check by computing RMSE or MAE in price units and comparing them with the standard deviation of the second city's prices.
Exercise
You add a column of random numbers to a least-squares model that includes an intercept. What can you say about the training R², and why is that a problem for model selection?
Show answer
The training R² cannot decrease, and it will usually increase slightly. The old model is a special case of the new one (coefficient zero on the new column), and least squares minimizes SS_res over all coefficient choices. A selection rule based on training R² would therefore always prefer the model with more columns. Use held-out R², cross-validation, or adjusted R² instead.