Statistical modeling with Python · Lesson 10 of 16
Checking a regression: residuals and VIF
Check a linear regression before you trust it: residuals and the residual plot, influential points with Cook's distance, and multicollinearity with VIF.
A regression always returns numbers, even when its assumptions are broken. Before you believe the p-values, spend two minutes on diagnostics. The main tool is the residual: the actual value minus the model's prediction, what the model got wrong for each row.
Residuals
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.ols("score ~ hours + absences + C(prep) + C(course)", data=df).fit()
res = model.resid
print(f"mean of residuals: {abs(res.mean()):.3f}")
print(f"residual sd: {res.std():.2f}")
check = pd.DataFrame({"score": df["score"], "predicted": model.fittedvalues.round(1),
"residual": res.round(1)})
print(check.head())mean of residuals: 0.000 residual sd: 12.10 score predicted residual 0 33 25.7 7.3 1 13 24.0 -11.0 2 99 91.3 7.7 3 18 18.5 -0.5 4 45 61.1 -16.1
With an intercept in the model, residuals always average 0.
What you want: residuals with no pattern. They should be scattered evenly around 0, whatever the predicted value. The quickest check is the residual plot: predicted values along the bottom, residuals up the side.
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.ols("score ~ hours + absences + C(prep) + C(course)", data=df).fit()
import matplotlib.pyplot as plt
print(f"largest miss: {model.resid.abs().max():.1f} points")
plt.scatter(model.fittedvalues, model.resid, color="steelblue", alpha=0.6)
plt.axhline(0, color="crimson")
plt.title("Residuals against predicted score")
plt.xlabel("Predicted score")
plt.ylabel("Residual")
plt.show()largest miss: 29.3 points

- A random band around 0: good, as here.
- A curve (residuals positive at both ends, negative in the middle): the link is not a straight line. Try a transformed predictor, such as
I(hours ** 2)ornp.log(hours). - A funnel (spread grows with the prediction): the variance is not constant (heteroscedasticity). The coefficients are still fine, but the standard errors are not;
fit(cov_type="HC3")gives robust ones.
Two formal tests back up the picture: Breusch–Pagan for a funnel (small p = trouble) and Shapiro–Wilk for whether the residuals look normal. With 100 rows, normality matters less than the other checks: the p-values of a regression are fairly robust to it.
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.ols("score ~ hours + absences + C(prep) + C(course)", data=df).fit()
from scipy import stats
from statsmodels.stats.diagnostic import het_breuschpagan
bp = het_breuschpagan(model.resid, model.model.exog)
print(f"Breusch-Pagan p = {bp[1]:.3f}")
print(f"Shapiro-Wilk p = {stats.shapiro(model.resid).pvalue:.3f}")Breusch-Pagan p = 0.301 Shapiro-Wilk p = 0.214
Influential points: Cook's distance
Some rows pull the line towards them more than others. Cook's distance measures how much all the predictions would change if you dropped that one row. A common rule of thumb flags rows above 4 / n. Flagged rows are worth a look (a typo? a special case?), not automatic deletion.
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.ols("score ~ hours + absences + C(prep) + C(course)", data=df).fit()
infl = model.get_influence()
cooks = pd.Series(infl.cooks_distance[0], index=df.index)
limit = 4 / len(df)
print(f"rule of thumb: {limit:.3f}")
print(f"rows above it: {int((cooks > limit).sum())}")
top = cooks.sort_values(ascending=False).head(3).index
print(df.loc[top, ["hours", "absences", "prep", "score"]].assign(cooks=cooks[top].round(3)))rule of thumb: 0.040
rows above it: 3
hours absences prep score cooks
11 14.0 2 yes 71 0.087
44 3.3 4 yes 25 0.049
72 5.8 7 no 21 0.041Multicollinearity: VIF
When two predictors carry almost the same information (a flat's area and its number of rooms), the model cannot tell their effects apart: coefficients jump around and their standard errors balloon. The variance inflation factor (VIF) measures it for each predictor: 1 means no overlap; as a rule of thumb (not a strict cut-off), values above about 5 to 10 are a warning.
import pandas as pd
import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor
flats = pd.DataFrame({
"area": [45, 52, 60, 68, 75, 81, 90, 98, 105, 120, 58, 72],
"rooms": [1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 2, 3],
"floor": [2, 5, 1, 3, 4, 0, 2, 6, 1, 3, 4, 2],
"rent": [640, 720, 790, 880, 950, 990, 1100, 1180, 1220, 1400, 760, 930],
})
X = sm.add_constant(flats[["area", "rooms", "floor"]])
for i, name in enumerate(X.columns):
if name != "const":
print(f"{name:<6} VIF {variance_inflation_factor(X.values, i):.1f}")area VIF 18.7 rooms VIF 18.7 floor VIF 1.1
Compute VIF on the predictors with the constant included, and skip the constant's own value.
area and rooms have VIFs far above 10: they overlap heavily. floor is barely related to either. The fix is to keep only one of the overlapping pair, or combine them (area per room). Note that VIF does not look at the outcome at all, only at the predictors.
✎ Exercise
For the flats, fit rent ~ area + floor with smf.ols (rooms dropped) and print the VIFs of area and floor (1 decimal) and the coefficients (2 decimals).
Hint: Build X = sm.add_constant(flats[["area", "floor"]]) and loop over its columns as in the example.
import pandas as pd
import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor
flats = pd.DataFrame({
"area": [45, 52, 60, 68, 75, 81, 90, 98, 105, 120, 58, 72],
"rooms": [1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 2, 3],
"floor": [2, 5, 1, 3, 4, 0, 2, 6, 1, 3, 4, 2],
"rent": [640, 720, 790, 880, 950, 990, 1100, 1180, 1220, 1400, 760, 930],
})
import statsmodels.formula.api as smf
# your code here
Expected output:
area VIF 1.0 floor VIF 1.0 Intercept 185.96 area 9.99 floor 2.92 dtype: float64
Show a solution
import pandas as pd
import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor
flats = pd.DataFrame({
"area": [45, 52, 60, 68, 75, 81, 90, 98, 105, 120, 58, 72],
"rooms": [1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 2, 3],
"floor": [2, 5, 1, 3, 4, 0, 2, 6, 1, 3, 4, 2],
"rent": [640, 720, 790, 880, 950, 990, 1100, 1180, 1220, 1400, 760, 930],
})
import statsmodels.formula.api as smf
X = sm.add_constant(flats[["area", "floor"]])
for i, name in enumerate(X.columns):
if name != "const":
print(f"{name:<6} VIF {variance_inflation_factor(X.values, i):.1f}")
model = smf.ols("rent ~ area + floor", data=flats).fit()
print(model.params.round(2))area VIF 1.0 floor VIF 1.0 Intercept 185.96 area 9.99 floor 2.92 dtype: float64
Check yourself
1. The residual plot shows a funnel: small residuals on the left, large on the right. What is the problem?
Growing spread means non-constant variance; use robust standard errors (cov_type="HC3") or transform the outcome.
2. A row has a large Cook's distance. What should you do first?
Influential points deserve a check, not an automatic deletion.
3. Two predictors have VIFs of 25 and 24. What does that mean?
VIF only looks at the predictors: a high VIF means a predictor is largely explained by the others.