Complete Regression Diagnostics
Foundations of Statistics
A Comprehensive Checklist for Validating Regression Models
This toolkit covers every diagnostic from residual plots to influence measures, ensuring your regression model is trustworthy. Systematic diagnostics catch problems before they lead to erroneous conclusions.
- Research Validation â Meet publication standards with thorough assumption checking
- Business Analytics â Ensure predictive models are reliable before deployment
- Policy Evaluation â Confirm causal estimates are not artifacts of model misspecification
A model without diagnostics is a claim without evidence.
What You'll Learn
- 1Map each OLS assumption to the plot and formal test that checks it
- 2Compute leverage, studentised residuals and Cook's distance and apply their thresholds
- 3Separate outliers from influential points and decide what to do with each
- 4Produce a diagnostic report that a reviewer can audit line by line
Ordinary least squares comes with four assumptions about the errors and one about the design. When they hold, the coefficient estimates are the best linear unbiased estimators, the standard errors are correct, and the t and F distributions calibrate the p-values. When they break, the regression table still prints â which is precisely the danger.
The Four Assumptions and What Breaks Each One
| Assumption | Statement | Failure mode | First symptom |
|---|---|---|---|
| Linearity | The mean of y is linear in the predictors | Curvature, thresholds, interactions | Residuals curve against fitted values |
| Independence | Errors do not depend on each other | Time series, clusters, spatial data | Residuals autocorrelated over time |
| Homoscedasticity | Error variance is constant | Fan or trumpet shape | Interval width varies with fitted value |
| Normality of errors | Residuals are roughly normal | Skew, heavy tails, outliers | Q-Q plot bows or tapers |
A fifth condition, often listed separately, is that the design matrix has full rank and no near-collinear columns. Multicollinearity does not bias anything, but it inflates coefficient variance so that individual predictors become uninterpretable even when the model predicts well.
Each assumption has a matching visual, a matching formal test, and a matching remedy. Running all three â plot, test, action â is what separates a checked model from a fitted one.
The Standard Diagnostic Panel
Six plots cover nearly everything a reviewer will ask for.
- Residuals against fitted values. The workhorse. Look for three things at once: curvature (linearity), a funnel (heteroscedasticity), and isolated points far from the band (outliers). A horizontal red line at zero should be the centre of a structureless cloud.
- Normal Q-Q plot of the residuals. Points along the diagonal mean normality. Sagging at both ends means heavy tails; a single point deviating in one corner means one outlier. With more than about 50 observations the test is more sensitive than the eye, so read both.
- Scale-location plot. The square root of absolute standardised residuals against fitted values, with a smooth line. A rising line is the clearest evidence of increasing variance.
- Residuals against each predictor. Separately, and preferably as partial-residual plots, since a pattern hidden by another covariate only shows up here.
- Cook's distance. A stem plot with a reference line at . Points above the line can move the coefficients on their own.
- Residuals against leverage. The corners of this plot are where dangerous observations live: high leverage with a large residual is the signature of an influential point.
Outliers, Leverage and Influence Are Three Different Things
These terms get used interchangeably and should not be. An outlier is unusual in y. A high-leverage observation is unusual in x, meaning it sits far from the centre of the predictor space regardless of whether it fits the model. An influential observation is one whose removal would change the fitted model materially, which requires both.
Leverage comes from the hat matrix:
Each lies between 0 and 1, and the diagonals sum to p, the number of parameters including the intercept. The average leverage is therefore , and the conventional flag is above , with marking a more aggressive threshold.
Outlyingness is measured by studentised residuals. The internally studentised residual divides by an estimate of its own standard error that still includes the observation:
The externally studentised, or deleted, residual recomputes the model without observation i, giving a t-distributed quantity that detects outliers a fully included point would partly mask. Absolute values above 2 deserve inspection and values above 3 are almost always errors or genuinely unusual cases.
Influence combines the two through Cook's distance:
The numerator grows with a large residual; the denominator shrinks when leverage is high; both push the distance up together. The formula makes the geometry explicit: a point with no residual cannot be influential no matter how extreme its x, and a point at the centre of x cannot be influential no matter how extreme its y.
A Worked Influence Calculation
Take a dataset with observations, parameters, residual standard error , and a single observation with and .
- Leverage check: , and exceeds it, so the point is high leverage.
- Outlier check: , which is above 2, so it is also an outlier.
- Influence check: , well above both the flag and the conventional value of 1.
All three diagnostics fire, which is the worst case: this single row is steering the fit. The equivalent DFFITS value is , against a threshold of .
Contrast a point with but : its Cook's distance is , negligible. Extreme in x but perfectly on the line, it adds information rather than distorting the fit.
Formal Tests for Each Assumption
| Assumption | Visual check | Formal test | Reject when |
|---|---|---|---|
| Linearity | Curved residual trend | Ramsey RESET | p below 0.05 |
| Normality | Q-Q plot departures | Shapiro-Wilk, Jarque-Bera | p below 0.05 |
| Constant variance | Funnel shape | Breusch-Pagan, White | p below 0.05 |
| Independence | Residual ACF spikes | Durbin-Watson, Breusch-Godfrey | d far from 2 |
| No extreme influence | Cook's distance stems | D above 4 per n | Flagged row |
| Low multicollinearity | Predictor correlation matrix | Variance inflation factor | VIF above 5 |
The variance inflation factor for predictor j is , where comes from regressing that predictor on all the others. A VIF of 1 means no shared variance; a VIF of 10 means 90 percent of that predictor's variance is explained by its peers, leaving little independent information to estimate its coefficient. A VIF above 5 invites scrutiny and above 10 usually demands action, such as dropping a redundant variable, combining categories, or accepting that only the joint effect is identifiable.
Formal tests are corroborating evidence, not the verdict. With large n the Breusch-Pagan test rejects differences in spread too small to matter, and with small n it misses patterns visible in the plot. The plot tells you the shape of the problem, which is what determines the remedy.
Producing the Full Panel
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import stats
from statsmodels.stats.diagnostic import het_breuschpagan, acorr_breusch_godfrey
from statsmodels.stats.outliers_influence import variance_inflation_factor
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
n = 150
X1 = rng.uniform(1, 10, n)
X2 = rng.normal(5, 2, n)
y = 2 + 3*X1 - 1.5*X2 + rng.normal(0, 3, n)
# Inject a leverage outlier and a vertical outlier
X1 = np.append(X1, [2.0, 9.5]); X2 = np.append(X2, [5.0, 5.0])
y = np.append(y, [40.0, -5.0])
X = sm.add_constant(np.column_stack([X1, X2]))
model = sm.OLS(y, X).fit()
infl = model.get_influence()
r_std = infl.resid_studentized_internal
r_ext = infl.resid_studentized_external
lev = infl.hat_matrix_diag
cook = infl.cooks_distance[0]
p, n_obs = X.shape[1], len(y)
print(f"p = {p}, n = {n_obs}")
print(f"leverage flag 2p/n = {2*p/n_obs:.3f}: {(lev > 2*p/n_obs).sum()} points")
print(f"outlier flag |r| 3 : {(np.abs(r_std) > 3).sum()} points")
print(f"influence flag 4/n = {4/n_obs:.3f}: {(cook > 4/n_obs).sum()} points")
worst = np.argsort(cook)[-3:][::-1]
for i in worst:
print(f" row {i}: e={model.resid[i]:7.2f}, h={lev[i]:.3f}, "
f"r={r_std[i]:6.2f}, CookD={cook[i]:.3f}")
# Assumption tests
bp, bp_p, _, _ = het_breuschpagan(model.resid, model.model.exog)
bg, bg_p, _, _ = acorr_breusch_godfrey(model.resid, nlags=2)
jb = stats.jarque_bera(model.resid)
print(f"Breusch-Pagan p = {bp_p:.4f} Breusch-Godfrey p = {bg_p:.4f}")
print(f"Jarque-Bera p = {jb.pvalue:.4f}")
# Multicollinearity
vif = [variance_inflation_factor(model.model.exog, j) for j in range(p)]
for name, v in zip(["const", "X1", "X2"], vif):
print(f"VIF {name}: {v:.2f}")
fig, axes = plt.subplots(3, 2, figsize=(12, 12))
axes[0, 0].scatter(model.fittedvalues, model.resid, alpha=0.5)
axes[0, 0].axhline(0, color='red', ls='--')
axes[0, 0].set_title('Residuals vs fitted: linearity and variance')
stats.probplot(model.resid, dist='norm', plot=axes[0, 1])
axes[0, 1].set_title('Normal Q-Q')
axes[1, 0].scatter(model.fittedvalues, np.sqrt(np.abs(r_std)), alpha=0.5, color='coral')
axes[1, 0].set_title('Scale-location: horizontal band means constant variance')
axes[1, 1].stem(range(n_obs), cook, linefmt='gray', markerfmt='o')
axes[1, 1].axhline(4/n_obs, color='red', ls='--')
axes[1, 1].set_title("Cook's distance")
axes[2, 0].scatter(lev, r_std, alpha=0.5, color='orchid')
axes[2, 0].axhline(0, color='black', ls='--')
axes[2, 0].set_title('Residuals vs leverage')
sm.graphics.plot_partregress_grid(model, fig=fig, ax=axes[2, 1])
plt.tight_layout(); plt.show()
model <- lm(y ~ x1 + x2)
# The four standard plots, in one call
par(mfrow = c(2, 2)); plot(model); par(mfrow = c(1, 1))
# Formal tests
library(lmtest)
bptest(model) # Breusch-Pagan
bgtest(model, order = 2) # serial correlation
shapiro.test(residuals(model)) # normality
reset(model, power = 2:3) # functional form, package car
# Influence measures with thresholds
influence.measures(model)
car::influencePlot(model, id.method = "identify") # bubble size = Cook's D
car::avPlots(model) # partial regression plots
# Multicollinearity
car::vif(model)
# Remedies when diagnostics fail
library(sandwich)
coeftest(model, vcov = vcovHC(model, type = "HC3")) # heteroscedasticity
library(MASS)
rlm(model) # robust regression
â ī¸Never remove outliers without reason
From Finding to Remedy
| Diagnostic finding | Likely cause | Remedy |
|---|---|---|
| Curved residual trend | Wrong functional form, missing interaction | Add a quadratic term or an interaction, or transform the predictor |
| Funnel in residuals vs fitted | Non-constant variance | HC3 robust errors, weights, or log transform |
| Single point with Cook's D above 1 | Data error or a unique case | Verify the source, then report results with and without it |
| High leverage but small residual | An extreme but well-fitted x | Keep it; it increases precision rather than bias |
| Autocorrelated residuals | Omitted dynamics or trend | Newey-West errors, lagged terms, or a time-series model |
| VIF above 10 | Redundant predictors | Drop or combine variables, or report joint tests only |
| Q-Q plot tails sagging | Heavy tails or outliers | Robust or quantile regression as a sensitivity check |
Two remedies deserve emphasis. Adding a quadratic term fixes curvature at its source, whereas robust standard errors do nothing for a wrong mean function â they repair uncertainty around a biased specification. And robust regression, which down-weights large residuals through an M-estimator, changes the coefficients themselves; it is a modelling choice, not a repair to be applied automatically when OLS results are uncomfortable.
Reporting Checklist
A diagnostics section that satisfies a reviewer states, for each assumption, the evidence examined and the conclusion reached.
- Sample size and number of parameters, since every threshold depends on both.
- The residuals-versus-fitted plot and the Q-Q plot, shown rather than described.
- The Breusch-Pagan or White statistic with its p-value.
- A serial correlation test whenever the data are ordered in time.
- The count of observations exceeding leverage, , and Cook's distance.
- The maximum variance inflation factor, or the full VIF table for a small model.
- What was done about anything flagged, and whether the conclusions changed.
Sensitivity analysis is the strongest single addition: refit with robust standard errors, refit without each flagged observation, and report whether the substantive conclusion moves. A result that survives those variations is far more credible than one that depends on the exact specification chosen.
Common Mistakes
Treating a high-leverage point as an error
Fix: Leverage describes unusualness in x, not wrongness. If the residual is small the point is informative; only leverage combined with a large residual makes a point influential.
Removing rows because Cook's distance exceeds 4/n
Fix: 4/n flags rows for investigation, not deletion. Correct genuine errors, model genuine extremes, and always report the fit with and without them.
Running only formal tests and skipping the plots
Fix: Tests give a yes or no but not the shape of the problem, and shape determines the remedy. Show the panel and let the test corroborate it.
Reaching for robust standard errors when the mean function is wrong
Fix: HC3 repairs the covariance matrix around the model you fitted. Curvature or a missing interaction must be fixed by changing the model.
Best Practices
- Run the full panel before reading the coefficient table
- Report every threshold with its numeric value so a reader can audit the flags
- Provide a sensitivity analysis that refits the model under the obvious alternatives
- Keep diagnostics in the same order as the assumptions so nothing is skipped
Key Takeaways
- The six-plot panel â residuals vs fitted, Q-Q, scale-location, Cook's distance, residuals vs leverage, partial residuals â covers all four OLS assumptions
- Average leverage is p/n, so high leverage is h above 2p/n; Cook's D above 4/n flags influence, and above 1 marks a serious case
- Leverage plus a large residual equals influence; either one alone is usually harmless
- Formal tests corroborate the plots but never replace them, because the shape of the failure dictates the fix
- Sensitivity analysis â robust errors and refits without flagged rows â is the cheapest credibility a regression report can buy
Interview Questions
Q1: What is the difference between an outlier and an influential point?
An outlier is unusual in the response, measured by a studentised residual. A high-leverage point is unusual in the predictors, measured by its hat value. Influence, measured by Cook's distance, needs both: a large residual multiplied by high leverage, because either alone leaves the fit essentially unchanged.
Q2: State the formula and thresholds for Cook's distance.
D equals the squared residual times leverage, divided by p times the mean square error times one minus leverage squared. Above 4/n the point is flagged for investigation; above 1 it can move the coefficients substantially on its own.
Q3: A residuals-versus-fitted plot shows a clear curve. What do you do?
The mean function is misspecified, so change the model rather than the covariance: add a quadratic term, include a missing interaction, or transform the predictor. Robust standard errors will not repair a biased specification.
Q4: How do you interpret a VIF of 12?
Regressing that predictor on the others gives an R-squared of about 0.917, so only 8 percent of its variance is independent information. Its individual coefficient standard error is inflated by the square root of 12, making the coefficient unstable; consider dropping or combining predictors.
Frequently Asked Questions
How many observations do I need before these diagnostics are meaningful?
Every threshold scales with n, so small samples produce few flags and large samples produce many. Below about 30 observations the normality checks and Cook's distance have little power, and residual plots are hard to read; above a few hundred, formal tests will reject trivial departures and the plots carry more weight. Influence diagnostics remain useful at any size because their thresholds shrink automatically through and .
Does a failed diagnostic invalidate the model?
Not necessarily. The diagnostic identifies a specific failure, and each has a specific remedy â a transform for curvature, HC3 for variance, a lag term for correlation, robust regression for outliers. What invalidates a model is reporting inference that the diagnostics show to be unreliable while doing nothing about it.
What if the residuals are non-normal but the sample is large?
The coefficient estimates and standard errors barely depend on normality; only the small-sample t and F reference distributions do. With several hundred observations the central limit theorem makes the inference robust, and the practical response is to confirm the conclusion with a bootstrap interval rather than to abandon the model.
Should I diagnose the training set or the validation set?
Both, for different reasons. Training-set diagnostics reveal assumption failures that bias inference. Validation-set residuals reveal overfitting and distribution shift that hurt prediction. A model that passes in-sample diagnostics and fails out-of-sample needs complexity reduced, not assumptions repaired.