🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Residual Analysis

Regression AnalysisDiagnosticsđŸŸĸ Free Lesson

title: "Residual Analysis — Diagnosing Regression Problems"

module: "Regression Analysis"

topic: "Linear Regression"

slug: "residual-analysis"

description: "Master residual analysis for linear regression: types of residuals, diagnostic plots, influential points (Cook's distance), leverage, and Python implementation."

seoTitle: "Residual Analysis — Diagnosing Regression Problems | LearnWhole Statistics"

seoDescription: "Master residual analysis for linear regression: types of residuals, diagnostic plots, influential points (Cook's distance), leverage, and Python implementation."


Residual Analysis

Regression Analysis

Diagnosing What's Wrong With Your Regression

Residual analysis reveals whether your model assumptions hold, identifies influential outliers, and detects non-linearity. It's the diagnostic toolkit that separates trustworthy models from misleading ones.

  • Clinical Studies — Detect influential patients that distort treatment effect estimates

  • Financial Forecasting — Identify time periods where models systematically fail

  • Manufacturing — Spot measurement errors and anomalous production runs

What remains after fitting the model tells you as much as what the model predicts.


Residuals are the differences between observed and predicted values:

Analyzing residuals reveals whether regression assumptions are met and identifies influential observations.

python

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import statsmodels.api as sm

from scipy import stats



np.random.seed(42)



# Build a regression model with potential issues

n = 80

X = np.random.uniform(1, 10, n)

y = 2 + 3*X + np.random.normal(0, 2, n)



# Add some outliers and influential points

X = np.append(X, [1.5, 9.5])

y = np.append(y, [25, 10])  # outliers



X_dm = sm.add_constant(X)

model = sm.OLS(y, X_dm).fit()



# Types of residuals

raw_resid = model.resid

student_resid = model.outlier_test()['student_resid']

influence = model.get_influence()

leverage = influence.hat_matrix_diag

cooks_d = influence.cooks_distance[0]

standardized_resid = influence.resid_studentized_internal



print("Influence Diagnostics:")

print(f"Max leverage: {leverage.max():.4f} (threshold: {2*(2/len(X)):.4f})")

print(f"Max Cook's D: {cooks_d.max():.4f} (threshold: 4/n = {4/len(X):.4f})")



high_lev = leverage > 2*(2/len(X))

high_cook = cooks_d > 4/len(X)

print(f"High leverage points: {high_lev.sum()}")

print(f"High Cook's D points: {high_cook.sum()}")



# 4-panel diagnostic plot

fig, axes = plt.subplots(2, 2, figsize=(12, 8))



# 1. Residuals vs Fitted

axes[0,0].scatter(model.fittedvalues, raw_resid, alpha=0.6, color='steelblue')

axes[0,0].axhline(0, color='red', linestyle='--', linewidth=2)

axes[0,0].set_xlabel('Fitted Values')

axes[0,0].set_ylabel('Residuals')

axes[0,0].set_title('Residuals vs Fitted')



# 2. Q-Q Plot

stats.probplot(raw_resid, dist='norm', plot=axes[0,1])

axes[0,1].set_title('Normal Q-Q Plot')



# 3. Scale-Location

axes[1,0].scatter(model.fittedvalues, np.sqrt(np.abs(standardized_resid)), alpha=0.6, color='coral')

axes[1,0].set_xlabel('Fitted Values')

axes[1,0].set_ylabel('v|Standardized Residuals|')

axes[1,0].set_title('Scale-Location (Homoscedasticity)')



# 4. Residuals vs Leverage (Cook's D)

axes[1,1].scatter(leverage, standardized_resid, alpha=0.6, color='orchid')

axes[1,1].axhline(0, color='black', linestyle='--')

axes[1,1].axvline(2*(2/len(X)), color='red', linestyle=':', label='Leverage threshold')

for i, (lev, res, cd) in enumerate(zip(leverage, standardized_resid, cooks_d)):

    if cd > 4/len(X):

        axes[1,1].annotate(f'Obs {i}', (lev, res), fontsize=8)

axes[1,1].set_xlabel('Leverage')

axes[1,1].set_ylabel('Standardized Residuals')

axes[1,1].set_title("Residuals vs Leverage (Cook's D)")

axes[1,1].legend()



plt.tight_layout()

plt.savefig('residual_analysis.png', dpi=150)

plt.show()



# Outlier test (Bonferroni-corrected)

print("\nOutlier Test (Bonferroni-corrected):")

outlier_results = model.outlier_test()

significant_outliers = outlier_results[outlier_results['bonf(p)'] < 0.05]

print(f"Significant outliers: {len(significant_outliers)}")

Key Diagnostics

| Measure | Formula | Threshold | Indicates |

|---------|---------|-----------|----------|

| Leverage h?? | diag(H) | greater than 2p/n | Unusual X value |

| Standardized residual | e?/sv(1-h??) | |r| greater than 3 | Outlier in Y |

| Cook's Distance | D? | greater than 4/n | Influential observation |

| DFFITS | Scaled leverage | greater than 2v(p/n) | Influential in fitted value |


Key Takeaways


Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Statistics Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement