Method · Statistics Library

Linear regression

Linear regression fits a straight-line relationship between a continuous outcome and one or more predictors, reporting each predictor's coefficient with a significance test, an overall model fit (R-squared), and a full set of assumption diagnostics.

Chapter 5: Regression and predictionReading 5.1

Understand the idea

Linear regression answers a very natural question: as one or more predictors change, how does the outcome tend to change, ON AVERAGE, in a straight-line way? Each predictor gets its own slope, telling you how much the outcome moves for a one-unit change in that predictor while holding every other predictor fixed. The intercept is what the model predicts when every predictor equals zero (which is not always a meaningful value to picture, especially if zero is outside your data's actual range).

R-squared answers 'how much of the outcome's variation does this model actually explain?': 0 means none, 1 means all of it, perfectly. Adding more predictors to a model can never make R-squared go down, even predictors that are pure noise, which is exactly why adjusted R-squared exists: it specifically penalizes adding predictors that do not genuinely help, giving a fairer comparison between models with different numbers of predictors.

This card does not just hand you an equation: it automatically runs a battery of assumption checks (are the residuals (the gaps between each actual value and the model's prediction) independent, roughly normal, and evenly spread; are predictors too tangled up with each other; whether the relationship is really a straight line you judge from the residual plot) and flags unusually influential individual rows that might be distorting the whole fit. Reading those checks is not optional homework; they tell you whether the coefficients and p-values you are about to quote can actually be trusted.

Linear regression is usually fitted by ordinary least squares, so it is often called OLS regression; with more than one predictor it is called multiple regression. The VIF, or variance inflation factor, shows how much a coefficient's uncertainty is inflated by its correlation with the other predictors; values above about 5 to 10 are a warning.

Practitioner explanation

KernelStats fits OLS via statsmodels with the classical formula-based approach; categorical predictors are auto-encoded (one-hot). Standard errors default to classical but can be switched to heteroscedasticity-consistent HC0-HC3 without refitting; SE/t/p/CI are simply rebuilt from the robust covariance matrix. AIC/BIC count k as the number of REGRESSION COEFFICIENTS including the intercept (the statsmodels convention); R's AIC()/BIC() additionally count the residual variance sigma^2 as a parameter, making R's numbers larger by exactly 2 (AIC) and ln(n) (BIC); this offset is stated explicitly so a cross-check against R is not mistaken for a discrepancy, and model COMPARISONS are unaffected since the constant cancels on subtraction.

Four assumptions are tested automatically and reported on the card, not left as an exercise: independence of residuals (Durbin-Watson, target near 2), normality of residuals (Shapiro-Wilk), homoscedasticity (Breusch-Pagan), and multicollinearity via Variance Inflation Factor (VIF_j = 1/(1-R_j^2), where R_j^2 comes from regressing predictor j on all the others); VIF > 5 is flagged as concerning, 10 as an absolute ceiling. Linearity has no formal test on the card; it is judged from the residual-versus-fitted plot.

Influential-observation flagging uses THREE independent criteria and flags a row if ANY ONE fires: Cook's distance > 4/n (the sensitive screening threshold, deliberately more sensitive than the older 'Cook's D > 1' rule which only catches points that would drastically move the fit on their own), leverage > 2p/n, or an absolute externally-studentized residual > 3 (n = rows used, p = estimated parameters including the intercept). This is a deliberately more sensitive default than the historically common thresholds, framed explicitly as a screening tool: a flagged row is NOT automatically bad data and warrants inspection, not automatic removal.

When to use it

Consider it when

Predicting a continuous outcome (counts, prices, scores, durations) from one or more predictors, expecting roughly linear relationships, when interpretable coefficients with confidence intervals and p-values are needed.

Use caution when

The outcome is categorical or a count with a strongly skewed distribution (use logistic or Poisson regression instead), the relationship is clearly non-linear (consider a polynomial, spline, or GAM), or the assumption diagnostics (especially high VIF or a failed Breusch-Pagan test) indicate the classical standard errors and p-values cannot be trusted as reported.

Formulas and symbols

Multiple linear regression model

Y=β0+β1X1+β2X2+⋯+εY = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \dots + \varepsilon

beta_j the slope of Y per one-unit change in X_j, holding other predictors fixed; epsilon the residual.

R-squared

R2=1−SSresidualSStotalR^2 = 1 - \dfrac{SS_{\text{residual}}}{SS_{\text{total}}}

The proportion of Y's variance explained by the model; adjusted R-squared additionally penalizes adding predictors that do not help.

Variance Inflation Factor

VIFj=11−Rj2\text{VIF}_j = \dfrac{1}{1 - R_j^2}

R_j^2 the R-squared from regressing predictor j on all other predictors. VIF > 5 flagged as concerning, 10 as an absolute ceiling.

Assumptions and checks

  • Normality (of residuals, not of the raw data). Non-normal residuals make the standard errors, t-tests, and confidence intervals on the coefficients approximate rather than exact; the effect is usually modest at large n (the CLT helps) but can matter for small samples or strongly skewed errors.

    In KernelStats: Shapiro-Wilk on the model residuals (for 3 to 5000 residuals), reported directly on the card.

  • Homogeneity of variance (homoscedasticity). Heteroscedasticity (residual spread that changes with the fitted value) makes the classical standard errors, and therefore every p-value and confidence interval, wrong, usually too narrow in the region of higher variance.

    In KernelStats: Breusch-Pagan test on the residuals (skipped above roughly 50,000 rows, where it becomes over-powered), reported directly on the card; when it fails, the card recommends re-running with heteroscedasticity-consistent (HC3) standard errors, and states directly when those robust standard errors are already the ones being used below.

  • Independence of observations. Autocorrelated residuals (common in time-ordered data) make the standard errors too small, inflating apparent significance; the F and t statistics are no longer valid.

    In KernelStats: Durbin-Watson statistic on the residuals (skipped above roughly 50,000 rows), reported directly on the card and flagged outside the conventional 1.5-2.5 band.

  • No (severe) multicollinearity. Severely collinear predictors make individual coefficients unstable and their standard errors inflated, even though the model's overall fit and predictions remain fine.

    In KernelStats: Variance Inflation Factor computed for every predictor (skipped above 20 predictors, since VIF cost is quadratic in the predictor count), with the maximum VIF reported on the card and flagged above 5 (warn) or 10 (fail).

Alternatives

  • Logistic Regression. The outcome is binary (yes/no, success/failure) rather than continuous.
  • Polynomial Regression. The linearity assumption is violated and a known curved (polynomial) shape is a reasonable description.
  • Ridge Regression. Predictors show severe multicollinearity (high VIF) and stabilizing the coefficients matters more than unbiased inference on any single one.

Worked example

Scenario

Predicting penguin body mass from flipper length and species, with classical standard errors.

Result

Flipper length: beta = 40.7 g per mm, p < .001 (species adjusted: Chinstrap -207 g, Gentoo +267 g relative to Adelie); R-squared = 0.78, adjusted R-squared = 0.78. Shapiro-Wilk passes (p = .31), but Breusch-Pagan flags heteroscedasticity (p = .044), the maximum VIF is 5.07 (flipper length and the Gentoo indicator overlap), and Durbin-Watson = 2.56 is outside the 1.5-2.5 band.

Interpretation

Flipper length is a strong predictor of body mass within species, and the model explains 78% of the variance. The flagged checks change how to report it: re-run with HC3 standard errors because of the heteroscedasticity, read the flipper and Gentoo coefficients knowing they share information, and note that the Durbin-Watson flag reflects the file being sorted by species (row order), not a time-series dependence.

Dataset: penguins.csv

Common misconceptions

Misconception

A higher R-squared always means a better, more trustworthy model.

Correction

R-squared can never decrease when you add MORE predictors, even predictors that are pure noise: it mechanically rewards complexity. Adjusted R-squared, which penalizes unhelpful additions, is the fairer basis for comparing models with different numbers of predictors, and neither R-squared nor adjusted R-squared says anything about whether the model's ASSUMPTIONS (linearity, independence, homoscedasticity) actually hold.

Read more: Misconception: a high R-squared means the model will predict accurately on new data

Misconception

A row flagged as an 'influential observation' should simply be deleted from the analysis.

Correction

The three influence criteria this card checks (Cook's distance, leverage, studentized residuals) are a SCREENING tool, not an automatic data-cleaning rule. A flagged row deserves inspection (it may be a legitimate, important observation, a data-entry error, or simply an extreme but real value), and the decision to exclude it belongs to the analyst with a documented reason, never to an automatic threshold.

References

  1. NIST/SEMATECH e-Handbook of Statistical Methods, §4.1 Linear Least Squares Regression, NIST/SEMATECH (2012), §4.1.
  2. Applied Linear Statistical Models, Kutner, M. H., Nachtsheim, C. J., Neter, J. and Li, W. (2004).