🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Complete Regression Diagnostics Toolkit

Foundations of StatisticsRegression AnalysisđŸŸĸ Free Lesson

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

AssumptionStatementFailure modeFirst symptom
LinearityThe mean of y is linear in the predictorsCurvature, thresholds, interactionsResiduals curve against fitted values
IndependenceErrors do not depend on each otherTime series, clusters, spatial dataResiduals autocorrelated over time
HomoscedasticityError variance is constantFan or trumpet shapeInterval width varies with fitted value
Normality of errorsResiduals are roughly normalSkew, heavy tails, outliersQ-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.

  1. 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.
  2. 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.
  3. 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.
  4. Residuals against each predictor. Separately, and preferably as partial-residual plots, since a pattern hidden by another covariate only shows up here.
  5. Cook's distance. A stem plot with a reference line at . Points above the line can move the coefficients on their own.
  6. 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

AssumptionVisual checkFormal testReject when
LinearityCurved residual trendRamsey RESETp below 0.05
NormalityQ-Q plot departuresShapiro-Wilk, Jarque-Berap below 0.05
Constant varianceFunnel shapeBreusch-Pagan, Whitep below 0.05
IndependenceResidual ACF spikesDurbin-Watson, Breusch-Godfreyd far from 2
No extreme influenceCook's distance stemsD above 4 per nFlagged row
Low multicollinearityPredictor correlation matrixVariance inflation factorVIF 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

python
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

An observation can be the most informative row in the dataset. Removing points because they disagree with the model is circular reasoning that shrinks standard errors and manufactures significance. Investigate first: a data error should be corrected, a genuine extreme case should be modelled with robust regression or reported as a sensitivity analysis, and the decision must be documented.

From Finding to Remedy

Diagnostic findingLikely causeRemedy
Curved residual trendWrong functional form, missing interactionAdd a quadratic term or an interaction, or transform the predictor
Funnel in residuals vs fittedNon-constant varianceHC3 robust errors, weights, or log transform
Single point with Cook's D above 1Data error or a unique caseVerify the source, then report results with and without it
High leverage but small residualAn extreme but well-fitted xKeep it; it increases precision rather than bias
Autocorrelated residualsOmitted dynamics or trendNewey-West errors, lagged terms, or a time-series model
VIF above 10Redundant predictorsDrop or combine variables, or report joint tests only
Q-Q plot tails saggingHeavy tails or outliersRobust 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.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Statistics Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement