← Machine Learning

Residual Diagnostics in Linear Regression

Residuals

Recall the linear regression model:

Yi=β0+β1xi1+β1xi2+⋯+βp−1xi,p−1+ϵi,i=1,2,…,n(1)Y_i = \beta_0 + \beta_1 x_{i1} + \beta_1 x_{i2} + \cdots + \beta_{p-1} x_{i,p-1} + \epsilon_i, \quad i = 1, 2, \ldots, n \tag{1}

with

ϵi∼iidN(0,σ2).\epsilon_i \overset{\text{iid}}{\sim} N(0, \sigma^2).
  • What major assumptions are we making?

    • The response function E[Y]E[Y] is linear.
    • The errors ϵ\epsilon are normally distributed.
    • The errors ϵ\epsilon have constant variance (Homoscedasticity).
    • The errors ϵ\epsilon are independent and identically distributed.
  • Other considerations

    • Does the model fit all but one or a few outlying observations?
    • Have one or several important predictor variables been omitted from the model?

Notice the true errors can be expressed as:

ϵi=Yi−E[Yi]=Yi−(β0+β1xi),i=1,2,…,n.\epsilon_i = Y_i - E[Y_i] = Y_i - (\beta_0 + \beta_1 x_i), \quad i = 1, 2, \ldots, n.

Note: The errors are unobservable.
Note: The best guess of the true errors are the residuals ϵ^i=ei\quad \hat{\epsilon}_i = e_i, i=1,…,n\quad i = 1, \ldots, n.

Definition
Then the ith residual is defined by:

ei=Yi−Y^i,i=1,2,…,n.(2)e_i = Y_i - \hat{Y}_i, \quad i = 1, 2, \ldots, n. \tag{2}

Analyzing the residuals provides insight on whether or not the regression assumptions are satisfied.

  • Sample mean and sample variance of the residuals
eˉ=1n∑i=1nei=0andσ^2=1n−p∑i=1nei2=MSE\bar{e} = \frac{1}{n} \sum_{i=1}^{n} e_i = 0 \quad\text{and}\quad \hat{\sigma}^2 = \frac{1}{n - p} \sum_{i=1}^{n} e_i^2 = MSE
  • Although the errors ϵi\epsilon_i are independent random variables, the residuals are not independent random variables.
    This can be seen by the following two properties:
∑i=1nei=0and∑i=1nxikei=0,k=1,2,…,p−1.\sum_{i=1}^{n} e_i = 0 \quad \text{and} \quad \sum_{i=1}^{n} x_{ik} e_i = 0, \quad k = 1, 2, \ldots, p - 1.

Semistudentized residuals

Definition
Let eie_i be the residual defined in (2)(2) and let MSEMSE be the mean square error.
Then the ith semistudentized residual is defined by:

ei∗=ei−eˉσ^=eiσ^,i=1,2,…,n.(3)e_i^* = \frac{e_i - \bar{e}}{\hat{\sigma}} = \frac{e_i}{\hat{\sigma}}, \quad i = 1, 2, \ldots, n. \tag{3}

Studentized residuals

Recall that the residual vector can be expressed as

e=(In−H)Y\mathbf{e} = (\mathbf{I}_n - \mathbf{H})\mathbf{Y}

where the hat matrix H\mathbf{H} is defined by

