Regression Assumptions: The LINE Framework
Regression Analysis
Four Assumptions Every Regression Must Meet
The LINE framework (Linearity, Independence, Normality, Equal Variance) ensures OLS estimates are valid and inference is trustworthy. Violating these assumptions leads to biased or inefficient results.
- Policy Evaluation — Ensure causal estimates from regression models are credible
- Financial Modeling — Validate assumptions before using regression for risk assessment
- Scientific Research — Meet peer-review standards by demonstrating assumption compliance
Check assumptions before trusting the coefficients they produce.
What You'll Learn
- 1State the four LINE assumptions and name the consequence of breaking each one
- 2Read a residuals-versus-fitted plot and a Q-Q plot for the specific defect they reveal
- 3Run Durbin-Watson, Shapiro-Wilk, and Breusch-Pagan tests and interpret their output
- 4Match each violation to a remedy: transformation, robust standard errors, or a different model
For OLS estimates to be valid and inference to be correct, four key assumptions must hold.
What the Assumptions Actually Claim
The regression you fitted is a claim about how the data were produced: , where the errors have mean zero, no relationship with the predictors, no relationship with each other, constant spread, and — for exact small-sample inference — a normal shape. Every diagnostic in this lesson tests one clause of that sentence. The clauses are not equally important, and knowing which is which saves hours of pointless testing.
Gauss and Markov proved that linearity, strict exogeneity, absence of perfect collinearity, and spherical errors (independence plus equal variance) are enough for OLS to be the best linear unbiased estimator. Normality is not required for that result. It is required only so that t and F reference distributions are exact when the sample is small; with a few hundred observations the central limit theorem rescues those tests anyway. Independence and equal variance are the clauses you cannot wave away, because their violations corrupt the standard errors themselves, and every p-value in the report is built on those standard errors.
| Assumption | What fails when it is broken | Best diagnostic | Severity |
|---|---|---|---|
| Linearity | Slope estimates are biased; the model fits the wrong shape | Residuals versus fitted | High |
| Independence | Standard errors are wrong, usually far too small | Durbin-Watson, residual order | Critical |
| Normality | Small-sample t and F tests lose exactness | Q-Q plot, Shapiro-Wilk | Low at large n |
| Equal variance | Confidence intervals and p-values are mis-calibrated | Residuals versus fitted, Breusch-Pagan | High |
L — Linearity
The expected relationship between X and Y is linear.
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
from scipy import stats
np.random.seed(42)
n = 100
X = np.random.uniform(1, 10, n)
X_dm = sm.add_constant(X)
# Good: linear relationship
y_lin = 3 + 2*X + np.random.normal(0, 2, n)
model_lin = sm.OLS(y_lin, X_dm).fit()
# Violated: curved relationship
y_quad = 3 + 2*X + 0.5*X**2 + np.random.normal(0, 3, n)
model_quad = sm.OLS(y_quad, X_dm).fit()
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
for i, (model, label) in enumerate([(model_lin, 'Linear (Assumption Met)'),
(model_quad, 'Quadratic (Linearity Violated)')]):
axes[i,0].scatter(model.fittedvalues, model.resid, alpha=0.6)
axes[i,0].axhline(0, color='red', linestyle='--')
axes[i,0].set_title(f'{label}: Residuals vs Fitted')
axes[i,0].set_xlabel('Fitted Values')
axes[i,0].set_ylabel('Residuals')
stats.probplot(model.resid, dist='norm', plot=axes[i,1])
axes[i,1].set_title(f'{label}: Q-Q Plot')
plt.tight_layout()
plt.savefig('regression_assumptions.png', dpi=150)
plt.show()
The left-hand panel is the single most informative picture in regression diagnostics. When the true relationship is curved but you fitted a line, the residuals trace a clean arc: negative at the low end, positive in the middle, negative again at the high end. Nothing else in the output reveals that shape — the slope stays significant and may look acceptable. The remedy is to add the missing term, fit a spline, or transform the predictor, not to collect more data.
I — Independence
Residuals are independent across observations. Violated in:
- Time series data (autocorrelation)
- Clustered data (students within schools)
- Spatial data
from statsmodels.stats.stattools import durbin_watson
# Durbin-Watson statistic: 2 = no autocorrelation, <2 positive, >2 negative
dw = durbin_watson(model_lin.resid)
print(f"Durbin-Watson = {dw:.4f}")
print(f"Interpretation: {'No autocorrelation' if 1.5<dw<2.5 else 'Possible autocorrelation'}")
The Durbin-Watson statistic is approximately , where is the lag-one correlation of the residuals, so it ranges from 0 (perfect positive autocorrelation) through 2 (none) to 4 (perfect negative autocorrelation). Values between 1.5 and 2.5 are the usual comfort band. The number matters because positive autocorrelation makes the effective sample size much smaller than the row count: 200 monthly observations with carry roughly the information of 22 independent points, and ordinary standard errors overstate the precision by a factor near three.
Independence is the assumption you break by design rather than by accident. Students nested in classrooms, repeated measurements on the same patient, and transactions from the same store all violate it. The answer is not a test but a different model: cluster-robust standard errors, a mixed-effects model with random intercepts, or aggregation to the level at which observations are genuinely independent.
N — Normality of Residuals
Residuals should be approximately normally distributed.
# Shapiro-Wilk test
stat_sw, p_sw = stats.shapiro(model_lin.resid)
print(f"Shapiro-Wilk: W={stat_sw:.4f}, p={p_sw:.4f}")
# Also check Q-Q plot (visual is often more informative for moderate n)
# Normality mainly matters for inference (t-tests, p-values) — less for point estimates
Two cautions govern this test. First, Shapiro-Wilk is hypersensitive at large n: with 2,000 observations it rejects normality for deviations far too small to affect any conclusion, so a small p-value tells you the shape is not exactly Gaussian, not that your inferences are invalid. Second, normality concerns the errors, which you never observe; the residuals are a proxy, and they are mechanically squeezed because they must sum to zero and be orthogonal to the fitted values. For above roughly 50, the Q-Q plot and the shape of the residual histogram are more informative than any formal test.
The consequence of real non-normality is limited. Heavy tails inflate the type I error of t-tests slightly and make confidence intervals a touch narrow; skewed errors do the same asymmetrically. Point estimates and their standard errors are unaffected because those depend only on the first two moments.
E — Equal Variance (Homoscedasticity)
The variance of residuals should be constant across all levels of X.
# Breusch-Pagan test for heteroscedasticity
from statsmodels.stats.diagnostic import het_breuschpagan
bp_stat, bp_p, _, _ = het_breuschpagan(model_lin.resid, model_lin.model.exog)
print(f"Breusch-Pagan: χ²={bp_stat:.4f}, p={bp_p:.4f}")
print(f"Heteroscedasticity: {'Detected' if bp_p < 0.05 else 'Not detected'}")
# White's test (more general)
from statsmodels.stats.diagnostic import het_white
wh_stat, wh_p, _, _ = het_white(model_lin.resid, model_lin.model.exog)
print(f"White's test: F={wh_stat:.4f}, p={wh_p:.4f}")
A funnel shape in the residuals-versus-fitted plot is the classic signature: spread widening with the fitted value, common in spend data where large accounts vary more than small ones. Breusch-Pagan regresses the squared residuals on the predictors and tests jointly whether any coefficient is nonzero; White's test adds squares and cross-products so it also catches non-monotone patterns. A significant result does not bias the slopes, but it invalidates the homoscedastic standard errors that every confidence interval in the table was built from.
The cheapest fix in modern practice is heteroscedasticity-consistent (Huber-White) standard errors, available in one argument in statsmodels or through the vcov="HC3" option. When the variance structure is known and systematic, weighted least squares is more efficient. When the spread scales with the mean, a log transformation of the response often fixes both the variance and the skew at once.
Running the Full Diagnostic Suite
import pandas as pd
def regression_diagnostics(model, resid_order=None):
"""One-pass LINE check for a statsmodels OLS fit."""
r = model.resid
fitted = model.fittedvalues
out = {}
# L: curvature in residuals vs fitted
lo, hi = np.quantile(fitted, [0.1, 0.9])
mid = fitted[(fitted > lo) & (fitted < hi)]
out['resid_mean_by_third'] = float(np.mean(np.abs(
r[(fitted > lo) & (fitted < hi)])))
# I: autocorrelation in the order the rows were collected
out['durbin_watson'] = float(durbin_watson(r))
# N: normality of residuals
out['shapiro_W'], out['shapiro_p'] = stats.shapiro(r)
# E: constant variance
out['breusch_pagan_p'] = het_breuschpagan(r, model.model.exog)[1]
out['r_squared'] = model.rsquared
out['n_params'] = int(model.df_model)
return pd.Series(out)
print(regression_diagnostics(model_lin).round(4))
Treat the output as a decision list rather than a scorecard. A Durbin-Watson far from 2 calls for cluster-robust or time-series standard errors before anything else. A significant Breusch-Pagan calls for HC3 standard errors. A Q-Q plot with heavy tails calls for either robust inference or a bootstrap. Only a curved residuals-versus-fitted plot requires changing the model specification itself, and it is the only one of the four that no amount of standard-error adjustment can repair.
Remedy Selection
| Violation found | First remedy | Stronger remedy | Avoid |
|---|---|---|---|
| Curvature | Add polynomial or spline terms | Transform the predictor | Ignoring it, or adding robust SEs |
| Autocorrelation | Newey-West or cluster-robust SEs | ARIMA errors, mixed model | Reporting naive SEs |
| Grouped observations | Cluster-robust SEs | Multilevel model with random effects | Treating rows as independent |
| Heavy tails | Bootstrap the confidence intervals | Student-t or robust regression | Deleting outliers by eye |
| Heteroscedasticity | HC3 standard errors | Weighted least squares | Plain OLS standard errors |
| Non-normal errors at small n | Log or Box-Cox transform | Permutation or rank-based test | Relying on the central limit theorem |
Common Mistakes
Running Shapiro-Wilk and abandoning the model on a small p-value
Fix: With large samples it rejects harmless departures. Look at the Q-Q plot and ask whether t and F conclusions actually change.
Applying robust standard errors to a curved residuals-versus-fitted pattern
Fix: Robust SEs correct the spread, not the mean function. Fix the specification first, then adjust the covariance.
Treating independence as a property of the variables instead of the sampling design
Fix: Cluster at the level of assignment — school, store, patient, or time series — and let the number of clusters, not the number of rows, set the effective sample size.
Best Practices
- Fit the model, plot residuals versus fitted, and only then run formal tests
- Report which diagnostics you ran and which remedies you applied alongside the coefficient table
- State the cluster or time ordering used for robust standard errors so the result is reproducible
Key Takeaways
- Linearity, independence, normality, and equal variance each break something different; match the diagnostic to the consequence
- Normality only matters for exact small-sample inference — Gauss-Markov gives unbiased, efficient estimates without it
- Independence failures make standard errors wrong in a way no transformation of y can fix; use clustered or time-series covariance
- Most violations have a cheap modern remedy: HC3 for unequal variance, cluster-robust for grouped data, splines for curvature
Frequently Asked Questions
Which assumption can I safely ignore?
Normality, provided your sample runs into the hundreds and no extreme outliers dominate. The central limit theorem makes the t and F approximations reliable well before that point. Independence and equal variance deserve attention in every analysis, because they act directly on the standard errors that every p-value depends on.
Do I test assumptions on the residuals or the raw variables?
On the residuals. The assumption concerns the error term of the specific model you fitted, not the marginal distribution of or of any predictor. A strongly skewed response is perfectly fine if the residuals after fitting are well behaved.
Can I check assumptions with cross-validation instead?
No. Cross-validation measures predictive accuracy, which can be excellent under every kind of assumption violation. The LINE assumptions exist to justify confidence intervals, p-values, and coefficient interpretation — quantities cross-validation never evaluates.
Interview Questions
Q1: What is the LINE framework and why does each letter matter?
Linearity, Independence, Normality, Equal variance. Linearity protects the coefficient estimates from bias, independence protects the standard errors, equal variance protects the calibration of confidence intervals, and normality protects the exactness of small-sample t and F tests.
Q2: You see a funnel shape in the residuals-versus-fitted plot. What do you do?
The spread grows with the fitted value, so the homoscedastic standard errors are wrong. Report Huber-White HC3 standard errors, and consider a log transformation of the response if the variance scales with the mean.
Q3: Why is normality less important than the other three assumptions?
Gauss-Markov delivers unbiased, minimum-variance estimates under linearity, exogeneity, and spherical errors alone. Normality only makes the reference distributions exact; with moderate n the central limit theorem supplies the approximation.
Q4: How do you handle residuals from 300 students nested in 20 classrooms?
Rows are not independent, so ordinary standard errors are too small. Use cluster-robust standard errors at the classroom level or fit a mixed-effects model with random intercepts, and base inference on the number of clusters.