Outliers, Leverage, and Influence in OLS Regression
Machine LearningModel answerLast updated
Derive Cook's distance from first principles, build a diagnostic workflow, show how one point can flip a coefficient's sign, and compare robust regression alternatives.
Setting the scene
You are reviewing a linear regression model before it ships to production. A colleague flags that "there might be some weird points." Your job is to be precise about what that means and to decide what to do about it.
The model is ordinary least squares: $y = X\beta + \varepsilon$, where $X$ is $n \times p$ (including the intercept column).
What you are asked to do
Part 1 — Definitions and derivation
Clearly distinguish three concepts that are often conflated:
- An outlier in the response
- A high-leverage observation
- An influential observation
Then derive Cook's distance $D_i$ from the leave-one-out deletion formula. Your derivation should make explicit how $D_i$ depends on the leverage $h_{ii}$ and the studentized residual $r_i$, and explain why both components are necessary.
Part 2 — Diagnostic workflow
Walk through the sequence of plots and statistics you would run, in the order you would run them, to detect each of the three point types. Note any traps — situations where a standard diagnostic gives a misleading result.
Part 3 — Consequences and alternatives
Using a small concrete example (you may construct one), show how removing a single influential point can materially change a conclusion — for instance, flipping the sign of a coefficient. Then propose at least two robust regression alternatives to OLS, explaining how each one limits the damage from problematic points and what its limitations are.
Part 4 — Reporting
How would you document and justify a decision to retain, remove, or down-weight one or more observations in a model review? What distinguishes a defensible decision from p-hacking?
What a complete answer looks like
- A clean derivation with the key algebraic step made explicit
- A prioritized workflow (not just a list of tools)
- A numerical example that makes the sign-flip concrete
- A comparison of at least two robust methods with honest trade-offs
- A short but principled position on reporting
Hints
Hint 1
The hat matrix H = X(X'X)⁻¹X' projects y onto the column space of X. The diagonal entry h_ii is the leverage of observation i. Think about what it means geometrically — how far x_i sits from the centroid of the predictor space — and why that makes it possible for one observation to control the fit without showing a large raw residual.
Hint 2
For the derivation, apply the Sherman–Morrison identity to (X'X − x_i x_i')⁻¹. The payoff is a closed-form expression for β̂ − β̂_(i) that requires no refitting. Once you have that, Cook's distance is just that shift measured in the natural metric of the coefficient space.
Hint 3
Residual-only screening is the most common mistake. A high-leverage point that lies close to where the fitted line would land anyway has a small residual — but it may still be the observation that determined where the line landed. Always check leverage and Cook's distance together, and watch for masking: several bad points clustered in predictor space can make each other look unremarkable.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Definitions
The OLS estimator is $\hat\beta = (X^\top X)^{-1}X^\top y$. The hat matrix is $H = X(X^\top X)^{-1}X^\top$, so fitted values are $\hat y = Hy$ and residuals are $e = (I - H)y$.
Leverage of observation $i$ is the diagonal entry $h_{ii} = x_i^\top(X^\top X)^{-1}x_i$. It depends only on $X$, not on $y$. It equals the squared Mahalanobis distance of $x_i$ from the predictor centroid, rescaled. Properties: $1/n \le h_{ii} \le 1$ with an intercept; $\sum h_{ii} = p$; average leverage is $p/n$. A common flag is $h_{ii} > 2p/n$.
Outlier: the response $y_i$ is unusual given $x_i$. Detected by a large studentized residual, not a large raw residual.
High-leverage point: $x_i$ is far from the centroid of the predictor cloud. It can pull the fitted line, but a high-leverage point that happens to fall on the trend is harmless — it actually reduces $\text{Var}(\hat\beta)$.
Influential point: deleting it materially changes $\hat\beta$ or the fitted values. Influence $\approx$ leverage $\times$ residual. A point needs both to be influential.
Deriving Cook's distance
Step 1 — deletion formula. Apply Sherman–Morrison to $(X^\top X - x_i x_i^\top)^{-1}$:
$$\hat\beta - \hat\beta_{(i)} = \frac{(X^\top X)^{-1}x_i,e_i}{1 - h_{ii}}$$
This is exact and requires no refitting; all $n$ deletions follow from one model fit.
Step 2 — measure the shift. Cook's distance places that shift in the metric of the OLS confidence ellipsoid:
$$D_i = \frac{(\hat\beta - \hat\beta_{(i)})^\top X^\top X,(\hat\beta - \hat\beta_{(i)})}{p,s^2}$$
Step 3 — substitute and simplify. The quadratic form reduces to $e_i^2 h_{ii}/(1-h_{ii})^2$, giving:
$$\boxed{D_i = \frac{r_i^2}{p}\cdot\frac{h_{ii}}{1 - h_{ii}}}$$
where $r_i = e_i / (s\sqrt{1-h_{ii}})$ is the internally studentized residual.
Reading the formula: $D_i$ is large only when both the squared residual and the leverage factor are large. A large residual at low leverage barely moves the fit. High leverage with a tiny residual also barely moves it. Only the combination is dangerous.
Thresholds: $D_i > 4/n$ is a common screening cutoff. More formally, compare against the median of $F_{p,,n-p}$ — values near 1 are serious.
For per-prediction influence, $\text{DFFITS}i = t_i\sqrt{h{ii}/(1-h_{ii})}$, flagged above $2\sqrt{p/n}$. For per-coefficient influence, $\text{DFBETAS}_{ij}$, flagged above $2/\sqrt{n}$.
Diagnostic workflow
Run these in order — earlier steps prevent misreading later ones.
- Data audit first. Unit errors, timestamp misalignments, and bad joins produce apparent outliers that are really data bugs. Fix before modeling.
- Residuals vs. fitted. Nonlinearity or heteroskedasticity in the mean function creates artificial outliers. Model misspecification comes before point diagnostics.
- Q–Q plot of externally studentized residuals $t_i$. Use external studentization: in $r_i$, an outlier inflates $s$ and hides itself. Under the model, $t_i \sim t_{n-p-1}$.
- Outlier test. Flag observations where $|t_i|$ exceeds the Bonferroni-corrected critical value $t_{n-p-1,,\alpha/(2n)}$.
- Leverage index plot. Flag $h_{ii} > 2p/n$. For multivariate $X$, supplement with robust Mahalanobis distances (minimum covariance determinant). Ordinary $h_{ii}$ can be pulled toward 1 by a cluster of bad points, masking each individual one.
- Residuals vs. leverage with Cook's contours. This single plot is the most useful. Points in the upper-right and lower-right corners (large $|r_i|$, large $h_{ii}$) are the ones to investigate.
- Index plot of $D_i$, DFFITS, and DFBETAS for coefficients of interest.
- Added-variable plots to see which observation is driving which specific coefficient.
- Masking check. Single-deletion diagnostics break down when several bad points cluster together. Fit a high-breakdown estimator (LTS or MM), compute robust residuals, and compare. Points flagged there but not by OLS diagnostics are masked.
import statsmodels.api as sm
res = sm.OLS(y, sm.add_constant(X)).fit()
inf = res.get_influence()
h = inf.hat_matrix_diag
t_ext = inf.resid_studentized_external
cooks = inf.cooks_distance[0]
dffits = inf.dffits[0]
A concrete sign-flip example
Data: $(1,1),(2,2),(3,3),(4,4),(10,0)$.
Full fit: $\bar x = 4$, $S_{xx} = 50$, $S_{xy} = -10$. Slope $= -0.2$.
Point $(10,0)$: $h_{55} = 1/5 + 36/50 = 0.92$ — extreme leverage. Raw residual $e = -0.8$ — looks small because the line was pulled toward the point. $D \approx 17$, far above any reasonable threshold.
Fit without it: slope $= +1.0$. The sign flips. In an applied setting this is the difference between "variable X is negatively associated with the outcome" and "positively associated."
The lesson: screening on residuals alone would have retained this point.
Robust alternatives
Huber M-estimator. Uses a quadratic loss for $|u| \le c$ and linear beyond ($c = 1.345\hat\sigma$ for ~95% efficiency under normality). Fit by iteratively reweighted least squares. Convex, stable, easy to interpret. Limitation: it bounds the influence of large residuals but not of high leverage — a point like $(10,0)$ can still pull it badly. Its breakdown point in $x$ is 0.
MM-estimation (Tukey biweight). Two-stage: an S-estimator first achieves 50% breakdown point to get a robust scale and starting coefficients, then a biweight M-step redescends the loss so that gross outliers get weight exactly zero. This is the standard production choice when you expect a meaningful contamination fraction. Limitation: non-convex; needs a good starting point; less interpretable weights.
RANSAC. Fits on random minimal subsets, counts inliers within a tolerance, iterates. Works well with very high contamination fractions and is natural for geometric fitting. Limitations: sensitive to the inlier threshold; stochastic; slow on large $n$.
LTS (least trimmed squares). Minimizes the sum of the smallest $h$ squared residuals. High breakdown. Limitation: computationally expensive; the choice of $h$ is a tuning decision.
Reporting and defensibility
A defensible decision has a documented data-quality reason (recording error, known instrument failure, event outside the model's scope) or a pre-registered rule that does not depend on which direction the removal moves the coefficient. Write down the reason before you look at how the coefficient changes.
Red flags for p-hacking: the decision is made after seeing the p-value; the removal helps the hypothesis but the paper reports only the cleaned result without sensitivity analysis; or no robust-fit comparison is shown.
Best practice: report both the full-data and cleaned results. Show a Cook's distance plot and state the threshold used. If a robust estimator gives similar conclusions to the cleaned OLS, that is meaningful convergent evidence. If they disagree, say so and explain why.
The hardest case is a domain-meaningful extreme point — a market crash day, a patient with a rare comorbidity. Removing it is usually wrong; modeling it explicitly (indicator variable, separate regime, mixture model) is usually right.