2.2.8Linear & Logistic Regression

R-squared and adjusted R-squared

2,618 words12 min readdifficulty · medium1 backlinks

What is R-squared?

Range: R2[0,1]R^2 \in [0, 1] for typical regression (can be negative for bad models without intercept)

Derivation from First Principles

WHY do we need this? The mean yˉ\bar{y} is our baseline predictor—if we know nothing, we'd predict the mean. A regression model tries to beat this baseline. We need a metric that compares how much variance remains (residuals) vs. the original variance.

Start with variance decomposition: SStot=SSreg+SSresSS_{tot} = SS_{reg} + SS_{res}

WHY this works: Total variance = Explained variance + Unexplained variance

  1. Total variance SStotSS_{tot}: How much yy values spread around their mean SStot=i=1n(yiyˉ)2SS_{tot} = \sum_{i=1}^{n}(y_i - \bar{y})^2

  2. Residual variance SSresSS_{res}: How much predictions miss the actual values SSres=i=1n(yiy^i)2SS_{res} = \sum_{i=1}^{n}(y_i - \hat{y}_i)^2

  3. Explained variance SSregSS_{reg}: How much the model predictions vary from the mean SSreg=i=1n(y^iyˉ)2SS_{reg} = \sum_{i=1}^{n}(\hat{y}_i - \bar{y})^2

Now derive R2R^2: SStot=SSreg+SSresSS_{tot} = SS_{reg} + SS_{res} SStotSStot=SSregSStot+SSresSStot\frac{SS_{tot}}{SS_{tot}} = \frac{SS_{reg}}{SS_{tot}} + \frac{SS_{res}}{SS_{tot}} 1=SSregSStot+SSresSStot1 = \frac{SS_{reg}}{SS_{tot}} + \frac{SS_{res}}{SS_{tot}} SSregSStot=1SSresSStot\frac{SS_{reg}}{SS_{tot}} = 1 - \frac{SS_{res}}{SS_{tot}}

This ratio is R2R^2: R2=1SSresSStotR^2 = 1 - \frac{SS_{res}}{SS_{tot}}

WHY this interpretation works: If SSres=0SS_{res} = 0 (perfect fit), R2=1R^2 = 1. If SSres=SStotSS_{res} = SS_{tot} (model no better than mean), R2=0R^2 = 0.

Figure — R-squared and adjusted R-squared

For simple linear regression (y=β0+β1xy = \beta_0 + \beta_1 x): R2=r2R^2 = r^2 where rr is the Pearson correlation coefficient between xx and yy.

WHY? In simple regression, the proportion of variance explained equals the squared correlation. This doesn't hold for multiple regression!

What is Adjusted R-squared?

Alternative form: Radj2=1(1R2)n1np1R^2_{adj} = 1 - (1-R^2)\frac{n-1}{n-p-1}

Derivation: Why the Penalty?

THE PROBLEM: Regular R2R^2 always increases when you add more features, even if those features are pure noise!

WHY this happens: More parameters → model can fit training noise → SSresSS_{res} decreases → R2R^2 increases, even if the model generalizes worse.

THE FIX: Penalize by degrees of freedom used.

Start with the variance ratio:

  • Residual variance estimate: σ^res2=SSresnp1\hat{\sigma}^2_{res} = \frac{SS_{res}}{n-p-1} (unbiased estimator)
  • Total variance estimate: σ^tot2=SStotn1\hat{\sigma}^2_{tot} = \frac{SS_{tot}}{n-1} (sample variance)

Build the adjusted metric: Radj2=1σ^res2σ^tot2=1SSres/(np1)SStot/(n1)R^2_{adj} = 1 - \frac{\hat{\sigma}^2_{res}}{\hat{\sigma}^2_{tot}} = 1 - \frac{SS_{res}/(n-p-1)}{SS_{tot}/(n-1)}

Relate to R2R^2: Radj2=1SSresSStotn1np1R^2_{adj} = 1 - \frac{SS_{res}}{SS_{tot}} \cdot \frac{n-1}{n-p-1} Radj2=1(1R2)n1np1R^2_{adj} = 1 - (1-R^2)\frac{n-1}{n-p-1}

