Sub topic 8
Checking residuals and assumptions
This chapter assumes you can fit a LinearRegression, split data with train_test_split, and compute RMSE, MAE and R-squared. You should also be comfortable with NumPy arrays and the idea of variance. Metrics give you one number for the error. Residuals show you where and how the model is wrong.
What a residual is
A residual is the actual value minus the predicted value for one row:
residual = y_actual - y_predictedA positive residual means the model predicted too low. A negative residual means it predicted too high. If the model captured the real pattern, the residuals should look like random noise around zero. Any visible structure in them is information the model missed.
Ordinary least squares (OLS) fitted with an intercept guarantees that the residuals on the training data average to zero. That holds by construction and tells you nothing about quality. The residuals that matter most are the ones on held-out data, and the shape of residuals matters more than their mean.
The assumptions behind the linear model
OLS gives sensible coefficients even when its assumptions fail. The assumptions matter for how much you can trust the model's predictions and any statistical claims built on it. The main ones are:
- Linearity. The average of
yis a linear function of the features. If the true relationship curves, the model is biased in a systematic way. - Constant variance (homoscedasticity). The spread of the errors is the same at every prediction level. If the spread grows with the prediction, the errors are heteroscedastic.
- Independent errors. One row's error tells you nothing about another's. Time series and grouped data often break this.
- Roughly normal errors. This matters mainly for confidence intervals and p-values. It matters little for prediction when you have plenty of data.
scikit-learn does not report p-values or confidence intervals. For that, use statsmodels. In scikit-learn, the practical tool is looking at residuals directly.
Computing residuals on the test set
This example fits a model on data that really is linear, then computes residuals on the test set.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(200, 1))
y = 3.0 * X[:, 0] + 2.0 + rng.normal(0, 1.0, size=200)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
model = LinearRegression().fit(X_train, y_train)
residuals = y_test - model.predict(X_test)
print("mean residual:", residuals.mean())
print("residual std:", residuals.std())The mean should be close to zero, and the standard deviation should be close to 1.0, the noise level used to generate the data. On real data you do not know the true noise. The residual standard deviation then serves as an estimate of the typical error, and it is nearly the same quantity as RMSE.
A mean near zero on the test set does not prove the model is good. A model can have a zero-mean residual and still be wrong in a systematic way, as the next section shows.
Reading a residual plot
The standard diagnostic plots residuals on the vertical axis against predicted values on the horizontal axis. A horizontal line at zero is the reference.
import matplotlib.pyplot as plt
pred = model.predict(X_test)
plt.scatter(pred, residuals, alpha=0.7)
plt.axhline(0, color="black", linewidth=1)
plt.xlabel("Predicted value")
plt.ylabel("Residual (actual - predicted)")
plt.show()Use predicted values on the horizontal axis, not a single feature. With many features, the prediction summarizes all of them in one axis. You can also plot residuals against each feature separately to find which one carries the problem.
The table below lists what common patterns mean and what to try.
| Pattern in the plot | What it suggests | What to try |
|---|---|---|
| Random cloud around zero, even width | Assumptions look reasonable | Nothing needed |
| Curve (a U shape or arch) | Relationship is not linear | Add `PolynomialFeatures`, or transform a feature |
| Funnel (spread grows left to right) | Non-constant variance | Model `log(y)`, or use a different loss |
| A few points far from zero | Outliers or data errors | Check the rows, consider a robust model |
| Waves or runs of same-sign residuals | Errors depend on order | Use time-aware features and splits |
A model that fails the linearity check
The next example fits a straight line to a curved relationship. R-squared may look acceptable, which is why the residual plot is worth checking.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
rng = np.random.default_rng(1)
X = rng.uniform(-3, 3, size=(300, 1))
y = X[:, 0] ** 2 + rng.normal(0, 0.3, size=300)
line = LinearRegression().fit(X, y)
pred = line.predict(X)
res = y - pred
print("R2:", r2_score(y, pred))
print("mean residual:", res.mean())
# Compare average residual at the edges and in the middle
edges = np.abs(X[:, 0]) > 2
middle = np.abs(X[:, 0]) < 1
print("edge residual mean:", res[edges].mean())
print("middle residual mean:", res[middle].mean())Here the true relationship is symmetric, so the fitted line is nearly flat and R-squared is close to zero. The training mean residual is zero, as promised. The edge and middle means show the problem: the edges have large positive residuals and the middle has negative ones. That pattern is the U shape you would see in the plot. Adding a squared term fixes it, as a later chapter on PolynomialFeatures shows.
A numeric check like this is useful in automated reports, where nobody looks at plots. Grouping residuals by bins of a feature or prediction and comparing group means catches the same curve.
Checking for non-constant variance
Funnel shapes show up as residual size changing with the prediction. A quick numeric check compares the spread in the lower and upper halves of the predictions.
import numpy as np
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(2)
X = rng.uniform(1, 10, size=(400, 1))
noise = rng.normal(0, 1.0, size=400) * X[:, 0] # noise grows with X
y = 2.0 * X[:, 0] + noise
model = LinearRegression().fit(X, y)
pred = model.predict(X)
res = y - pred
cut = np.median(pred)
print("residual std, low predictions: ", res[pred <= cut].std())
print("residual std, high predictions:", res[pred > cut].std())The second number should be clearly larger. When this happens, coefficients are still unbiased, but a single RMSE hides the fact that errors are small for low predictions and large for high ones. If you need to report an error band, report it per range. If the target is positive and grows multiplicatively, such as prices, fitting log(y) often stabilizes the spread. TransformedTargetRegressor in sklearn.compose applies the transform and its inverse for you.
Use test residuals, and watch for leakage
Residuals on training data are optimistic, especially for flexible models. Compute them on held-out data, or on out-of-fold predictions from cross_val_predict. Plot the same way. With a pipeline, pass the whole pipeline to cross_val_predict so scaling is refit inside each fold.
Common errors
- Reading the mean residual as a quality check. OLS with an intercept makes the training mean zero. Look at the shape instead.
- Reversing the sign. scikit-learn metrics take
(y_true, y_pred). Residuals here arey_true - y_pred. Some libraries flip the sign, so check before comparing plots. - Plotting against the row index. That only helps if the rows have a meaningful order, as in time series.
- Over-reading small samples. With a few dozen points, random clouds can look like patterns. Compare with a plot from data you know is well behaved.
- Treating normality as required for prediction. Skewed residuals matter for intervals. They matter less for point forecasts.
Summary
Residuals are y_true - y_pred. Plot them against predictions on held-out data and look for curves, funnels, outliers and runs. Each pattern points to a specific fix: nonlinear terms, a target transform, a data review, or time-aware modeling.
Exercise
You fit LinearRegression with an intercept and find the mean residual on the training set is exactly zero (to rounding error). A colleague says this proves the model has no systematic bias. What is wrong with this claim, and what would you check instead?
Show answer
OLS with an intercept forces the training residuals to average zero, so this happens for any data, including data with a curved relationship. It says nothing about fit quality. Instead, compute residuals on held-out data and plot them against predictions (and against individual features). Look for curves, funnels, outliers and runs. A numeric alternative is to bin by a feature or by the prediction and compare the mean residual in each bin. Bins with consistently positive or negative means show systematic bias.
Exercise
A residual plot for a house-price model shows a funnel: small residuals for cheap houses and large residuals for expensive ones. Name the problem and one way to address it in scikit-learn.
Show answer
The errors have non-constant variance (heteroscedasticity). One fix is to model the logarithm of the price, using TransformedTargetRegressor with func=np.log and inverse_func=np.exp wrapped around the regressor. Predictions come back in the original units, and the spread of residuals on the log scale is usually more even.