Prediction & residuals

Draw the Best-Fit Line

Move a line, inspect its residuals and reveal the least-squares solution. Add an outlier and compare the errors.

8 min to exploreMachine Learning · CPTR 235
01 / UNDERSTAND

What exactly makes one line a better fit than another?

Residuals are observed minus predicted values. Least squares minimizes their squared sum, while MAE and RMSE describe errors differently and respond differently to outliers.

02 / EXPLORE

Make a prediction.
Then move a control.

Draw the best-fit lineInvented data · y = 1.5x + 3 + noise
Your modelŷ = 0.80x + 6.00
Observations, fitted line and residualsChange the slope and intercept to move a straight line. Vertical segments connect each actual value to its prediction.
ObservationYour line
Mean absolute error—MAE = mean(|y − ŷ|)
Root mean squared error—RMSE = √mean((y − ŷ)²)
Observations11All displayed points are used

Both errors use the same vertical residuals. RMSE gives large misses more weight.

What does least squares choose?

For these observations, ordinary least squares minimizes the sum of squared vertical residuals. It also minimizes RMSE, but does not generally minimize MAE.

Inspect the actual values, predictions and residuals
Your current model · residual = actual − prediction
xActual yPredicted ŷResidual

An educational experiment with illustrative data. The controls run locally in your browser.

03 / SEE THE CODE

The idea,
in Python.

A compact implementation of the core concept. Open the code when you are ready to connect the visual to the algorithm.

Open the core implementation Python ↗
Standalone example · illustrative valuesDownload .py
import numpy as np

x = np.array([1., 2., 3., 4., 5.])
y = np.array([2., 3., 5., 4., 6.])
design = np.column_stack([x, np.ones_like(x)])
slope, intercept = np.linalg.lstsq(design, y, rcond=None)[0]

prediction = slope * x + intercept
residual = y - prediction
mae = np.mean(np.abs(residual))
rmse = np.sqrt(np.mean(residual ** 2))
print("Slope / intercept:", slope, intercept)
print("MAE / RMSE:", mae, rmse)
04 / TRY IT

Explain the change.
Test your reasoning.

  1. Adjust slope and intercept to reduce the error before revealing the fitted line.
  2. Explain why a line with a small mean residual can still make large mistakes.
  3. Add an outlier and compare its effect on MAE, RMSE and the fitted line.
← All visual labsNext: Fit or Overfit?

Find your next idea.

Search across courses, research, projects, and resources.

Ideas, connected.esc to close