How to Generate Diagnostic Plots with statsmodels for Regression Models

How to Generate Diagnostic Plots with statsmodels for Regression Models
Image by Editor

Introduction to Diagnostic Plots

Regression analysis helps us understand the relationship between variables. However, after fitting a model, we need to check if it meets key assumptions. Diagnostic plots help us assess these assumptions visually. These plots check for patterns in residuals, normality, and influential points.

In this article, we will learn how to create diagnostic plots using the statsmodels library in Python.

Diagnostic plots are used to evaluate the validity of regression models by checking assumptions such as:

  • Linearity: The relationship between the predictors and the dependent variable should be linear
  • Homoscedasticity: The variance of residuals should be constant across all levels of the independent variables
  • Normality of Residuals: The residuals should follow a normal distribution for reliable hypothesis testing
  • Independence of Errors: There should be no correlation between residuals

Setting Up the Environment

First, ensure you have the necessary libraries installed. You can install them using:

pip install statsmodels matplotlib seaborn numpy pandas

We will use NumPy, pandas, statsmodels, Matplotlib, and Seaborn:

import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
import seaborn as sns

Fitting a Regression Model

We will use the built-in dataset mtcars (Motor Trend Car Road Tests) to fit a regression model.

data = sm.datasets.get_rdataset("mtcars", "datasets").data
X = data[["hp", "wt"]]  # Independent variables (horsepower and weight)
y = data["mpg"]         # Dependent variable (miles per gallon)
X = sm.add_constant(X)  # Add constant term for intercept

model = sm.OLS(y, X).fit()  # Fit the regression model
print(model.summary())

Explanation:

  • sm.add_constant(X) adds an intercept term to the model
  • sm.OLS(y, X).fit() fits an ordinary least squares (OLS) regression model

Regression Model

Generating Diagnostic Plots

Residual Plot

This plot checks if residuals have constant variance (homoscedasticity) and whether a linear relationship is appropriate. Ideally, residuals should be randomly scattered around the horizontal axis without a clear pattern. If they form a funnel shape or any structure, it may indicate changing variance (heteroscedasticity) or a model misspecification.

from statsmodels.nonparametric.smoothers_lowess import lowess

fitted_values = model.fittedvalues
residuals = model.resid

plt.figure(figsize=(8, 5))
sns.scatterplot(x=fitted_values, y=residuals, s=60, edgecolor=None)
# LOWESS smooth to highlight any trend in residuals
smooth = lowess(residuals, fitted_values, frac=0.6)
plt.plot(smooth[:, 0], smooth[:, 1], color='red', lw=2)
plt.axhline(y=0, color='black', linestyle='--')
plt.xlabel("Fitted Values")
plt.ylabel("Residuals")
plt.title("Residuals vs. Fitted")
plt.show()

Explanation:

  • Uses sns.scatterplot() to visualize residuals against fitted values
  • Adds a LOWESS smooth via lowess() to reveal any systematic trend

Residual Plot

Q-Q Plot

A Q-Q plot checks if residuals follow a normal distribution. If they are normal, the points will align with the reference line. Large deviations from the line suggest non-normality, which may indicate skewness or outliers.

sm.qqplot(residuals, line='45', fit=True)
plt.title("Q–Q Plot of Residuals")
plt.show()

Explanation:

  • Uses sm.qqplot() to create a Q–Q plot
  • line=’45’ adds a 45-degree reference line—if residuals are normal, points should align closely to this line

Q-Q Plot

Scale–Location Plot

The scale–location plot checks if residual variance is constant (homoscedasticity). It plots the square root of the absolute standardized residuals against fitted values. Ideally, the points should be randomly scattered. A visible pattern suggests changing variance and possible model issues.

influence = model.get_influence()
standardized_residuals = influence.resid_studentized_internal
sqrt_abs_std_resid = np.sqrt(np.abs(standardized_residuals))

plt.figure(figsize=(8, 5))
sns.scatterplot(x=fitted_values, y=sqrt_abs_std_resid, s=60, edgecolor=None)
plt.axhline(y=np.mean(sqrt_abs_std_resid), color='red', linestyle='--')
plt.xlabel("Fitted Values")
plt.ylabel("Sqrt(|Standardized Residuals|)")
plt.title("Scale–Location")
plt.show()

Explanation:

  • Computes standardized (studentized) residuals and plots fitted values vs. sqrt(|standardized residuals|)

Scale-Location Plot

Residuals vs. Leverage Plot

The residuals vs. leverage plot identifies influential points—observations that have a disproportionate impact on the model fit. Influential points often have extreme leverage (predictor values far from the mean) and/or large residuals. If present, they may need further investigation.

fig, ax = plt.subplots(figsize=(8, 6))
sm.graphics.influence_plot(model, ax=ax, criterion="cooks")
plt.title("Residuals vs. Leverage (Cook's Distance)")
plt.show()
  • Uses sm.graphics.influence_plot() to detect influential data points
  • Cook’s distance (criterion=”cooks”) highlights observations with strong influence on model predictions

Wrapping Up

Diagnostic plots help check whether a regression model meets key assumptions. Using statsmodels, we can create plots to analyze residuals, normality, variance, and influential points. These plots help surface problems early and improve model accuracy. By following these steps, you can check and refine your regression model using Python.

Leave a Reply

Your email address will not be published. Required fields are marked *