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. A good score can still hide a model that is wrong in a systematic way. Residuals show you that.
What a residual is
A residual is the actual value minus the predicted value: residual = y - prediction. If the linear model fits well, residuals look like random noise. If they show a pattern, the model is missing something.
The linear model makes these assumptions:
- The relationship between features and target is linear in the coefficients.
- Residuals have roughly constant spread (homoscedasticity).
- Residuals are roughly centered on zero, with no trend.
- Residuals are not strongly correlated with each other.
Computing residuals
Compute residuals on the test set, so you see how the model behaves on data it has not fitted.
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 close to the noise level used to generate the data (1.0). OLS with an intercept forces the training residuals to average zero, so a test mean far from zero points to a shift between train and test data.
Reading a residual plot
Plot residuals on the vertical axis and predictions on the horizontal axis. A healthy plot is a flat, even band around zero.
| Pattern | Likely cause | Common fix |
|---|---|---|
| Curve or U shape | Relationship is not linear | Add `PolynomialFeatures` or transform a feature |
| Funnel shape | Error grows with the prediction | Transform the target, for example with a log |
| Isolated large residuals | Outliers or data errors | Inspect those rows, then decide whether to keep them |
| Wave or runs of same sign | Rows are ordered in time | Use time-aware splits and features |
To draw the plot, pass model.predict(X_test) and residuals to matplotlib.pyplot.scatter, then add a horizontal line at zero with axhline(0).
Common errors
- Computing residuals as
prediction - y. The sign flips, so be consistent and say which convention you use. - Checking residuals only on training data. Overfit models look clean there.
- Relying on R-squared alone. Two datasets can share the same R-squared while one has a clear curve in its residuals.
- Treating the plot as a formal test. It is a visual check, so judge shapes, not single points.
Exercise
A residual plot of a fitted model shows a clear U shape, and R-squared on the test set is 0.85. Is the model fine? What would you try next?
Show answer
Not necessarily. The U shape means the linear form misses a curved relationship, even though R-squared looks good. Add squared terms with PolynomialFeatures(degree=2) inside a pipeline, refit, and check that the residual plot becomes a flat band.