GNGiseldo Neo and Alana NeoBooks
Linear Regression with Python10 / 19

Model Diagnostics

Proper diagnostics of linear regression models are essential to ensure the validity of inferences and predictions. This chapter explores techniques for evaluating model adequacy and identifying potential problems.

9.1 Residuals and Residual Analysis

Residuals are the difference between the observed values and the values predicted by the model. Residual analysis is a powerful tool for verifying whether the assumptions of linear regression have been met.

9.1.1 Types of Residual Analysis

Residuals vs. Fitted Values Plots

  • Purpose: To assess homoscedasticity and linearity.

  • Interpretation: Residuals should be randomly scattered around zero with no apparent patterns. Systematic patterns indicate issues with model specification.

import matplotlib.pyplot as plt

# Residual plot
plt.scatter(y_pred, y_test - y_pred)
plt.hlines(y=0, xmin=min(y_pred), xmax=max(y_pred), colors='red')
plt.xlabel('Fitted Values')
plt.ylabel('Residuals')
plt.show()

Histograms of Residuals

  • Purpose: To assess the normality of the residuals.

  • Interpretation: Residuals should follow an approximately normal distribution. Significant deviations may indicate violations of normality.

plt.hist(y_test - y_pred, bins=20, edgecolor='black')
plt.xlabel('Residuals')
plt.ylabel('Frequency')
plt.show()

Q-Q (Quantile-Quantile) Plots

  • Purpose: To compare the distribution of the residuals against a normal distribution.

  • Interpretation: If the residuals are normally distributed, the points should lie along the diagonal line.

import scipy.stats as stats

stats.probplot(y_test - y_pred, dist="norm", plot=plt)
plt.show()

9.2 Outlier Detection

Outliers can distort model estimates and affect the interpretation of results. Identifying and addressing them is crucial for the validity of the model.

9.2.1 Methods for Detecting Outliers

Visual Analysis

Scatter plots can help identify outliers visually.

Cook’s Distance

  • Purpose: To measure the influence of each data point on the estimation of the regression coefficients.

  • Interpretation: High Cook’s distance values indicate influential observations.

import statsmodels.api as sm

# Calculating Cook's distance
model = sm.OLS(y_train, sm.add_constant(x_train)).fit()
influence = model.get_influence()
cooks_d = influence.cooks_distance[0]

plt.stem(np.arange(len(cooks_d)), cooks_d, markerfmt=",", use_line_collection=True)
plt.xlabel('Observation')
plt.ylabel("Cook's Distance")
plt.show()

Leverage

  • Purpose: To measure the influence of a data point based on its position in the space of the independent variables.

  • Interpretation: High-leverage points have the potential to significantly influence the regression line.

leverage = influence.hat_matrix_diag
plt.stem(np.arange(len(leverage)), leverage, markerfmt=",", use_line_collection=True)
plt.xlabel('Observation')
plt.ylabel('Leverage')
plt.show()

9.3 Significance Testing for Coefficients

Statistical significance tests for the coefficients help determine whether the independent variables have a significant impact on the dependent variable.

9.3.1 t-Test for Coefficients

  • Purpose: To test the null hypothesis that a coefficient is equal to zero (no effect).

  • Interpretation: p-values smaller than a chosen significance level (typically 0.05) indicate that the coefficient is significantly different from zero.

# Model summary
print(model.summary())

9.3.2 Confidence Intervals

  • Purpose: To provide a range of values within which the true coefficient is likely to lie.

  • Interpretation: If the confidence interval does not include zero, the coefficient is considered statistically significant.

# Confidence intervals for the coefficients
conf_intervals = model.conf_int(alpha=0.05)
print(conf_intervals)