WHY this works: The penalty factor n1np1\frac{n-1}{n-p-1} increases as pp increases. Adding a useless feature increases pp but doesn't decrease SSresSS_{res} enough to compensate → Radj2R^2_{adj} decreases.

Step 1: Compute mean yˉ=200+250+300+350+4005=300\bar{y} = \frac{200+250+300+350+400}{5} = 300 WHY this step? The mean is our baseline—how well would we do predicting the average every time?

Step 2: Compute SStotSS_{tot} SStot=(200300)2+(250300)2+(300300)2+(350300)2+(400300)2SS_{tot} = (200-300)^2 + (250-300)^2 + (300-300)^2 + (350-300)^2 + (400-300)^2 =10000+2500+0+2500+10000=25000= 10000 + 2500 + 0 + 2500 + 10000 = 25000 WHY this step? This is the total variance we're trying to explain.

Step 3: Compute SSresSS_{res} SSres=(200210)2+(250240)2+(300310)2+(350340)2+(400390)2SS_{res} = (200-210)^2 + (250-240)^2 + (300-310)^2 + (350-340)^2 + (400-390)^2 =100+100+100+100+100=500= 100 + 100 + 100 + 100 + 100 = 500 WHY this step? This is the variance our model fails to explain—the leftover error.

Step 4: Compute R2R^2 R2=150025000=10.02=0.98R^2 = 1 - \frac{500}{25000} = 1 - 0.02 = 0.98

Interpretation: The model explains 98% of variance in house prices. Excellent fit!

Step 1: Apply the formula Radj2=1(10.98)51521R^2_{adj} = 1 - (1-0.98)\frac{5-1}{5-2-1} WHY this step? We need to penalize for the 2 features we used.

Step 2: Calculate Radj2=1(0.02)42=10.04=0.96R^2_{adj} = 1 - (0.02)\frac{4}{2} = 1 - 0.04 = 0.96

Interpretation: After penalizing for 2 features, we still explain 96% of variance.

Now add useless 3rd feature (random noise):

  • New R2=0.985R^2 = 0.985 (slightly higher due to overfitting)
  • p=3p = 3

Radj2=1(10.985)4531=1(0.015)41=10.06=0.94R^2_{adj} = 1 - (1-0.985)\frac{4}{5-3-1} = 1 - (0.015)\frac{4}{1} = 1 - 0.06 = 0.94

WHY it decreased: The new feature added negligible explanatory power but consumed a degree of freedom. Radj2R^2_{adj} caught this!

Radj2=1(10.99)4950481=1(0.01)×49=10.49=0.51R^2_{adj} = 1 - (1-0.99)\frac{49}{50-48-1} = 1 - (0.01)\times 49 = 1 - 0.49 = 0.51

WHY the huge drop? With p=48p=48 and n=50n=50, you only have 1 degree of freedom left! The model is fitting noise, not signal. Radj2R^2_{adj} reveals this disaster.

Why it feels right: High R2R^2 means the model fits the training data well.

Why it's wrong:

  1. R2R^2 measures training fit, not generalization
  2. Overfitted models have high R2R^2 but fail on new data
  3. R2R^2 doesn't detect if you're fitting noise

The fix: Always validate on held-out test data. Use cross-validation. Check Radj2R^2_{adj} for feature proliferation.

Why it feels right: R2R^2 increased, which sounds like improvement.

Why it's wrong: R2R^2 cannot decrease when adding features (mathematically impossible on training data). The increase might be pure overfitting.

The fix: Use Radj2R^2_{adj}. If it decreases or barely changes, the new features are useless. Better yet, use cross-validated metrics.

Why it feels right: In typical linear regression with intercept, R20R^2 \geq 0 holds.

Why it's wrong: If you fit a model without an intercept or use a model so bad that SSres>SStotSS_{res} > SS_{tot}, R2R^2 can be negative!

Example: Force regression through origin when data has large intercept → terrible predictions → negative R2R^2.

The fix: Always include an intercept unless you have strong theoretical reasons. If R2<0R^2 < 0, your model is worse than predicting the mean.

Key Properties

