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:
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
MediumA 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.
- Compute the residuals.
- 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:
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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Supervised Learning
1Your First Model
Learning from ExamplesTrain and Test SetsFit and PredictScoring a ModelRecap: Seed Sorter2Nearest Neighbors
How k-NN DecidesChoosing kDecision BoundariesScaling for NeighborsRecap: Wine Neighbors5Measuring Classifiers
The Confusion MatrixPrecision and RecallThe F1 ScoreImbalanced ClassesROC CurvesRecap: Screening Test11Project: Penguin Species
Meet the PenguinsPrepare the DataChoose a ModelTune the WinnerShip the Model3Linear Regression
Predicting NumbersSeveral FeaturesMeasuring ErrorsResidual PlotsRecap: Bike RentalsPractice on your own: Online Python compiler