H=X(XTX)−1XT.\mathbf{H} = \mathbf{X} (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T.

The mean and variance of the residual vector e\mathbf{e} are respectively

E[e]=0andVar[e]=σ2(In−H)E[\mathbf{e}]=\mathbf{0} \quad\text{and}\quad Var[\mathbf{e}]=\sigma^2(\mathbf{I}_n-\mathbf{H})

Consequently, the ith studentized residual is defined by:

ti=eiσ^2(1−hii),(4)t_i = \frac{e_i}{\sqrt{\hat{\sigma}^2 (1 - h_{ii})}}, \tag{4}

where hiih_{ii} is the ith diagonal element of the hat matrix H\mathbf{H}.

Note: If hii≈1⇒tih_{ii} \approx 1 \Rightarrow t_i is big (hiih_{ii} is close to 1 for an outlier)


Deleted residuals

A useful refinement to make residuals more effective for detecting outlying YY observations is to measure the ith residual eie_i when the fitted regression is based on all of the cases except the ith one. Denote

  • Y^(i)\hat{Y}_{(i)}: the fitted regression equation based on all cases except the ith one.
  • Yi(i)^\hat{Y_i(i)} the ith fitted response value based on the predicted model Y(i)^\hat{Y_(i)}

Consequently, the deleted residual denoted did_i is defined by

di=Yi−Y^i(i).(5)d_i = Y_i - \hat{Y}_{i(i)}. \tag{5}
Residual_diagnostics_deleted_residual

Note: This relates to leave-one-out cross validation.


We want to studentize (or standardize) the deleted residuals, i.e., we want to find an expression for

t(i)=diσ^di.t_{(i)} = \frac{d_i}{\hat{\sigma}_{d_i}}.

An algebraically equivalent expression for did_i that does not require a recomputation of the fitted regression function omitting the ith case is:

di=ei1−hii.(6)d_i = \frac{e_i}{1 - h_{ii}}. \tag{6}

Define σ^(i)2\hat{\sigma}^2_{(i)} as the mean square error based on all cases except the ith one.

The following equation analogous to (6)(6) relates σ^(i)2\hat{\sigma}^2_{(i)} with the regular σ^2\hat{\sigma}^2:

(n−p)σ^2=(n−p−1)σ^(i)2+ei21−hii.(n - p) \hat{\sigma}^2 = (n - p - 1) \hat{\sigma}^2_{(i)} + \frac{e_i^2}{1 - h_{ii}}.

Studentized deleted residuals

Using the above relation, the studentized deleted residuals can be expressed as:

t(i)=diσ^di=ein−p−1SSE(1−hii)−ei2.(7)t_{(i)} = \frac{d_i}{\hat{\sigma}_{d_i}} = e_i \sqrt{ \frac{n - p - 1}{SSE(1 - h_{ii}) - e_i^2} }. \tag{7}

Uses of studentized deleted residuals

  • Using the deleted studentized residuals in diagnostic plots is a common technique of validating the regression assumptions.
  • The deleted studentized residuals are particularly useful in identifying outlying YY values.

Proof. Derivation of the Studentized Deleted Residual

The Studentized Deleted Residual (also called the Externally Studentized Residual) is defined as:

t(i)=eiσ^(i)1−hiit_{(i)} = \frac{e_i}{\hat{\sigma}_{(i)} \sqrt{1 - h_{ii}}}

Where:

  • ei=yi−y^ie_i = y_i - \hat{y}_i: the residual of observation ii
  • hiih_{ii}: the leverage of observation ii (diagonal of the hat matrix)
  • σ^(i)2\hat{\sigma}_{(i)}^2: the variance of residuals calculated by excluding observation ii

Step 1: Express σ^(i)2\hat{\sigma}_{(i)}^2

We estimate the leave-one-out residual variance as:

σ^(i)2=SSE(i)n−p−1\hat{\sigma}_{(i)}^2 = \frac{\text{SSE}_{(i)}}{n - p - 1}

We can approximate the leave-one-out sum of squared errors as:

SSE(i)=SSE−ei21−hii\text{SSE}_{(i)} = \text{SSE} - \frac{e_i^2}{1 - h_{ii}}

Thus:

σ^(i)2=SSE−ei21−hiin−p−1\hat{\sigma}_{(i)}^2 = \frac{\text{SSE} - \frac{e_i^2}{1 - h_{ii}}}{n - p - 1}

Step 2: Substitute into the definition of tit_i

Plug into the original formula:

ti=eiσ^(i)2(1−hii)=ei(SSE−ei21−hiin−p−1)(1−hii)t_i = \frac{e_i}{\sqrt{ \hat{\sigma}_{(i)}^2 (1 - h_{ii}) }} = \frac{e_i}{\sqrt{ \left( \frac{\text{SSE} - \frac{e_i^2}{1 - h_{ii}}}{n - p - 1} \right)(1 - h_{ii}) }}

Step 3: Simplify the expression

Multiply terms in the denominator:

(SSE−ei21−hii)(1−hii)=SSE(1−hii)−ei2( \text{SSE} - \frac{e_i^2}{1 - h_{ii}} )(1 - h_{ii}) = \text{SSE}(1 - h_{ii}) - e_i^2

So we arrive at:

ti=ei⋅n−p−1SSE(1−hii)−ei2t_i = e_i \cdot \sqrt{ \frac{n - p - 1}{ \text{SSE}(1 - h_{ii}) - e_i^2 } }

This formula allows you to compute the Studentized Deleted Residual without explicitly re-fitting the model for each observation, making it highly efficient for outlier diagnostics.


Use the studentized or deleted studentized residuals to construct residual plots.
Some recommendations follow:

  • Scatter plot matrix of all variables.
    Linearity, Constant Variance, General exploratory analysis

  • Plot of the studentized residuals against all (or some) of the predictor variables XX.
    Linearity, Constant Variance, Normality, Independence

  • Plot of the studentized residuals against fitted values.
    Same as the previous plot

  • Plot of the studentized residuals against time or other sequence.
    Independence, Normality

  • Plots of the studentized residuals against omitted predictor variables.
    Model validation

  • Box plot (or histogram) of the studentized residuals.
    Normality

  • Normal probability plot of studentized residuals.
    Normality, Linearity


Summary

TermSymbolFormulaDescription
Residualeie_iei=Yi−Y^ie_i = Y_i - \hat{Y}_iThe raw error between the observed value and the predicted value.
Semistudentized Residual
(Semistandardized Residual)
ei∗e_i^*eiσ^\dfrac{e_i}{\hat{\sigma}}Raw residual divided by the overall RMSE (ignores leverage).
Studentized Residual
(Internally Studentized Residual, Standardized Residual)
tit_ieiσ^1−hii\dfrac{e_i}{\hat{\sigma} \sqrt{1 - h_{ii}}}Adjusts residual by both RMSE and leverage
Deleted Residuale(i)e_{(i)}Yi−Y^(i)Y_i - \hat{Y}_{(i)}The residual when observation ii is left out from model fitting (leave-one-out prediction error).
Studentized Deleted Residual
(Externally Studentized Residual)
t(i)t_{(i)}eiσ(i)^1−hii\dfrac{e_i}{\hat{\sigma_(i)} \sqrt{1 - h_{ii}}}Residual scaled by RMSE computed excluding observation ii. Most reliable for outlier detection.

Notes

  • σ^\hat{\sigma}: The standard deviation of residuals computed using all observations (i.e., the RMSE).
  • σ^(i)\hat{\sigma}_{(i)}: The standard deviation of residuals computed by excluding observation ii from the model. This is used in externally studentized residuals.
  • hiih_{ii}: The leverage of observation ii — it represents how much influence observation ii has on its own predicted value (i.e., the diagonal element of the hat matrix H=X(XTX)−1XT\mathbf{H} = \mathbf{X} (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T).

Practical Tips

  • In real-world applications, the Studentized Deleted Residual (also called Externally Studentized Residual) is most commonly used for outlier detection, because it accounts for the influence of the observation being tested.
  • The Deleted Residual (i.e., the prediction error when leaving out a point) is important for assessing predictive performance, especially in cross-validation contexts.
  • The Semistudentized Residual is less commonly used in practice, but it serves as a basic form of normalization (dividing residuals by the global RMSE).

Example

import numpy as np import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.stats.outliers_influence import OLSInfluence # Simulate new data with an internal outlier np.random.seed(42) n = 30 x = np.linspace(0, 10, n) y = 3 * x + np.random.normal(0, 2, n) # Add an outlier within the range of x but with a strange y value x = np.append(x, 5.5) # within x range y = np.append(y, 30) # y value inconsistent with trend at x=5.5 # Create new DataFrame data_internal = pd.DataFrame({'x': x, 'y': y}) X_internal = sm.add_constant(data_internal['x']) model_internal = sm.OLS(data_internal['y'], X_internal).fit() # Get influence measures influence_internal = OLSInfluence(model_internal) studentized_residuals_internal = influence_internal.resid_studentized_external # Plot fig, ax = plt.subplots(figsize=(10, 6)) ax.scatter(range(len(studentized_residuals_internal)), studentized_residuals_internal, color='blue') ax.axhline(y=3, color='red', linestyle='--', label='Threshold (+3)') ax.axhline(y=-3, color='red', linestyle='--', label='Threshold (-3)') ax.set_xlabel('Observation Index') ax.set_ylabel('Studentized Deleted Residual') ax.set_title('Studentized Deleted Residual Plot') # Highlight potential outliers outlier_indices_internal = np.where(np.abs(studentized_residuals_internal) > 3)[0] for idx in outlier_indices_internal: ax.annotate(f"{idx}", (idx, studentized_residuals_internal[idx]), textcoords="offset points", xytext=(0, 10), ha='center', color='red') ax.legend() plt.tight_layout() plt.show() # Return suspected outlier info print('Outlier Info: \n', data_internal.iloc[outlier_indices_internal])
Studentized_Deleted_Residual_Plot
Outlier Info: x y 30 5.5 30.0

Note: Understanding Hat Matrix

In linear regression, the predicted values can be written as:

Y^=Xβ^=X(XTX)−1XTY=HY\mathbf{\hat{Y}} = \mathbf{X} \hat{\mathbf{\beta}} = \mathbf{X} (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{Y} = \mathbf{H} \mathbf{Y}

Here, H=X(XTX)−1XT\mathbf{H} = \mathbf{X} (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T is called the hat matrix. It maps the observed values Y\mathbf{Y} to the predicted values Y^\mathbf{\hat{Y}}:

Y^i=∑j=1nhijYj\hat{Y}_i = \sum_{j=1}^n h_{ij} Y_j

The diagonal element hiih_{ii} shows how much the prediction Y^i\hat{Y}_i depends on its own observed value YiY_i:

Y^i=hiiYi+∑j≠ihijYj\hat{Y}_i = h_{ii} Y_i + \sum_{j \ne i} h_{ij} Y_j

Why is hiih_{ii} called "Leverage"?

  • hiih_{ii} tells us how much influence observation ii has on its own predicted value.
  • If hiih_{ii} is large, then yiy_i contributes a large weight to predicting Y^i\hat{Y}_i.
  • This usually happens when xix_i is far from the center of the predictor space.
  • Such points are said to have high leverage, because they can pull the regression line toward themselves.

Properties of hiih_{ii}

  • 0<hii<10 < h_{ii} < 1
  • ∑i=1nhii=p\sum_{i=1}^n h_{ii} = p  (where pp is the number of model parameters including the intercept)
  • Average leverage: hˉ=pn\displaystyle \bar{h} = \frac{p}{n}
  • A rule of thumb: if hii>2hˉh_{ii} > 2\bar{h} or 3hˉ3\bar{h}, the point may be considered high leverage

High Leverage ≠ Outlier

  • A high hiih_{ii} doesn't necessarily mean the point is an outlier.
  • To detect influential outliers, we need to look at both:
    • The residual eie_i
    • The leverage hiih_{ii}
    • → This is what studentized deleted residuals are designed to detect.

Conclusion

  • hiih_{ii} (leverage) measures how much the predicted value Y^i\hat{Y}_i is influenced by the actual observation YiY_i.
  • High leverage points are far from the center of the xx-space and can strongly affect the regression fit.