Property 1: R-squared and Model Complexity

  • R2R^2 is non-decreasing in pp (number of features)
  • Radj2R^2_{adj} can decrease if added feature is weak
  • For nested models (Model A ⊂ Model B), RB2RA2R^2_B \geq R^2_A but Radj,B2R^2_{adj,B} may be <Radj,A2< R^2_{adj,A}

Property 2: Perfect Fit vs. No Fit

R2=1    SSres=0    perfect predictionsR^2 = 1 \iff SS_{res} = 0 \iff \text{perfect predictions} R2=0    SSres=SStot    model = meanR^2 = 0 \iff SS_{res} = SS_{tot} \iff \text{model = mean}

Property 3: Relationship Between Metrics

Radj2=R2(1R2)pnp1R^2_{adj} = R^2 - (1-R^2)\frac{p}{n-p-1} The "penalty" is (1R2)pnp1(1-R^2)\frac{p}{n-p-1}, which grows with:

  • More features (pp↑)
  • Smaller sample (nn ↓)
  • Worse fit (R2R^2 ↓)
Recall Explain to a 12-year-old

Imagine you're trying to guess how tall your classmates are. If you just guess "average height" every time, you'll be pretty wrong. Now, what if you use clues like their age and shoe size? If your guesses get way better, R-squared measures HOW MUCH BETTER.

Think of it like a test score: if R-squared is 0.80, your clues helped you get 80% of the way from "random guessing" to "perfect prediction." An R-squared of 1.0 is 100%—you're a mind reader!

But here's the trick: what if you add a silly clue like "favorite color"? It won't actually help, but you might get lucky and your score goes up a tiny bit just by chance. Adjusted R-squared is like a strict teacher who says "Nope, I'm taking points off for using useless clues!" It keeps you honest and makes sure you only use clues that truly help.

When to Use Which

Metric Use When
R2R^2 Comparing models with same number of features
Radj2R^2_{adj} Comparing models with different numbers of features
Neither Final model evaluation (use test set MSE, MAE, cross-validation)

WHY? Both R2R^2 and Radj2R^2_{adj} are training metrics. They don't tell you how well the model generalizes. For production decisions, always validate on unseen data.

Remember: Regular R² is like a student who counts "I studied!" even if they just stared at the book. Adjusted R² is the actual exam score.

Connections

  • Linear Regression -squared evaluates linear model fit
  • Mean Squared Error - R2R^2 relates to MSE: R2=1MSEVar(y)R^2 = 1 - \frac{MSE}{Var(y)}
  • Overfitting - High R2R^2 with low Radj2R^2_{adj} signals overfitting
  • Feature Selection - Use Radj2R^2_{adj} to decide if features help
  • Cross-Validation - Better than R2R^2 for true performance estimation
  • Bias-Variance Tradeoff - Radj2R^2_{adj} implicitly trades off bias and variance
  • Model Selection - AIC/BIC provide alternative penalized fit metrics

#flashcards/ai-ml

What does R-squared measure? :: The proportion of variance in the dependent variable explained by the model, ranging from 0 (no explanation) to 1 (perfect explanation).

