TExcelTAD
Home › Data Science › DS Residual Analysis

DS Residual Analysis

A regression's coefficients, p-values and intervals are only trustworthy if the model's assumptions roughly hold. The residuals — actual minus fitted values — are where you check them. If the model has captured the systematic part of the data, the residuals should look like structureless noise.

Assumption Check Problem looks like
Linearity residuals vs fitted values a curve or U-shape
Constant variance residuals vs fitted values a funnel (spread grows)
Independence residuals over time; Durbin-Watson runs of positive/negative residuals
Normality histogram, Q-Q plot; Jarque-Bera skewed or heavy-tailed residuals

Residuals vs fitted values

The single most useful diagnostic plot. Let's compare our good model with one that's missing something:

python · try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

poor = smf.ols("rides ~ temp_c", data=bikes).fit()
good = smf.ols("rides ~ temp_c + rain_mm + weekend", data=bikes).fit()

fig, axes = plt.subplots(1, 2, figsize=(11, 4), sharey=True)
for ax, m, title in [(axes[0], poor, "rides ~ temp_c"), (axes[1], good, "rides ~ temp_c + rain_mm + weekend")]:
    ax.scatter(m.fittedvalues, m.resid, c=bikes["weekend"], cmap="coolwarm", s=15)
    ax.axhline(0, color="black", lw=1)
    ax.set_title(title)
    ax.set_xlabel("fitted rides")
axes[0].set_ylabel("residual")
plt.tight_layout()
plt.show()

print("mean residual on weekends, poor model:", round(poor.resid[bikes["weekend"] == 1].mean(), 1))
print("mean residual on weekends, good model:", round(good.resid[bikes["weekend"] == 1].mean(), 1))
mean residual on weekends, poor model: 49.6
mean residual on weekends, good model: -0.0

In the temperature-only model, weekend days (red) sit mostly above zero: the model systematically under-predicts them, a sign of a missing variable. In the full model they are spread evenly around zero.

A curve the line missed

When the true relationship is curved, the residuals of a straight line form an arch:

python · try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf

rng = np.random.default_rng(8)
temp = rng.uniform(5, 38, 80).round(1)
rides = (40 + 32 * temp - 0.7 * temp ** 2 + rng.normal(0, 30, 80)).round()
summer = pd.DataFrame({"temp_c": temp, "rides": rides})

line = smf.ols("rides ~ temp_c", data=summer).fit()
plt.scatter(line.fittedvalues, line.resid, s=15)
plt.axhline(0, color="black", lw=1)
plt.xlabel("fitted rides")
plt.ylabel("residual")
plt.title("Straight line fitted to curved data")
plt.show()

summer["band"] = pd.cut(summer["temp_c"], [0, 15, 28, 40], labels=["cool", "mid", "hot"])
print(line.resid.groupby(summer["band"], observed=True).mean().round(1))
band
cool   -32.8
mid     40.2
hot    -42.8
dtype: float64

Residuals are negative at both ends and positive in the middle — the straight line is the wrong shape. The fix is a squared term, as in Feature Engineering.

Normality: the Q-Q plot

A Q-Q plot compares the residuals' quantiles with those of a normal distribution. Points on the diagonal line mean the residuals are close to normal:

python · try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf
from scipy import stats

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

good = smf.ols("rides ~ temp_c + rain_mm + weekend", data=bikes).fit()
stats.probplot(good.resid, dist="norm", plot=plt)
plt.title("Q-Q plot of residuals")
plt.show()

jb_stat, jb_p = stats.jarque_bera(good.resid)
print(f"Jarque-Bera p-value: {jb_p:.3f}")
print(f"skew: {stats.skew(good.resid):.2f}")
Jarque-Bera p-value: 0.009
skew: 0.90

Most points follow the line, but at the upper end they bend away from it: a few days have larger positive residuals than a normal distribution would produce. The Jarque-Bera test (also printed at the bottom of summary()) flags this with p ≈ 0.009, and the skew is 0.90. Is that a problem? For the coefficients and their p-values, hardly: OLS is fairly robust to mild non-normality with 60 observations. It matters more for prediction intervals, which assume normal errors — the model may understate how often unusually busy days occur. Worth a note in the report, and worth re-checking as more data arrives.

Independence over time

For data collected over time, plot the residuals in time order. Long runs above or below zero mean that one day's error predicts the next — the model is missing something that changes slowly (a trend, a holiday period). The Durbin-Watson statistic summarises this: about 2 means no autocorrelation; values well below 2 mean positive autocorrelation.

python · try it yourself
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from statsmodels.stats.stattools import durbin_watson

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

good = smf.ols("rides ~ temp_c + rain_mm + weekend", data=bikes).fit()
print("Durbin-Watson, good model:", round(durbin_watson(good.resid), 2))

# add a slow upward drift (e.g. growing membership) the model doesn't know about
bikes["rides_trend"] = bikes["rides"] + 3 * np.arange(60)
drift = smf.ols("rides_trend ~ temp_c + rain_mm + weekend", data=bikes).fit()
print("Durbin-Watson, missing trend:", round(durbin_watson(drift.resid), 2))
signs = np.sign(drift.resid.to_numpy())
print("first 10 residual signs:", "".join("+" if s > 0 else "-" for s in signs[:10]),
      "... last 10:", "".join("+" if s > 0 else "-" for s in signs[-10:]))
Durbin-Watson, good model: 1.83
Durbin-Watson, missing trend: 0.56
first 10 residual signs: ---------- ... last 10: ++++++++++

The missing trend pushes residuals below zero at the start and above at the end, and Durbin-Watson drops well below 2. The fix is to add a time feature such as day_index.

Test yourself

Residuals plotted against fitted values form a U-shape. What does it suggest?

  1. The model is perfect
  2. The relationship is non-linear; consider a squared term or transformation
  3. There are missing values
  4. The residuals are normal

What does a funnel shape (spread growing with fitted values) indicate?

  1. Non-constant variance (heteroscedasticity)
  2. Perfect fit
  3. Too few variables
  4. Normal residuals

A Durbin-Watson statistic of 0.9 on daily data suggests…

  1. No autocorrelation
  2. Positive autocorrelation: residuals of neighbouring days are similar
  3. Normal residuals
  4. A perfect model