TExcelTAD
Home › Data Science › DS Regression R-Squared

DS Regression R-Squared

R-squared (R², the coefficient of determination) answers one question: what share of the variation in the dependent variable does the model explain? It ranges from 0 (the model explains nothing — you might as well predict the mean every day) to 1 (the model predicts every value perfectly).

Our temperature model has R² = 0.726: temperature explains about 73 % of the day-to-day variation in rides. The other 27 % comes from rain, weekends and chance.

Where R² comes from

R² compares two sums of squares:

text
SST = Σ (yᵢ − mean)²        total variation: errors of the "always predict the mean" model
SSE = Σ (yᵢ − ŷᵢ)²          variation left over after the regression
R²  = 1 − SSE / SST
python · try it yourself
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

model = smf.ols("rides ~ temp_c", data=bikes).fit()
y = bikes["rides"]

sst = ((y - y.mean()) ** 2).sum()
sse = (model.resid ** 2).sum()
print(f"SST = {sst:.0f}")
print(f"SSE = {sse:.0f}")
print(f"R2 by hand   = {1 - sse / sst:.4f}")
print(f"model.rsquared = {model.rsquared:.4f}")
print(f"corr(temp, rides)^2 = {y.corr(bikes['temp_c']) ** 2:.4f}")
SST = 695473
SSE = 190638
R2 by hand   = 0.7259
model.rsquared = 0.7259
corr(temp, rides)^2 = 0.7259

With one predictor, R² equals the squared correlation between x and y — 0.852² ≈ 0.726.

What "good" R² means depends on the field

There is no universal threshold. Physics experiments often reach 0.99; models of human behaviour may be useful at 0.2. More important questions are:

  • Are the prediction errors small enough for the decision at hand?
  • Do the residuals look random (Residual Analysis)?
  • Does the model work on data it hasn't seen (Train/Test Split)?

R² always rises when you add variables

Adding any variable — even pure noise — can never lower R² on the data used for fitting. That makes R² a poor tool for choosing between models of different size. Adjusted R² fixes this by penalising every extra predictor:

text
adjusted R² = 1 − (1 − R²) × (n − 1) / (n − k − 1)
python · try it yourself
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

junk = np.random.default_rng(9)
for i in range(1, 9):
    bikes[f"junk{i}"] = junk.normal(size=60)

formulas = [
    "rides ~ temp_c",
    "rides ~ temp_c + rain_mm",
    "rides ~ temp_c + rain_mm + weekend",
    "rides ~ temp_c + rain_mm + weekend + " + " + ".join(f"junk{i}" for i in range(1, 9)),
]
for f in formulas:
    m = smf.ols(f, data=bikes).fit()
    print(f"{int(m.df_model):2} predictors: R2={m.rsquared:.4f}  adjusted R2={m.rsquared_adj:.4f}")
 1 predictors: R2=0.7259  adjusted R2=0.7212
 2 predictors: R2=0.8487  adjusted R2=0.8434
 3 predictors: R2=0.9155  adjusted R2=0.9110
11 predictors: R2=0.9204  adjusted R2=0.9022

Adding rain and weekend raises both measures — they carry real information. Adding eight junk variables still nudges R² up a little, but adjusted R² goes down: the penalty outweighs the tiny, accidental gain.

R² doesn't tell you everything

A high R² does not mean the model is right. Here are two datasets with almost the same R² but very different stories:

python · try it yourself
import numpy as np
import statsmodels.api as sm

x = np.arange(1, 21, dtype=float)
straight = 3 * x + np.random.default_rng(5).normal(0, 3, 20)
curved = 0.25 * x ** 2

for name, y in [("straight + noise", straight), ("curve, no noise", curved)]:
    m = sm.OLS(y, sm.add_constant(x)).fit()
    res = m.resid
    pattern = np.corrcoef(res[:-1], res[1:])[0, 1]
    print(f"{name:17} R2={m.rsquared:.3f}  neighbouring residuals corr={pattern:5.2f}")
straight + noise  R2=0.974  neighbouring residuals corr= 0.18
curve, no noise   R2=0.944  neighbouring residuals corr= 0.92

Both fits score a high R² (0.97 and 0.94), but the curved data's residuals are strongly related to their neighbours (correlation 0.92), while the noisy straight line's residuals hardly are: the line systematically misses — too high in the middle, too low at both ends. A straight line is the wrong shape there, and R² alone can't tell you. This example also shows sm.OLS, statsmodels' array interface, where you add the intercept column yourself with sm.add_constant.

Test yourself

A model has R² = 0.40. What does that mean?

  1. It is correct 40 % of the time
  2. It explains 40 % of the variance in the dependent variable
  3. 40 % of coefficients are significant
  4. The slope is 0.40

You add a column of random noise to a regression. What happens to R² on the training data?

  1. It decreases
  2. It stays the same or increases slightly
  3. It becomes 0
  4. It doubles

For a simple regression with one predictor and correlation r = 0.6, what is R²?

  1. 0.6
  2. 0.36
  3. 0.77
  4. 1.2