Build residual-versus-predicted coordinates and fixed-bin summaries from held-out records before interpreting a regression error plot.
Regression residual plots: locate bias, spread and missing segments
Name the residual and the split
For this lesson, residual means observed value minus predicted value. A positive residual is an underprediction; a negative residual is an overprediction. Put predicted value on the horizontal axis and residual on the vertical axis with a visible zero line. State the outcome unit and whether the records are training, validation or a final held-out set. Training residuals can look artificially calm after model selection. If repeated measurements belong to the same account or machine, preserve that identity when splitting and when estimating uncertainty. Overplotting controls matter when thousands of residuals pile onto rounded predictions.
Inspect structure before a score
A curved center suggests the model misses a systematic relationship; a fan-shaped spread suggests error size changes with the predicted level. Bands or clusters may reveal a missing segment or a target recorded at only a few allowed values. None of these shapes by itself identifies a cause. Color or facet by a prespecified segment, but hold axes fixed across panels so one group's errors do not look small only because its scale expanded. Small multiples make that comparison testable. Plot residuals against time as a second view; time order can reveal drift that disappears when points are sorted by predicted value.
Pair points with fixed-bin summaries
Choose predicted-value bin boundaries before reading the result. For each bin, print support, mean signed residual, mean absolute error and perhaps an upper error quantile. The signed mean detects directional bias; the absolute mean cannot cancel positive and negative misses. A bin with three records should not receive the same visual authority as one with three thousand. Keep bins fixed when comparing model versions or periods and disclose records outside the chart domain. Population and denominator rules still apply: removing failed predictions changes the displayed population. Uncertainty views can show how unstable a sparse bin's mean is.
Do not turn every pattern into a linear-model violation
The familiar constant-variance diagnostic is useful for some regression assumptions, but count-like or positive skewed outcomes may naturally have error spread that grows with the expected value. The plot still documents operational error; interpreting it requires the loss function and data-generating process. Large residuals can be genuine costly cases, label errors or records outside the model's intended domain. Investigate with stable IDs, not anonymous dots. If the outcome was transformed during training, bring predictions and actuals back to a common declared scale before computing residuals. A Q–Q plot checks tail shape; it answers a different question from residual versus fitted value.
Worked contract
from bisect import bisect_right
from math import isfinite, sqrt
def residual_profile(records: list[tuple[str, float, float]],
edges: list[float]):
if (len(edges) < 2 or any(not isfinite(edge) for edge in edges)
or any(left >= right for left, right in zip(edges, edges[1:]))):
raise ValueError("bin edges must be finite and strictly increasing")
record_ids = [record_id for record_id, _, _ in records]
if len(record_ids) != len(set(record_ids)) or any(not key for key in record_ids):
raise ValueError("record IDs must be unique and nonempty")
bins = [[] for _ in range(len(edges) - 1)]
points = []
for record_id, observed, predicted in records:
if (not isfinite(observed) or not isfinite(predicted)
or predicted < edges[0] or predicted > edges[-1]):
raise ValueError("record is invalid or outside the plot domain")
residual = observed - predicted
index = min(bisect_right(edges, predicted) - 1, len(bins) - 1)
bins[index].append(residual)
points.append((record_id, predicted, residual))
summaries = []
for index, errors in enumerate(bins):
count = len(errors)
summaries.append((edges[index], edges[index + 1], count,
sum(errors) / count if count else None,
sum(abs(error) for error in errors) / count
if count else None,
sqrt(sum(error * error for error in errors) / count)
if count else None))
return points, summaries
shipment_estimates = [("shipment-47", 23, 20), ("shipment-59", 31, 32),
("shipment-83", 44, 48), ("shipment-97", 68, 60),
("shipment-101", 69, 72), ("shipment-131", 78, 88)]
points, bands = residual_profile(shipment_estimates, [0, 50, 100])
assert points[3] == ("shipment-97", 60, 8)
assert bands[0][2:5] == (3, -2 / 3, 8 / 3)
assert bands[1][2:5] == (3, -5 / 3, 7.0)Performance and operating cost
For N records and B fixed bins, assigning each prediction with binary search takes O(N log B) time and summarizing residuals takes O(N + B); storing the points, ID set and bin contents uses O(N + B) space. The six-shipment assertion checks sign convention and separates signed bias from absolute error. It does not diagnose serial correlation, supply uncertainty intervals or validate the model split. Those require a held-out design and more observations.
Common Mistakes
- Switching residual sign between charts without changing the label.
- Re-estimating bins for each model so apparent segment changes cannot be compared.
- Dropping observations whose predictions lie beyond the drawn axis without an exclusion count.
- Using only average signed residual when large positive and negative errors cancel.
Validation drill
Export 470 held-out shipment predictions with stable IDs and outcome times. Build residual-versus-predicted and residual-versus-time views, keep fixed bin edges and shared axes, and audit the three bins with the largest mean absolute error alongside their support counts.
