Regression diagnostics are the checks you run after fitting a linear model to find out whether its numbers can be trusted. A high R-squared does not tell you that. In this tutorial we fit a fuel-economy model on 392 real cars and look at residual patterns, multicollinearity (VIF), unequal variance, influential points and a validation trap that cut the apparent R-squared from 0.70 to 0.33.
Versions: pandas 3.0.5, statsmodels 0.15.0, scikit-learn 1.9.1, SciPy 1.18.1. The data is seaborn’s mpg.csv (UCI Auto MPG, 398 cars from 1970 to 1982); six rows have no horsepower and are dropped, which leaves 392. If you need the model basics first, start with exploratory data analysis in Python.
Step 1: fit the model
import pandas as pd, numpy as np, statsmodels.api as sm, statsmodels.formula.api as smf
d = pd.read_csv("mpg.csv").dropna(subset=["horsepower"]).reset_index(drop=True)
m = smf.ols("mpg ~ weight + horsepower", d).fit()
print(d.shape, m.params.round(5).to_dict(), round(m.rsquared, 3))Output:
(392, 9)
{'Intercept': 45.64021, 'weight': -0.00579, 'horsepower': -0.0473} 0.706Each extra 1,000 lbs of weight costs about 5.8 mpg with horsepower held fixed, and R-squared is 0.706. Looks fine. Now test the assumptions.
Step 2: look at residuals by fitted value
A well-behaved model has residuals centred on zero with the same spread everywhere. Group the residuals by fitted-value quintile:
d["fit"], d["res"] = m.fittedvalues, m.resid
print(d.groupby(pd.qcut(d.fit, 5), observed=True)["res"].agg(["mean", "std"]).round(2))Output:
mean std
fit
(6.308999999999999, 17.018] 1.06 2.35
(17.018, 23.214] -1.53 3.01
(23.214, 26.414] -0.92 4.15
(26.414, 29.587] -0.91 4.51
(29.587, 33.626] 2.25 5.28Two problems show up at once. The mean residual is positive at both ends and negative in the middle, a U shape that signals curvature the straight line misses. The spread also grows from 2.35 to 5.28 as predicted mpg rises. Those are the two classic failures: wrong functional form and heteroscedasticity.

Step 3: test for unequal variance and non-normal residuals
from statsmodels.stats.diagnostic import het_breuschpagan
from scipy import stats
X = sm.add_constant(d[["weight", "horsepower"]])
lm, lm_p, f, f_p = het_breuschpagan(m.resid, X)
print("Breusch-Pagan LM", round(lm, 2), "p", lm_p)
print("skew", round(stats.skew(m.resid), 3), stats.shapiro(m.resid))Output:
Breusch-Pagan LM 25.23 p 3.31433059792957e-06
skew 0.683 ShapiroResult(statistic=0.9732966504896515, pvalue=1.3052289984370923e-06)Both tests reject (p about 3e-6 and 1e-6). With 392 rows even small violations get flagged, so use the tests together with the pattern in step 2, not instead of it.
Step 4: fix the form
Adding a squared horsepower term addresses the curvature, and modelling the log of mpg addresses the growing spread:
m2 = smf.ols("mpg ~ weight + horsepower + I(horsepower**2)", d).fit()
print(round(m2.rsquared, 3), round(m2.rsquared_adj, 3), "vs", round(m.rsquared_adj, 3))
m3 = smf.ols("np.log(mpg) ~ weight + horsepower", d).fit()
X3 = sm.add_constant(d[["weight", "horsepower"]])
print("log model R2", round(m3.rsquared, 3),
"BP p", round(het_breuschpagan(m3.resid, X3)[1], 2),
"Shapiro p", round(stats.shapiro(m3.resid).pvalue, 3))Output:
0.74 0.738 vs 0.705
log model R2 0.788 BP p 0.15 Shapiro p 0.472The squared term lifts adjusted R-squared from 0.705 to 0.738. The log model passes both tests (Breusch-Pagan p = 0.15, Shapiro p = 0.472). Its R-squared of 0.788 is on the log scale, so it cannot be compared directly with 0.706. If you prefer to keep the original model, heteroscedasticity-robust standard errors (HC3) are a cheap fix; ours barely moved, for example horsepower 0.01109 classic versus 0.01161 HC3.
Step 5: multicollinearity and influence
Weight and horsepower correlate at 0.865. The variance inflation factor (VIF) says how much that inflates the uncertainty of each coefficient:
from statsmodels.stats.outliers_influence import variance_inflation_factor
print([round(variance_inflation_factor(X.values, i), 2) for i in (1, 2)])
inf = m.get_influence()
d["cook"] = inf.cooks_distance[0]
print("max Cook", d.cook.max().round(3), "n > 4/n:", (d.cook > 4/len(d)).sum())
top = d.sort_values("cook", ascending=False).index[:5]
m4 = smf.ols("mpg ~ weight + horsepower", d.drop(top)).fit()
print(m.params.round(4).to_dict()); print(m4.params.round(4).to_dict())Output:
[3.96, 3.96]
max Cook 0.037 n > 4/n: 24
{'Intercept': 45.6402, 'weight': -0.0058, 'horsepower': -0.0473}
{'Intercept': 45.2543, 'weight': -0.0059, 'horsepower': -0.0418}A VIF near 4 is acceptable by the usual rule of thumb (worry above 5 to 10). When we added acceleration as a third predictor, VIFs rose to 5.2 (weight) and 8.2 (horsepower), and acceleration’s coefficient was nowhere near significant (p = 0.987). No point has Cook’s distance above 1 (the largest is 0.037), so none dominates, but 24 points exceed the 4/n rule of thumb. Dropping the five most influential cars changed the horsepower coefficient from -0.0473 to -0.0418, about 12%, while weight barely moved. The most influential rows are the VW Dasher and Rabbit diesels and the Mazda GLC (all 43 to 47 mpg, which the model underpredicts) and the Pontiac Grand Prix, a heavy 230 hp car.
Step 6: the validation trap
The file is sorted by model year. Cross-validation without shuffling puts the earliest cars in one fold and the latest in another, so each fold is a different era:
from sklearn.model_selection import cross_val_score, KFold
from sklearn.linear_model import LinearRegression
cols = ["weight", "horsepower"]
for name, cv in {"unshuffled": KFold(5), "shuffled": KFold(5, shuffle=True, random_state=0)}.items():
print(name, cross_val_score(LinearRegression(), d[cols], d.mpg, cv=cv, scoring="r2").mean().round(3))Output:
unshuffled 0.332
shuffled 0.698Same model, same data: 0.332 versus 0.698. Neither number is “wrong”, but they measure different things. The unshuffled score is closer to predicting a new era of cars from older ones, where the model does badly; the shuffled score matches the in-sample 0.706. Always decide which question you are asking, and read cross-validation in Python and train test split in Python before trusting a single number.
Checklist
Plot residuals against fitted values, test for unequal variance, check VIF, find influential points with Cook’s distance, and refit without them to see what moves. See the statsmodels diagnostics reference for more tests, and logistic regression in Python for the classification counterpart.
Frequently asked questions
What are regression diagnostics?
Checks on residuals, multicollinearity and influential observations that tell you whether a fitted regression meets its assumptions.
Is a high R-squared enough?
No. Our model had R-squared 0.706 with curved, widening residuals.
What VIF is too high?
Common rules of thumb flag values above 5 or 10. Here weight and horsepower had 3.96 each in the two-predictor model.
Should I delete high-Cook’s-distance points?
Not automatically. Check whether they are errors, refit without them, and report both results if the conclusions change.