Write the formula for R-squared in terms of sum of squares.
R2=1SSresSStotR^2 =1 - \frac{SS_{res}}{SS_{tot}} where SSresSS_{res} is residual sum of squares and SStotSS_{tot} is total sum of squares.
What is the key difference between R-squared and adjusted R-squared?
Adjusted R-squared penalizes for the number of features using degrees of freedom, while regular R-squared always increases when adding features.
Write the formula for adjusted R-squared.
Radj2=1(1R2)n1np1R^2_{adj} = 1 - (1-R^2)\frac{n-1}{n-p-1} where nn is sample size and pp is number of predictors.
Why can regular R-squared be misleading?
It always increases when adding features, even if those features are pure noise, making it prone to encouraging overfitting.
When is adjusted R-squared preferred over R-squared?
When comparing models with different numbers of features, as it accounts for model complexity.
What does SStotSS_{tot} represent?
Total sum of squares: SStot=(yiyˉ)2SS_{tot} = \sum(y_i - \bar{y})^2, the total variance in the dependent variable.
What does SSresSS_{res} represent?
Residual sum of squares: SSres=(yiy^i)2SS_{res} = \sum(y_i - \hat{y}_i)^2, the unexplained variance (prediction errors).
Can R-squared be negative?
Yes, if the model fits worse than predicting the mean (typically when fitting without an intercept or using a very bad model).
What is the range of adjusted R-squared?
It can be negative (for terrible models) up to 1, and is always ≤ R-squared.
How does R-squared relate to correlation in simple linear regression?
In simple linear regression, R2=r2R^2 = r^2 where rr is the Pearson correlation coefficient.
What does R-squared = 0 mean?
The model explains none of the variance—it performs no better than always predicting the mean.
What does R-squared = 1 mean?
The model perfectly predicts all observations with zero residual error.
Why does adjusted R-squared penalize adding features?
Because each feature consumes a degree of freedom; if a feature doesn't sufficiently reduce error, the penalty outweighs the benefit.
What is the penalty term in adjusted R-squared?
(1R2)pnp1(1-R^2)\frac{p}{n-p-1}, which increases with more features pp, smaller sample nn, or worse fit (lower R2R^2).

Concept Map

defines

produces

produces

decomposes into

decomposes into

feeds

feeds

equals SS_reg over SS_tot

equals r^2 in simple regression

penalized by predictors p

uses degrees of freedom

guards against

Mean as baseline predictor

SS_tot total variance

Regression model

SS_res unexplained variance

SS_reg explained variance

R-squared

Proportion variance explained

Pearson correlation r

Adjusted R-squared

n minus p minus 1

Too many useless features

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Chalो dekhte hain iska core intuition. Jab tum koi regression model banate ho, tumhe pata kaise chalega ki wo achha kaam kar raha hai ya nahi? Yahi kaam R-squared karta hai. Simple bhaasha mein, ye batata hai ki tumhare data mein jitna variation (utaar-chadhaav) hai, uska kitna percentage tumhara model explain kar paa raha hai. Socho ki agar tumhe kuch nahi pata, to tum har baar simply average (mean) value predict karoge — ye tumhara baseline hai. R-squared basically ye compare karta hai ki tumhara model us baseline se kitna behtar hai. Formula R2=1SSresSStotR^2 = 1 - \frac{SS_{res}}{SS_{tot}} mein SSresSS_{res} matlab jo error bacha (unexplained), aur SStotSS_{tot} matlab total variation. Agar error zero hai to R2=1R^2 = 1 (perfect), aur agar model mean jaisa hi hai to R2=0R^2 = 0 (bekaar).

Ab yahan ek badi problem aati hai jiski wajah se Adjusted R-squared aata hai. Regular R-squared ki ek gandi aadat hai — jab bhi tum koi naya feature add karte ho, chahe wo bekaar noise hi kyun na ho, R-squared हमेशा badh jaata hai ya same rehta hai, kabhi ghatta nahi. Iska matlab tum galti se ye soch sakte ho ki zyada features add karne se model behtar ho raha hai, jabki reality mein wo sirf training data ke noise ko yaad kar raha hai (overfitting). Isiliye Adjusted R-squared thoda "skeptical" version hai — ye tumhe har extra feature ke liye penalty deta hai. Formula mein jo (np1)(n-p-1) term hai, wo degrees of freedom ka dhyaan rakhta hai, jahan pp features ki sankhya hai. Agar naya feature actually useful hai to Adjusted R-squared badhega, warna wo ghat jaayega.

Ye kyun important hai? Real life mein tumhare paas bahut saare features ho sakte hain aur tumhe decide karna hota hai ki kaunse rakhne hain. Agar tum sirf plain R-squared pe bharosa karoge to tum har cheez model mein daalte jaaoge aur model dikhne mein achha lagega par naye data pe fail ho jaayega. Adjusted R-squared tumhe honest feedback deta hai ki extra complexity worth hai ya nahi. Interview mein bhi ye ek common question hai, aur practically model banate waqt ye tumhari model selection ko sahi rakhta hai — isliye dono ka fark samajhna zaroori hai.

Go deeper — visual, from zero

Test yourself — Linear & Logistic Regression

Connections