Menu
CoddyTech

Residual Plots

Part of the Supervised Learning section of Coddy's Machine Learning journey. Lesson 14 of 58.

A good score can hide a wrong shape. This line scores R squared 0.82 on a rising dough, yet its misses arch:

Left: dough height against hours, rising fast then slowing, with a straight fitted line, R squared 0.82. Right: the residuals against the predictions climb from -1.3 to +0.7 and fall back to -0.7, an arch around the dashed zero line

That right chart is a residual plot: each residual, actual minus predicted, against its prediction, over a line at 0:

residuals = y_test - pred
fig, ax = plt.subplots()
ax.scatter(pred, residuals)
ax.axhline(0, color="gray", linestyle="--")
plt.show()

Healthy residuals scatter like noise around 0. A pattern means the model misses something: here, that the rise slows down.

With several features, plot residuals against each feature too: the one that arches hides the curve.

challenge icon

Challenge

Medium

A driving school fitted a line to 80 braking tests: speed_kmh and braking_m. The starter keeps the test predictions in pred and labels the chart.

  1. Compute the residuals.
  2. Scatter them against the predictions over a dashed gray line at 0, then show it.

Does the line miss a curve? On the left it even predicts a negative braking distance.

A sound line's plot, from other data, looks like this:

A residual plot titled A Sound Line: twenty dots scattered without any pattern above and below a dashed line at 0

Coddy describes your chart.

Try it yourself

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

brakes = pd.read_csv("braking.csv")
X_train, X_test, y_train, y_test = train_test_split(brakes[["speed_kmh"]], brakes["braking_m"], test_size=0.25, random_state=0)
model = LinearRegression()
model.fit(X_train, y_train)
pred = model.predict(X_test)

fig, ax = plt.subplots()
ax.set_title("Braking Line Check")
ax.set_xlabel("Predicted braking distance (m)")
ax.set_ylabel("Residual (m)")

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Supervised Learning

Practice on your own: Online Python compiler