Skip to main content

Lesson 2 of 9

Residual Diagnostics: Homoscedasticity, Normality & Autocorrelation

A high R² does not prove that a linear regression model is valid. Residuals e = (y - y_hat) must be statistically tested to ensure model assumptions are satisfied. Diagnostic testing evaluates: (1) Zero Mean & Linearity (residuals symmetrically scattered around zero), (2) Homoscedasticity (constant variance, verified via Breusch-Pagan test), (3) Normality of Errors (Jarque-Bera test), and (4) Independence (Durbin-Watson test for autocorrelation).

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Complete Statistical Residual Diagnostic Suite

Complete Statistical Residual Diagnostic Suite
import numpy as np
import scipy.stats as stats
import statsmodels.api as sm
from statsmodels.stats.diagnostic import het_breuschpagan
from statsmodels.stats.stattools import durbin_watson

# Generate regression data with heteroscedasticity (variance increases with X)
np.random.seed(42)
n = 500
X = np.sort(np.random.uniform(10, 100, size=n))
# Residual variance expands proportionally to X (fan shape)
hetero_noise = np.random.normal(0, scale=0.15 * X, size=n)
y = 2.5 * X + 15.0 + hetero_noise

# Fit OLS model using statsmodels
X_with_const = sm.add_constant(X)
model = sm.OLS(y, X_with_const).fit()
residuals = model.resid
fitted_values = model.fittedvalues

# 1. BREUSCH-PAGAN TEST FOR HOMOSCEDASTICITY (Constant Variance)
# H0: Residual variance is constant (homoscedastic)
bp_test = het_breuschpagan(residuals, model.model.exog)
labels = ['LM Statistic', 'LM-Test p-value', 'F-Statistic', 'F-Test p-value']
print("=== BREUSCH-PAGAN TEST FOR HETEROSCEDASTICITY ===")
print(dict(zip(labels, [f"{v:.4e}" for v in bp_test])))
print(f"Result: {'Severe Heteroscedasticity Detected (Reject H0)' if bp_test[1] < 0.05 else 'Homoscedastic'}")

# 2. JARQUE-BERA TEST FOR NORMALITY OF RESIDUALS
# H0: Residuals are normally distributed (skew=0, kurtosis=0)
jb_stat, jb_p_val, skew, kurt = stats.jarque_bera(residuals)
print(f"\nJarque-Bera Normality Test p-value: {jb_p_val:.4e} (Skew={skew:.2f}, Kurtosis={kurt:.2f})")

# 3. DURBIN-WATSON TEST FOR AUTOCORRELATION
# DW ~ 2.0 indicates no serial correlation (range 0 to 4)
dw_stat = durbin_watson(residuals)
print(f"\nDurbin-Watson Statistic: {dw_stat:.4f} (~2.0 indicates uncorrelated independent errors)")

Pro Tip: Curing Heteroscedasticity with Huber-White Robust Errors

When heteroscedasticity is detected, coefficient point estimates remain unbiased, but their standard errors are distorted. In production, use Heteroscedasticity-Consistent (HC3) standard errors (`model.get_robustcov_results(cov_type='HC3')`) or log-transform the target variable `y`.

Diagram
Loading diagram…

MlResidualAnalysis Visual Representation

Hands-On Challenge: Build a Residual Diagnostic Plotter

Write a function that outputs a 2x2 diagnostic grid: (1) Residuals vs Fitted values, (2) Normal Q-Q plot, (3) Scale-Location plot (sqrt of standardized residuals vs fitted), and (4) Residuals vs Leverage plot (highlighting Cook's distance > 0.5).

Quick Quiz & Key Concept Checks

Common Pitfall: Ignoring High-Leverage Outliers (Cook's Distance)

A single data point with extreme feature values (high leverage) can tilt an OLS regression line by 30+ degrees even if its residual is small. Always compute Cook's distance to identify and audit influential observations.

Topics in This Module

0/9 done