Sub topic 6
R squared: how much better than the baseline?
R squared (written R², also called the coefficient of determination) answers a different question from MAE and RMSE. Those two report the size of the error in the units of the target. R² reports how much of the target's variation the model explains, compared with a model that ignores the inputs.
This chapter assumes you can read basic NumPy, know what residuals are, and understand the predict-the-mean baseline from the previous chapter. It also assumes you know why models are scored on a held-out test set.
The definition
R² compares two sums of squared errors.
- The residual sum of squares,
SS_res, is the sum of (ytrue − ypred)² over all samples. It measures the error of your model. - The total sum of squares,
SS_tot, is the sum of (ytrue − mean(ytrue))² over all samples. It measures the error of the baseline that always predicts the mean.
The formula is:
R² = 1 − SSres / SStot
The ratio SSres / SStot is the fraction of the baseline's squared error that your model still makes. R² is what remains after subtracting that fraction from 1.
A worked example
This is the same four-point example used for MAE and RMSE, so you can compare the numbers.
import numpy as np
y_true = np.array([3.0, 5.0, 2.5, 7.0])
y_pred = np.array([2.5, 5.0, 4.0, 8.0])
ss_res = np.sum((y_true - y_pred) ** 2) # 3.5
ss_tot = np.sum((y_true - y_true.mean()) ** 2) # 12.6875
r2 = 1 - ss_res / ss_tot # about 0.7241
print(ss_res, ss_tot, r2)The mean of y_true is 4.375. The baseline's squared errors are 1.890625, 0.390625, 3.515625 and 6.890625, which add up to 12.6875. The model's squared errors are 0.25, 0, 2.25 and 1, which add up to 3.5. The model keeps 3.5 / 12.6875, or about 27.6%, of the baseline's squared error. So R² is about 0.724, and you can say the model removes about 72% of the baseline's squared error.
R² and RMSE are the same information on different scales
Divide both sums by the number of samples n:
- SS_res / n is the MSE.
- SS_tot / n is the variance of y, which is the squared standard deviation.
So R² = 1 − MSE / Var(y). In the example, MSE is 0.875 and the variance of y_true is 3.171875. The ratio is 0.2759, and 1 − 0.2759 = 0.7241.
This relationship has two practical consequences:
- On a fixed test set, R² and RMSE rank models in the same order. A lower RMSE always means a higher R², because the variance of y does not change between models.
- They differ when you compare across datasets. RMSE carries the units of the target, so an RMSE of 10 means different things for house prices in dollars and for temperatures in degrees. R² has no units, because the units cancel in the ratio. R² still depends on how spread out the target is. The same model error gives a higher R² on a target with a large variance.
Reading the scale
| R² | Meaning |
|---|---|
| 1.0 | Every prediction is exact. `SS_res` is 0. |
| Between 0 and 1 | The model beats the mean baseline. Closer to 1 is better. |
| 0 | The model is exactly as good as predicting the mean. |
| Below 0 | The model is worse than predicting the mean. |
There is no universal threshold for a "good" R². In a physics experiment with low noise, 0.95 may be disappointing. In predicting human behavior or stock returns, 0.2 may be useful. Judge R² against the noise level of the problem and against other models on the same data.
The baseline scores exactly zero
The mean baseline sets the zero point of the scale. Plugging it into the formula makes SS_res equal to SS_tot:
import numpy as np
y_true = np.array([3.0, 5.0, 2.5, 7.0])
# Always predicting the mean of y_true gives R squared of exactly 0.
y_pred = np.full_like(y_true, y_true.mean())
ss_res = np.sum((y_true - y_pred) ** 2)
ss_tot = np.sum((y_true - y_true.mean()) ** 2)
print(1 - ss_res / ss_tot) # 0.0The mean is the constant that minimizes squared error. Any other constant therefore does worse and scores below zero. Predicting 5.0 for every sample gives SS_res = 14.25, so R² = 1 − 14.25 / 12.6875, or about −0.123.
Negative R²
R² is not the square of anything in this general definition, so it can be negative. A negative value means that your predictions have a larger squared error than a constant prediction of the mean.
import numpy as np
from sklearn.metrics import r2_score
y_true = np.array([3.0, 5.0, 2.5, 7.0])
bad_pred = np.array([7.0, 2.5, 5.0, 3.0]) # confidently wrong
print(r2_score(y_true, bad_pred)) # about -2.5073Here SS_res is 44.5 against a SS_tot of 12.6875. The model makes 3.5 times the baseline's squared error, so R² = 1 − 3.507 = −2.507. There is no lower bound. A single wild prediction can push R² to −100 or lower.
Negative values are common in two situations:
- The model is evaluated on data it was not trained on, and it generalizes poorly.
- The model was fit without an intercept, or with constraints that stop it from matching the average level of the target.
On training data, an ordinary least-squares linear model with an intercept cannot score below 0, because the mean baseline is one of the models it could have chosen. That guarantee ends once you move to test data or to other model types.
Which mean is the baseline?
The mean in SS_tot is the mean of the y_true you pass in. When you score a model on a test set, scikit-learn's r2_score uses the test set's own mean. It does not use the mean of the training set.
This has a subtle effect. The baseline is a slightly idealized one, because it knows the average of the data it is being scored on. A deployed baseline would only know the training mean. If the test mean differs from the training mean, the practical baseline is worse than the one R² uses, so R² is a little harsh on your model. In most projects the difference is small. It matters when the test set is small or comes from a different period than the training set.
Edge cases in the formula
- Constant target. If every
y_truevalue is the same,SS_totis 0 and the formula divides by zero. By default, scikit-learn returns 1.0 if the predictions are all perfect and 0.0 otherwise, instead of returningnanor-inf. This is theforce_finite=Truedefault. Treat such a score as a sign that the test set is unsuitable for R². - Tiny test sets. With few samples,
SS_totis small and noisy. R² can swing widely from one split to the next. - Multiple outputs. If the target has several columns,
r2_scorecomputes one R² per column and averages them with equal weight by default (multioutput="uniform_average"). A column with a tiny variance counts as much as one with a huge variance. Passmultioutput="variance_weighted"to weight each column by its variance. - Outliers.
SS_resandSS_totboth square their errors, so R² inherits RMSE's sensitivity to large misses. One extreme sample can dominate the score.
R² is not accuracy
R² of 0.72 does not mean that 72% of predictions are correct. It is not a percentage of anything about individual predictions. It says only that the squared error shrank by about 72% relative to the baseline.
R² also says nothing about how large the errors are in practice. Two models can have the same R² on different datasets while one is off by 2 dollars and the other by 20,000 dollars. For that reason, report RMSE or MAE alongside R² whenever the units matter to the reader.
Simple regression: R² as squared correlation
For simple linear regression with an intercept and one input feature, evaluated on the training data, R² equals the square of Pearson's correlation coefficient between x and y. A correlation of 0.85 gives an R² of 0.7225.
This identity does not hold in general. Once you have several features, a model without an intercept, or a test set instead of the training set, R² is no longer the squared correlation. Do not use np.corrcoef(y_true, y_pred) ** 2 as a replacement for r2_score. It ignores bias. If your predictions are perfectly correlated with the truth but shifted by a constant, the squared correlation is 1.0 and r2_score is lower.
import numpy as np
from sklearn.metrics import r2_score
y_true = np.array([3.0, 5.0, 2.5, 7.0])
shifted = y_true + 10.0 # perfect shape, wrong level
corr_squared = np.corrcoef(y_true, shifted)[0, 1] ** 2
print(round(corr_squared, 4)) # 1.0
print(round(r2_score(y_true, shifted), 4)) # about -6.8The shifted predictions are off by 10 everywhere, so SS_res is 400 and R² = 1 − 400 / 12.6875, or about −30.5. The code's printed value depends on the exact numbers, so compute it yourself. The point is that the correlation is blind to the shift and R² is not.
Common mistakes
- Reporting training R² as the result. A flexible model can reach a training R² near 1 by memorizing noise. Report R² on held-out data. Later chapters cover this and the effect of adding features.
- Comparing R² across different targets. A model for a noisy target and a model for a smooth target are not comparable through R² alone, because the variance of y differs.
- Swapping the arguments.
r2_score(y_true, y_pred)is not symmetric. The first argument defines the baseline. Passing the predictions first gives a different number. - Expecting a value between 0 and 1. Code that clips or validates R² to that range will hide the cases where your model is worse than the baseline.
Summary of what R² tells you
| Question | Does R² answer it? |
|---|---|
| Is the model better than predicting the mean? | Yes. Positive means better, negative means worse. |
| How large are typical errors, in the target's units? | No. Use MAE or RMSE. |
| Can I compare models on the same test set? | Yes. It ranks models the same way RMSE does. |
| Can I compare across unrelated datasets? | Only with caution, because it depends on the variance of y. |
| Is the model correct or unbiased? | No. Inspect the residuals. |
Exercise
A model's squared errors on a test set sum to 20. The squared deviations of the true values from their mean sum to 80. What is R², and what does it tell you about the model compared with the mean baseline?
Show answer
R² = 1 − 20 / 80 = 0.75. The model keeps a quarter of the baseline's squared error, so it removes 75% of it. It is clearly better than predicting the mean.
Exercise
You predict a constant 6.0 for every sample in the four-point example (y_true = [3.0, 5.0, 2.5, 7.0]). Is R² positive, zero, or negative, and why? Compute it.
Show answer
It is negative. The mean is 4.375, and any other constant has a larger squared error than the mean. The residuals are 3.0, 1.0, 3.5 and −1.0 in magnitude, so SSres = 9 + 1 + 12.25 + 1 = 23.25. With SStot = 12.6875, R² = 1 − 23.25 / 12.6875, which is about −0.833.
Exercise
Two models are scored on the same test set. Model A has RMSE 4.0 and Model B has RMSE 5.0. Without computing anything else, which has the higher R², and why?
Show answer
Model A. R² = 1 − MSE / Var(y), and Var(y) is the same for both models on the same test set. The lower RMSE means a lower MSE, so the ratio is smaller and R² is higher.