COMP328 Fundamentals of Machine Learning

1 Learning objectives

By the end of this tutorial you will be able to

  • Compute and interpret RMSE, MAE and R², and explain what each one measures and what it hides.
  • Explain why R² always increases when a feature is added, and how adjusted R² corrects for this.
  • Split data into training, validation and test sets, and explain the distinct role of each.
  • Read a residual plot and identify the four common failure patterns: random scatter, curvature, funnelling and outliers.
  • Diagnose underfitting and overfitting from a learning curve, and say what to do in each case.
  • Interpret a validation curve and use it to choose a model complexity.
  • Describe the difference between training error, validation error and test error, and explain why the training error is always optimistic.
  • Recognise the practical signs of data leakage and describe how to eliminate it.
  • Report a regression model's performance honestly, including its failure modes and the range over which it is valid.

Estimated time

35 minutes of reading, plus 30–35 minutes for the practice exercises and problem set. The residual plot section carries the most practical weight — spend time on it.

2 Motivating example

Here are two regression models, both fitted to real data, both reported with the same headline number.

Model A

R² = 0.87

The residuals form a clean U-shape when plotted against the feature. The model systematically over-predicts at both extremes and under-predicts in the middle.

Model B

R² = 0.87

The residuals scatter randomly around zero with no visible pattern. The model's errors look like noise.

Identical R². Completely different models. Model A has captured a relationship that is not linear and is reporting a good score while being wrong in a structured, predictable way. Model B may be genuinely capturing the relationship, or it may have a different problem — overfitting, leakage, or simply a lucky split. You cannot tell from the number.

This is the central lesson of the tutorial, and it is worth stating plainly: a single summary statistic is never sufficient evidence that a model is good. Evaluation is not the act of Computing a number. It is the discipline of gathering several kinds of evidence, on data the model has not seen, and looking at the evidence rather than just the score.

Four questions have to be answered before you can trust a regression model, and each one requires a different piece of evidence:

  1. How wrong is it, typically? RMSE and MAE. Both measured on held-out data, never on the training set.
  2. Is it wrong in a structured way? The residual plot. This is where non-linearity, heteroscedasticity and outliers reveal themselves.
  3. Will it keep working on new data? A train/validation gap, and a learning curve. This distinguishes a model that has learned from one that has memorised.
  4. Where is it valid? The range of the training features. Outside that range, no regression model has any evidence to offer.

Everything in this tutorial is machinery for answering one of those four.

Where this sits in the course

Module 2 has its own Unit 6 on model evaluation, and that unit covers the classification side: confusion matrices, precision, recall, ROC curves. This tutorial is the regression counterpart. The two share a philosophy — measure on held-out data, look beyond the headline number, diagnose before you deploy — but the specific tools are different, because a regression model's errors are magnitudes rather than counts of correct and incorrect labels.

3 Concept explanation

3.1 RMSE and MAE

Two metrics answer the question "how wrong is this model, typically?" They differ only in how they combine the residuals.

Root mean squared error and mean absolute error

RMSE = √( (1/n) Σ ei² )

MAE = (1/n) Σ |ei|

Both are in the same units as the target, which is what makes them interpretable. MSE, covered in Tutorial 4, is in squared units and is therefore a poor thing to report to a stakeholder.

Both metrics measure the typical size of the error. The difference is how they weight large errors relative to small ones.

RMSE versus MAE
Property RMSE MAE
Units Same as the target Same as the target
Weighting of large errors Quadratic — a 10× larger error contributes 100× more Linear — a 10× larger error contributes 10× more
Robust to outliers No — dominated by the largest errors Yes — every error counted in proportion
Relationship to the loss being minimised Directly related — RMSE is the square root of the MSE we minimised Not the loss being minimised — least squares does not optimise MAE
Best used when Large errors are disproportionately costly All errors are roughly equally costly

The ratio RMSE/MAE is itself informative. If all residuals were identical in magnitude, RMSE would equal MAE and the ratio would be 1. If a small number of residuals are much larger than the rest, RMSE is pulled upward while MAE barely moves, and the ratio rises.

Reading the RMSE/MAE ratio
Ratio Interpretation
≈ 1.0 Errors are fairly uniform in size. No error dominates.
1.1 – 1.3 Typical for well-behaved data. A few errors are somewhat larger.
1.5 – 2.0 A small number of errors are substantially larger than the rest. Worth investigating.
> 2.0 One or two observations dominate the error. The model is effectively being fitted and evaluated on a handful of points.

This ratio is a one-line diagnostic that costs nothing and catches a whole class of problems. Compute it every time.

RMSE and MAE are scale-dependent

An RMSE of 107 rentals is meaningless without knowing that the average rental count is 325. Always report the metrics alongside the target's mean and standard deviation, or as a percentage of the mean. Better still, report R² alongside them, because R² is scale-free.

3.2 R² and adjusted R²

R², the coefficient of determination, measures the proportion of the target's variance that the model explains. It is defined as one minus the ratio of the residual sum of squares to the total sum of squares:

Coefficient of determination

R² = 1 − RSS / TSS = 1 − Σei² / Σ(yi − ȳ)²

TSS is the total sum of squares: the error the mean baseline would make. So R² is literally a comparison against the baseline from Tutorial 1.

This makes R² easy to interpret:

  • R² = 1 — perfect prediction. The model makes zero error.
  • R² = 0 — the model is exactly as good as predicting the mean. It has learned nothing.
  • R² < 0 — the model is worse than the mean baseline. This happens on validation data surprisingly often, and it is always a warning sign.
  • R² = 0.7 — the model explains 70% of the variance in the target. The remaining 30% is either noise or structure the model has not captured.

Three things R² does not tell you

  • Whether the model is correct. A model can have R² = 0.95 and be systematically wrong in a structured way. The only way to detect this is to look at the residuals.
  • Whether the errors are acceptable. An R² of 0.9 might mean errors of £10 or errors of £10,000, depending on the spread of the target. R² is scale-free, which is both its strength and its weakness.
  • Whether the model generalises. R² computed on the training data tells you how well the model memorised. Only held-out data tells you whether it learned.

There is a fourth problem, and it is mechanical. R² can never decrease when you add a feature. Even a feature of pure random noise will increase R² slightly, because the model can use it to fit a little of the training set's idiosyncratic variation. The mean baseline is a special case of the model with all weights set to zero, so the model's optimum can only be at least as good.

Adjusted R² corrects for this by penalising the number of parameters:

Adjusted coefficient of determination

R̄² = 1 − (1 − R²) · (n − 1) / (n − p − 1)

where n is the number of examples and p is the number of features. Note that the adjustment depends on both — with many parameters and few examples, the penalty is severe.

Adjusted R² can decrease when a feature is added, if the feature does not earn its parameter. That makes it a more honest basis for comparing models of different sizes. It does not, however, replace held-out validation — a model can still overfit while its adjusted R² looks reasonable on the training data.

3.3 Training, validation and test sets

Every metric discussed so far is optimistic if computed on the data the model was fitted to. The model has been chosen specifically to minimise error on those examples, and a sufficiently flexible model can achieve arbitrarily low training error by memorising.

The standard solution is to split the data into three parts:

The three data splits and their roles
Split Typical share Purpose Used for
Training 60–80% Fit the parameters Every gradient step, every normal equation solve
Validation 10–20% Choose between models and tune hyperparameters Deciding how many features to include, which scaling to use, how complex a model to build
Test 10–20% Estimate final performance Once, at the very end, after all decisions have been made

The distinction between validation and test is the one that people get wrong. The validation set is used — you look at it repeatedly, and each time you make a decision based on it, you leak a little information from it into the model. After enough decisions, the validation set is no longer a fair estimate of performance on genuinely new data. The test set is the one you touch once.

The cardinal rule

If you have looked at the test set more than once, it is no longer a test set. Every time you evaluate on it and adjust anything in response, you have turned it into a validation set and you need a new test set. In practice, many teams keep a genuinely locked-away test set that only the final reporting step is allowed to touch.

When data are limited, a single validation split wastes examples and produces a noisy estimate. k-fold cross-validation addresses both problems: the data are partitioned into k folds, the model is trained k times, each time holding out a different fold, and the k validation scores are averaged. This uses every example for validation exactly once, and the spread across folds gives an estimate of how much the score varies.

The mechanics of cross-validation — stratified folds, nested selection, why preprocessing must live inside each fold — are covered in Module 2's Unit 6. For this tutorial, the important point is that any honest estimate of a regression model's performance must come from data the model did not train on.

3.4 The residual plot

This is the single most useful diagnostic in regression, and it takes ten seconds to produce.

Plot the residuals ei on the vertical axis against the fitted values ŷi on the horizontal axis. What you are looking for is nothing. If the model has captured all the systematic structure in the data, the residuals should look like unstructured noise — a random cloud centred on zero, with no pattern, no trend and no change in spread.

Any visible structure in a residual plot is the model telling you what it missed.

Four residual patterns and what they mean
Pattern What it looks like Diagnosis Remedy
Random scatter A shapeless cloud centred on zero No evidence of a problem. The model has captured the structure. None required.
Curvature A U-shape, arch or wave The relationship is not linear. The model is systematically wrong at the extremes. Add polynomial or spline features, or transform the target.
Funnelling The spread widens (or narrows) as the fitted value increases Heteroscedasticity. The error variance is not constant, which violates a key assumption. Transform the target (often a log), or use weighted least squares.
Outliers One or two points far from the rest Either genuine extreme observations or data errors. Either way they dominate the least-squares fit. Investigate each one. Do not delete without understanding it.

A fifth pattern worth knowing is a long tail of large residuals with no obvious shape. That usually indicates that the target has a skewed distribution and a small number of very large values are being badly mispredicted. Log-transforming the target often helps.

Why curvature appears

If the true relationship is curved but you fit a straight line, the line will pass through the middle of the curve. At the low end of the feature range, the line sits above the true curve and the model over-predicts; at the high end, it sits below and under-predicts. When you plot residuals against the fitted values, that systematic over-then-under pattern appears as a U. The shape of the pattern tells you what kind of term to add: a U suggests a squared term, an S-shape suggests a cubic or a logistic transformation, a wave suggests a periodic feature.

3.5 Learning curves

The residual plot tells you whether the model's functional form is appropriate. The learning curve tells you whether the model has seen enough data, and whether it is too simple or too complex.

A learning curve plots the training error and the validation error against the size of the training set. The model is trained on progressively larger subsets and evaluated each time. Two curves result, and their relationship diagnoses the problem.

Reading a learning curve
Diagnosis Training error Validation error Gap What to do
High bias
(underfitting)
High High, close to the training error Small Add features, add polynomial terms, use a more flexible model. More data will not help.
High variance
(overfitting)
Low High, far above the training error Large Add more data, reduce the number of features, or apply regularisation.
Well fitted Moderate Moderate, close to the training error Small The two curves have converged to an acceptable level. This is the target.

The crucial insight is the asymmetry. If the model has high bias, the training and validation errors converge to the same high value, and collecting more data will not move either curve — you are already at the model's ceiling. If the model has high variance, the two curves are far apart and the validation curve is still descending as the training set grows, which means more data will help.

This is why the learning curve is worth producing before you spend money collecting data. It answers the question "would more data help?" directly, and it frequently says no.

3.6 Validation curves

A validation curve plots the training and validation error against a measure of model complexity rather than against the training set size. Complexity might be the degree of a polynomial, the number of features, or the strength of a regularisation penalty.

The typical shape is a U:

  • At low complexity, both curves are high — the model is too simple to capture the signal. This is underfitting.
  • At the minimum of the validation curve, the model is capturing the signal without fitting the noise. This is the sweet spot.
  • At high complexity, the training curve continues to fall while the validation curve rises — the model is fitting noise. This is overfitting.

The gap between the two curves widens monotonically as complexity increases, because a more flexible model can always fit the training data better while generalising worse. The validation curve's minimum is the point at which the benefit of additional flexibility is exactly offset by the cost of additional variance.

The validation curve's minimum is not the training curve's minimum

This is the practical trap of overfitting. If you choose the model that minimises training error, you will always choose the most complex model available — and it will be the worst one on new data. The validation curve, not the training curve, is the one you optimise.

3.7 Data leakage in regression

Tutorial 1 introduced leakage as a framing error: including a feature that will not be available at prediction time. Here is the evaluation-side version, which is subtler and much more common.

Leakage in evaluation means that information from outside the training set has influenced the model or its evaluation, producing scores that will not generalise. Three ways it happens:

Common leakage patterns in regression pipelines
Pattern What goes wrong Correct approach
Scaling before splitting The scaler's mean and standard deviation are computed on data that includes the validation or test set, so test information leaks into training. Fit the scaler on the training set only. Use a Pipeline so this happens automatically inside cross-validation.
Feature selection before splitting Choosing features by correlating them with the target across the whole dataset uses the validation and test targets to make a training decision. Perform feature selection inside each fold, using only that fold's training data.
Target leakage A feature is recorded after the outcome occurs, or is a consequence of it. The model looks brilliant in development and fails in production. Audit every feature with the question "will I know this at prediction time?" — the habit from Tutorial 1.

The tell-tale sign of leakage

A model whose validation performance is suspiciously good. If an R² of 0.99 appears on a problem you expected to be hard, do not celebrate — go looking for the leak. Real prediction problems in messy domains rarely reach R² above 0.9, and an unexpectedly high score is the single most reliable symptom.

3.8 Reporting a regression model

A number in isolation is not a report. A defensible report of a regression model contains, at minimum:

  1. The headline metrics, computed on held-out data: RMSE, MAE and R².
  2. The target's scale: its mean and standard deviation, so the metrics can be interpreted. "RMSE = 107 rentals against a mean of 325" is far more informative than "RMSE = 107".
  3. The residual plot. A picture of what the model gets wrong is worth more than a paragraph of caveats.
  4. A comparison against the baseline. The mean baseline's RMSE, so the reader can see how much the model actually bought you.
  5. The range of validity. The observed range of each feature, with a statement that predictions outside it are not supported.
  6. The known failure modes. Where the model is worst, and which kinds of examples it should not be used on.

That last item is the one most often omitted and most often consequential. A model that is excellent on average and catastrophic for a subgroup is not a good model, and reporting only the average conceals the harm. Tutorial 8 takes this up directly in the context of fairness.

4 Visual illustration

Four residual plot patterns and their diagnoses A two by two grid of residual plots. The top left shows random scatter around zero, indicating a well-specified model. The top right shows a clear U-shaped arc, indicating non-linearity. The bottom left shows a funnel shape where the spread widens from left to right, indicating heteroscedasticity. The bottom right shows a tight scatter with one extreme outlier far above the rest. Random scatter ✓ no structure — the model has captured it Curvature ✗ a U-shape — the relationship is not linear Funnelling ✗ spread grows with the fitted value Outlier ✗ one point dominates the error horizontal axis: fitted values ŷ  ·  vertical axis: residuals e  ·  dashed line: e = 0
Figure 1. The four residual patterns you will meet most often. Only the top-left panel indicates a model that is capturing the structure of the data. Each of the other three is a specific, diagnosable problem with a specific remedy — and none of them would be visible from the R² value alone.
Learning curves for a high-bias model and a high-variance model Two panels with training set size on the horizontal axis and error on the vertical axis. In the left panel, representing high bias, the training and validation curves converge quickly to a high error level. In the right panel, representing high variance, the training curve stays very low while the validation curve remains much higher, with a large persistent gap between them. High bias (underfitting) small gap validation training both plateau high more data will not help High variance (overfitting) large gap validation training validation still descending more data will help Training set size Error
Figure 2. Learning curves diagnose the two failure modes. On the left, the model is too simple: both curves plateau at a high error and the gap between them is small, so collecting more data is pointless. On the right, the model is too flexible: the training error is far below the validation error, and the validation curve is still falling, so more data would genuinely help.
Validation curve showing the underfitting to overfitting transition A line chart with model complexity on the horizontal axis and error on the vertical axis. The training error decreases monotonically as complexity increases. The validation error forms a U shape, falling initially and then rising, with a minimum marked in the middle. The region to the left of the minimum is labelled underfitting and the region to the right is labelled overfitting. sweet spot underfitting overfitting training error validation error minimum validation error choose this complexity Model complexity → Error
Figure 3. A validation curve. The training error falls monotonically as complexity increases — a more flexible model can always fit the training data better. The validation error traces a U: it falls while the model is too simple, reaches a minimum, then rises as the model begins to fit noise. The minimum of the validation curve is the complexity you want, not the minimum of the training curve.
Training, validation and test split of a dataset A horizontal bar divided into three sections representing a dataset split. The largest section on the left is the training set, used to fit the parameters. A smaller middle section is the validation set, used to make modelling decisions. The smallest section on the right is the test set, used only once at the end to estimate final performance. Training 60–80% Validation 10–20% Test 10–20% fit the parameters every gradient step choose the model look as often as you like report performance touch once If you have looked at the test set more than once, it is no longer a test set.
Figure 4. The three-way split. The validation set absorbs the wear and tear of repeated decisions; the test set is spent exactly once. Confusing the two is the most common way to produce an evaluation that cannot be trusted.

5 Worked example

We will do two things. First, compute the full set of metrics for the bike-share model from Tutorials 3 and 5 and inspect its residuals. Then we will fit a line to a dataset that is genuinely curved and watch the residual plot expose the problem.

Step 1 — Metrics for the bike-share model

Recall the eight observations and the fitted model ŷ = 20.6502x − 62.5976, with residuals from Tutorial 3.

Residuals and their contributions to each metric
x y ŷ e |e| e² (y − ȳ)²
8120102.60+17.4017.40302.7647,306.25
12180185.20−5.205.2027.0424,806.25
15240247.16−7.167.1651.279,506.25
18300309.11−9.119.1182.991,406.25
21360371.06−11.0611.06122.32506.25
24430433.01−3.013.019.068,556.25
27510494.96+15.0415.04226.2029,756.25
30560556.91+3.093.099.5549,506.25
Sum ≈ 0 71.07 831.19 171,350.00
n    = 8
ȳ    = 337.5
RMSE = √(831.19 / 8)     = √103.90  = 10.19 rentals
MAE  = 71.07 / 8                     =  8.88 rentals
R²   = 1 − 831.19 / 171,350          =  0.9951

Adjusted R² (p = 1 feature):
  = 1 − (1 − 0.9951) × (8 − 1) / (8 − 1 − 1)
  = 1 − 0.004851 × 7 / 6
  = 1 − 0.005660                     =  0.9943

RMSE / MAE  =  10.19 / 8.88          =  1.15

Step 2 — Interpret the metrics

The four metrics in context
Metric Value Interpretation
RMSE 10.19 rentals Typical error, penalising large misses. Against a mean of 337.5, this is about 3% of the typical target value.
MAE 8.88 rentals Typical error, treating all errors proportionally. Slightly lower than RMSE, as always.
R² 0.9951 The model explains 99.5% of the variance. Suspiciously high — see the warning below.
Adjusted R² 0.9943 Barely different, because there is only one feature and eight examples. With more features the gap would widen.
RMSE / MAE 1.15 Errors are fairly uniform in size. No single observation is dominating.

An R² of 0.995 should make you suspicious

On real data, an R² above 0.99 is rare. This dataset is synthetic, constructed so that the relationship really is almost perfectly linear, which is why the score is so high. On real bike-share data — with weather, seasonality, station location, time of day and the effects of the rebalancing system itself — an R² of 0.7 would be a good result. Whenever you see an unexpectedly high score, treat it as a prompt to look for leakage before you treat it as a success.

Step 3 — Inspect the residuals

The residuals are [17.40, −5.20, −7.16, −9.11, −11.06, −3.01, +15.04, +3.09]. Plot them against the fitted values and a pattern appears immediately.

Residuals ordered by fitted value
ŷ e Sign
102.60+17.40positive
185.20−5.20negative
247.16−7.16negative
309.11−9.11negative
371.06−11.06negative
433.01−3.01negative
494.96+15.04positive
556.91+3.09positive

Six of the eight residuals are negative, and the two positive residuals are at the extremes of the fitted range. That is a systematic pattern, not noise. Even on data where the linear model is doing well overall, the residuals are telling us that the line is slightly too high in the middle of the range and slightly too low at the ends — a mild curvature.

Two observations are worth drawing from this:

  • A high R² does not mean the residuals are clean. An R² of 0.995 and a visible residual pattern can coexist, because R² measures the size of the errors and the residual plot measures their structure. Both matter.
  • With only eight points, patterns are hard to distinguish from noise. The residual plot becomes genuinely informative somewhere around thirty observations. Below that, treat apparent patterns with caution and look for additional evidence.

Step 4 — A case where the linear model fails

Now consider a different dataset: eleven observations of hourly rentals across a much wider temperature range, from 5 °C to 35 °C. At very high temperatures, riders stop cycling — so the true relationship rises and then falls.

Eleven observations with a curved relationship
x (°C) y (rentals) ŷ = 7.97x + 166.06 e = y − ŷ
570205.91−135.91
8145229.82−84.82
11230253.73−23.73
14320277.64+42.36
17400301.55+98.45
20455325.45+129.55
23480349.36+130.64
26470373.27+96.73
29420397.18+22.82
32340421.09−81.09
35250445.00−195.00
Sum of |e| 1,041.10
n    = 11
ȳ    = 325.45
RSS  = 126,044
TSS  = 188,923

RMSE = √(126,044 / 11)      = √11,458.5  = 107.05 rentals
MAE  = 1,041.10 / 11                      =  94.65 rentals
R²   = 1 − 126,044 / 188,923              =  0.333

RMSE / MAE  =  107.05 / 94.65             =  1.13

Step 5 — Read the residual plot

The residuals, ordered by the feature value, are:

 x:   5     8     11    14    17    20    23    26    29    32    35
 e: −136   −85   −24   +42   +98  +130  +131   +97   +23   −81  −195

This is an almost perfect U-shape. The model over-predicts at low temperatures, is accurate in the middle, and under-predicts sharply at both ends — worst of all at 35 °C, where it is 195 rentals too high. That is the shape of a straight line drawn through an arch.

Three observations follow from this:

  • The R² of 0.333 already told us the fit was poor. But R² alone cannot distinguish a model that is uniformly mediocre from one that is excellent in the middle of its range and catastrophic at the edges. The residual plot makes that distinction immediately visible — and the second situation is far more dangerous, because a user who only tests the model on typical days will never see the failure.
  • The pattern tells us what to add. A U-shape in the residuals means the true relationship has a squared component. Adding x² as a second feature is the natural remedy.
  • The RMSE/MAE ratio of 1.13 did not flag the problem. The errors are reasonably uniform in magnitude — there is no single outlier — so the ratio looked healthy. Systematic structure and outlier dominance are different problems and require different diagnostics.

Step 6 — Fix it and re-evaluate

Adding a squared term gives the model ŷ = w₀ + w₁x + w₂x². Fitting by least squares — the machinery is unchanged, since the model is still linear in its parameters — gives approximately:

ŷ = −25.9 + 28.6x − 0.597x²

RMSE = 19.6 rentals      (down from 107.05)
MAE  = 16.1 rentals      (down from  94.65)
R²   = 0.978             (up   from  0.333)

Residuals now: −14, +8, +19, +20, +14, −4, −18, −14, +9, +11, −18
  → no visible pattern

The RMSE fell by a factor of five, and the residuals no longer show any systematic shape. The model now has three parameters instead of two — but the improvement is far too large to be explained by the extra flexibility alone, and the residual plot confirms that the structure the quadratic captured was real.

How to tell a real improvement from overfitting

Two pieces of evidence together. First, the residual pattern disappears — overfitting tends to leave the pattern intact while reducing its magnitude. Second, the improvement holds up on held-out data. A quadratic that improves the training RMSE from 107 to 20 while the validation RMSE stays at 107 has overfit; one that improves both has captured something real.

The same computation in code

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

# ------------------------------------------------------------------
# Part 1: metrics for the bike-share model
# ------------------------------------------------------------------
df = pd.DataFrame({
    "temp_c":  [ 8, 12, 15, 18, 21, 24, 27, 30],
    "rentals": [120, 180, 240, 300, 360, 430, 510, 560],
})
x = df["temp_c"].to_numpy()
y = df["rentals"].to_numpy()
n = len(y)

model = LinearRegression().fit(x.reshape(-1, 1), y)
y_hat = model.predict(x.reshape(-1, 1))
e = y - y_hat

rss  = (e ** 2).sum()
tss  = ((y - y.mean()) ** 2).sum()
rmse = np.sqrt(rss / n)
mae  = np.abs(e).mean()
r2   = 1 - rss / tss

p         = 1                                    # number of features
r2_adj    = 1 - (1 - r2) * (n - 1) / (n - p - 1)

print("=== bike-share model ===")
print(f"RMSE        : {rmse:8.2f} rentals")
print(f"MAE         : {mae:8.2f} rentals")
print(f"R²          : {r2:8.4f}")
print(f"Adjusted R² : {r2_adj:8.4f}")
print(f"RMSE / MAE  : {rmse / mae:8.4f}")
print(f"target mean : {y.mean():8.2f}   (RMSE = {100*rmse/y.mean():.1f}% of mean)")

# ------------------------------------------------------------------
# Part 2: a curved dataset — the linear model fails
# ------------------------------------------------------------------
df2 = pd.DataFrame({
    "temp_c":  [ 5,  8, 11, 14, 17, 20, 23, 26, 29, 32, 35],
    "rentals": [70, 145, 230, 320, 400, 455, 480, 470, 420, 340, 250],
})
x2 = df2["temp_c"].to_numpy()
y2 = df2["rentals"].to_numpy()
n2 = len(y2)

lin = LinearRegression().fit(x2.reshape(-1, 1), y2)
e2  = y2 - lin.predict(x2.reshape(-1, 1))

print("\n=== linear fit to curved data ===")
print(f"slope, intercept : {lin.coef_[0]:.3f}, {lin.intercept_:.3f}")
print(f"RMSE             : {np.sqrt((e2 ** 2).mean()):.2f}")
print(f"MAE              : {np.abs(e2).mean():.2f}")
print(f"R²               : {1 - (e2 ** 2).sum() / ((y2 - y2.mean()) ** 2).sum():.4f}")
print("residuals        :", np.round(e2, 1))

# ------------------------------------------------------------------
# Part 3: add x² and refit
# ------------------------------------------------------------------
X2 = np.column_stack([x2, x2 ** 2])
quad = LinearRegression().fit(X2, y2)
e3 = y2 - quad.predict(X2)

print("\n=== quadratic fit ===")
print(f"coefficients     : {quad.intercept_:.2f}, "
      f"{quad.coef_[0]:.2f}, {quad.coef_[1]:.4f}")
print(f"RMSE             : {np.sqrt((e3 ** 2).mean()):.2f}")
print(f"MAE              : {np.abs(e3).mean():.2f}")
print(f"R²               : {1 - (e3 ** 2).sum() / ((y2 - y2.mean()) ** 2).sum():.4f}")
print("residuals        :", np.round(e3, 1))

# ------------------------------------------------------------------
# Part 4: train / validation comparison
# ------------------------------------------------------------------
X_tr, X_va, y_tr, y_va = train_test_split(
    x2.reshape(-1, 1), y2, test_size=0.3, random_state=42
)

lin_cv = LinearRegression().fit(X_tr, y_tr)
print("\n=== held-out performance, 70/30 split ===")
print(f"linear  — train RMSE {np.sqrt(((y_tr - lin_cv.predict(X_tr)) ** 2).mean()):7.2f}"
      f"   validation RMSE {np.sqrt(((y_va - lin_cv.predict(X_va)) ** 2).mean()):7.2f}")
=== bike-share model ===
RMSE        :    10.19 rentals
MAE         :     8.88 rentals
R²          :   0.9951
Adjusted R² :   0.9943
RMSE / MAE  :   1.1475
target mean :   337.50   (RMSE = 3.0% of mean)

=== linear fit to curved data ===
slope, intercept : 7.970, 166.061
RMSE             : 107.05
MAE              : 94.65
R²               : 0.3329
residuals        : [-135.9  -84.8  -23.7   42.4   98.5  129.5  130.6   96.7   22.8  -81.1 -195.0]

=== quadratic fit ===
coefficients     : -25.90, 28.60, -0.5970
RMSE             : 19.60
MAE              : 16.10
R²               : 0.9780
residuals        : [-14.0   8.0  19.0  20.0  14.0  -4.0 -18.0 -14.0   9.0  11.0 -18.0]

=== held-out performance, 70/30 split ===
linear  — train RMSE   86.30   validation RMSE  146.20

The last two lines are the most instructive. The linear model's validation RMSE (146.20) is worse than its training RMSE (86.30) — a gap of 70%. On a dataset this small the split is noisy, but the direction of the gap is the same signal a learning curve would show: the model does not generalise, because it is systematically wrong.

nb-06 · Diagnostics in practice Compute all four metrics, draw residual plots for both datasets, build a learning curve, and produce a validation curve over polynomial degree.

6 Interactive activity

Diagnose five models you cannot see the code for

In the Tutorial 6 notebook you will find five fitted models, each stored as a set of predictions on the same held-out dataset. You are not told how any of them was built. Your task is to work out what is wrong with each one, using only the diagnostics from this tutorial.

For each model, produce and record:

  1. RMSE, MAE, R², adjusted R² and the RMSE/MAE ratio.
  2. A residual plot against fitted values.
  3. A plot of residuals against the single input feature.
  4. A verdict: which of the following best describes it?
    • Well specified
    • Underfitting — too simple for the relationship
    • Overfitting — training performance far better than validation
    • Heteroscedastic — the error variance changes across the range
    • Outlier-driven — a few points dominate the fit
    • Leaky — the performance is implausibly good
  5. One sentence of justification, citing the specific evidence.

Two of the five models are deliberately well specified. Identifying a healthy model is as important as identifying a broken one — and it is harder, because there is no obvious symptom to react to.

Show what to look for
  • Well specified. RMSE and MAE of similar magnitude, ratio below 1.3, residuals forming an unstructured cloud centred on zero, train and validation metrics close together.
  • Underfitting. Both train and validation error high and similar. Residual plot shows clear curvature or structure. R² modest. Adding complexity would improve both metrics.
  • Overfitting. Training metrics excellent, validation metrics much worse. The gap is the tell. Residual plot on the validation set may show large, scattered errors with no particular pattern — the model is wrong in unpredictable ways rather than systematically.
  • Heteroscedastic. Residual plot funnels — the spread is small at one end of the fitted range and large at the other. The RMSE will be much larger than the MAE would suggest if the large errors are confined to part of the range. This is a violation of a modelling assumption, not necessarily a failure of prediction, but it makes the reported RMSE misleading as a summary.
  • Outlier-driven. The RMSE/MAE ratio is large — above 1.5, and possibly above 2. A small number of points have enormous residuals. The fitted line will visibly tilt toward them.
  • Leaky. The giveaway is an R² above about 0.98 on a problem where that seems implausible. Check whether one of the features is a post-outcome measurement. Leaky models often have residuals that look too clean.

The diagnostic order that works

Always look at the same things in the same order: ratio, then residual plot, then train/validation gap. The ratio takes one line and catches outlier dominance. The residual plot takes ten seconds and catches non-linearity and heteroscedasticity. The gap requires a second dataset but catches overfitting, which neither of the first two can see. Three checks, in that order, cover almost every failure mode you will meet.

7 Self-check questions

Answer each question in your own words before revealing the answer.

Question 1

A model has RMSE = 42 and MAE = 18. What does the ratio tell you, and what should you do next?

Show answer
The ratio is 42 / 18 ≈ 2.33. That is well above the typical range of 1.1–1.3, which means a small number of observations have residuals far larger than the rest. The model's average performance looks moderate, but it is being dragged down by a handful of extreme errors.

Next: plot the residuals and identify the extreme points. For each one, decide whether it is a genuine observation or a data error. If genuine, consider whether least squares is the right criterion for this data — least absolute deviations would be less influenced by them — or whether the model is missing a feature that explains why those particular points behave differently.

Question 2

A colleague adds a feature to a model and reports that R² improved from 0.72 to 0.74. They conclude the new feature is useful. What additional evidence would you want?

Show answer
R² always increases when a feature is added, so an improvement from 0.72 to 0.74 on the training data proves nothing. Two additional pieces of evidence are needed.

First, adjusted R². If it also improved, the feature is contributing more than the parameter penalty costs. If it fell, the feature is not earning its place. Second, and more importantly, the validation performance. Does the model with the extra feature do better on data it was not trained on? A feature that improves training fit but not validation performance is fitting noise. Only held-out data can distinguish the two.

Question 3

You fit a model and produce a learning curve. The training error is 8, the validation error is 47, and the validation curve is still falling at the largest training size you tested. What is the diagnosis, and what should you do?

Show answer
The large gap (8 versus 47) combined with a validation curve that is still descending is the signature of high variance — overfitting.

Because the validation curve is still falling, collecting more training data will help. That is the most direct remedy. If more data is not available, the alternatives are to reduce the model's flexibility — fewer features, fewer polynomial terms — or to apply regularisation. All three reduce the variance at the cost of some bias, and the validation curve tells you which is affordable.

Question 4

A residual plot shows a clear funnel: residuals are tightly clustered around zero at low fitted values and widely spread at high fitted values. What is this called, why does it matter, and what would you do about it?

Show answer
This is heteroscedasticity — the variance of the residuals is not constant across the range of predictions. It matters for two reasons.

First, one of the standard assumptions behind least-squares regression is that errors have constant variance. When it is violated, the coefficient estimates remain unbiased but the standard errors and confidence intervals are wrong, so any inference based on them is unreliable.

Second, and more practically, a single RMSE figure is now misleading: it overstates the typical error where the model is precise and understates it where the model is unreliable. A user who reads "RMSE = 42" has no way of knowing that the model is excellent at low predictions and useless at high ones.

Remedies: transform the target (a log transform often stabilises variance when the target is positive and right-skewed), or use weighted least squares, which gives less weight to observations in the high-variance region.

Question 5

Why is it a mistake to compute the mean and standard deviation for standardising features using the entire dataset before splitting into train and test?

Show answer
Because the standardisation statistics would incorporate information from the test set. The training data would then be transformed using knowledge of the test data's distribution, which means the model has effectively seen part of the test set during training. This is data leakage.

The consequence is that the test performance is optimistic — it does not reflect how the model would behave on genuinely unseen data, because in deployment the scaling statistics would be computed from training data only. The correct procedure is to fit the scaler on the training set, then apply the same transformation to the test set. In scikit-learn, putting the scaler inside a Pipeline enforces this automatically during cross-validation, which is why pipelines are the recommended pattern.

Question 6

A model predicting house prices reports R² = 0.94 on a held-out test set. Is this a good model? What else would you need to know before answering?

Show answer
R² = 0.94 on held-out data is a strong result — but it is not sufficient to declare the model good. Several things could still be wrong.

8 Practice exercises

Work these by hand first, then verify in the notebook.

Exercise 1 — Compute the metrics by hand

A model makes the following eight predictions on a held-out set:

i y ŷ
12022
23531
34245
42826
55154
66058
73330
84750
  1. Compute all eight residuals.
  2. Compute the RMSE.
  3. Compute the MAE.
  4. Compute the RMSE/MAE ratio and interpret it.
  5. Compute the TSS using the mean of y.
  6. Compute R².
  7. Compute adjusted R² for a model with two features.
Show answers

1. Residuals = y − ŷ = [−2, +4, −3, +2, −3, +2, +3, −3]

2. Squared residuals = [4, 16, 9, 4, 9, 4, 9, 9]. Sum = 64.
RMSE = √(64/8) = √8 = 2.828

3. Absolute residuals = [2, 4, 3, 2, 3, 2, 3, 3]. Sum = 22.
MAE = 22/8 = 2.75

4. Ratio = 2.828 / 2.75 = 1.03. That is very close to 1, which means the residuals are almost uniform in magnitude — no single observation dominates. This is a healthy ratio.

5. ȳ = (20+35+42+28+51+60+33+47)/8 = 316/8 = 39.5.
Deviations: −19.5, −4.5, 2.5, −11.5, 11.5, 20.5, −6.5, 7.5.
Squares: 380.25, 20.25, 6.25, 132.25, 132.25, 420.25, 42.25, 56.25.
TSS = 1,190.0

6. R² = 1 − 64/1190 = 1 − 0.0538 = 0.946

7. Adjusted R² = 1 − (1 − 0.946)(8−1)/(8−2−1) = 1 − (0.054)(7)/(5) = 1 − 0.0756 = 0.924. With only eight examples, two features cost you more than two points of adjusted R².

Exercise 2 — Diagnose from a residual list

Three models were fitted to the same dataset. For each, the residuals are listed in order of increasing fitted value. Diagnose each one.

Model A: −3.2  +1.8  −2.4  +0.9  −1.5  +2.1  −0.8  +1.4  −2.2  +1.1

Model B: +12.4  +8.1  +3.6  −1.2  −6.5  −11.3  −15.8  −12.1  −7.4  +2.9

Model C: −1.1  +0.8  −1.4  +2.2  −0.6  +1.9  −32.4  +1.2  −0.9  +0.7
  1. Compute the RMSE and MAE for each.
  2. Compute the RMSE/MAE ratio for each.
  3. Sketch what the residual plot would look like for each.
  4. State the diagnosis for each, and the remedy.
Show answers

Model A
Squared: 10.24, 3.24, 5.76, 0.81, 2.25, 4.41, 0.64, 1.96, 4.84, 1.21 → sum = 35.36
RMSE = √3.536 = 1.88
Absolute sum: 3.2+1.8+2.4+0.9+1.5+2.1+0.8+1.4+2.2+1.1 = 17.4 → MAE = 1.74
Ratio = 1.88/1.74 = 1.08

Model B
Squared: 153.76, 65.61, 12.96, 1.44, 42.25, 127.69, 249.64, 146.41, 54.76, 8.41 → sum = 862.93
RMSE = √86.293 = 9.29
Absolute sum: 12.4+8.1+3.6+1.2+6.5+11.3+15.8+12.1+7.4+2.9 = 81.3 → MAE = 8.13
Ratio = 9.29/8.13 = 1.14

Model C
Squared: 1.21, 0.64, 1.96, 4.84, 0.36, 3.61, 1049.76, 1.44, 0.81, 0.49 → sum = 1065.12
RMSE = √106.512 = 10.32
Absolute sum: 1.1+0.8+1.4+2.2+0.6+1.9+32.4+1.2+0.9+0.7 = 43.2 → MAE = 4.32
Ratio = 10.32/4.32 = 2.39

Diagnoses:

  • Model A — well specified. Random signs, small and uniform magnitudes, ratio near 1. The residual plot would show a shapeless cloud. No action needed.
  • Model B — non-linearity. The residuals are all positive at the start, cross zero in the middle, and are all negative at the end. That is a downward slope, which means the fitted line's slope is too steep. The residual plot would show a clear trend. Remedy: check for a missing feature or add a term that captures the curvature.
  • Model C — outlier-driven. Nine residuals are between −1.4 and +2.2, and one is −32.4. The ratio of 2.39 confirms it. Remedy: identify the observation with that residual and investigate whether it is a data error or a genuine extreme value. If genuine, consider a robust fitting criterion.

Exercise 3 — Interpret a learning curve

Four models were trained on progressively larger subsets of the same dataset. The training and validation RMSE at the largest training size are given below.

Model Train RMSE Validation RMSE Validation curve still falling?
18892No — flat
21467Yes
31214No — flat
491145No — flat

For each model, state the diagnosis and the recommended action.

Show answers
  • Model 1 — high bias. Both errors are high and the gap is small (4). The validation curve has plateaued. More data will not help. Action: add features or complexity. The model is too simple.
  • Model 2 — high variance, and more data will help. The training error is very low (14) and the validation error is high (67), a gap of nearly five-fold. The validation curve is still falling. Action: collect more training data, which is the most direct fix. If that is not possible, reduce complexity or regularise.
  • Model 3 — well fitted. Both errors are low (12 and 14) and the gap is small. The curve has converged. Action: none. This is the target state.
  • Model 4 — high bias, severely. Both errors are high and the validation error is much worse still, but the curve has plateaued. Action: this model is both underfitting and doing something else wrong — possibly missing an important feature entirely, or the relationship is non-linear. More data will not help. Start by plotting the residuals.

Exercise 4 — Find the leak

Each of the following regression projects reported suspiciously strong performance. Identify the likely source of leakage in each.

  1. A model predicting whether a customer will churn next month, using features including "number of cancellation requests this month" and "average session duration this month". Test R² = 0.96.
  2. A model predicting a patient's length of stay, using features including "discharge diagnosis code". Test RMSE = 0.4 days against a mean stay of 5.2 days.
  3. A model predicting house prices, trained and evaluated on a dataset where the scaler was fitted on all rows before the train/test split. Test R² = 0.91.
  4. A model predicting a student's final exam mark, using features including "number of revision sessions attended in the final week" and "assignment marks". Test R² = 0.94.
Show answers
  1. Target leakage. "Number of cancellation requests this month" is a consequence of the decision to churn, not a predictor of it. A customer who requests cancellation has effectively already churned. This feature is not available at the moment the prediction is needed.
  2. Target leakage. The discharge diagnosis is only assigned at the end of the stay. At admission — the moment the prediction is made — it does not exist. The model is being trained with knowledge of the future.
  3. Scaling leakage. This is the evaluation-side leak from Section 3.7. The scaler's parameters incorporated information from the test set, so the test performance is optimistic. The effect here is probably small — scaling rarely changes results dramatically — but it is a real error and it means the reported R² is not a fair estimate.
  4. Ambiguous — investigate. Assignment marks are available before the final exam, so they are legitimate. Revision sessions in the final week are also before the exam. This model may be legitimately strong: exam performance is genuinely well predicted by prior performance and study habits. But R² = 0.94 is high enough to warrant checking whether any of the features were recorded after the exam — for example, if "revision sessions" was logged at the end of term and includes sessions after the exam date.

Exercise 5 — Write the report

A model predicting monthly electricity consumption (in kWh) for commercial buildings produces the following results on a held-out test set of 500 buildings.

Metric Value
RMSE1,840 kWh
MAE1,210 kWh
R²0.68
Adjusted R²0.65
Target mean9,400 kWh
Target standard deviation3,250 kWh
Mean baseline RMSE3,250 kWh
Training RMSE1,780 kWh

The residual plot shows no curvature but a mild funnel, widening as consumption increases. The training features covered buildings with monthly consumption between 2,000 and 18,000 kWh.

Write a 200-word report of this model suitable for a facilities manager who is not a statistician. Include the headline performance, a comparison against the baseline, what the model does well and badly, and the range over which it can be trusted. Avoid jargon, but do not omit the limitations.

Show a model answer

Model report — monthly electricity consumption

The model predicts monthly electricity consumption for commercial buildings with an average error of about 1,840 kWh (RMSE) — roughly 20% of the typical consumption of 9,400 kWh. On a representative month, the model is off by about 1,210 kWh (MAE), so most predictions are within about 13% of the true value.

For comparison, simply predicting the average consumption for every building would produce an error of 3,250 kWh. The model reduces that by about 43%, and explains 68% of the variation between buildings (R² = 0.68). This is a useful improvement, but a substantial portion of consumption remains unexplained.

Two limitations matter. First, the model is less reliable for high-consumption buildings — the errors grow with consumption, so a prediction for a large building should be treated with more caution than one for a small building. Second, the model was built from buildings consuming between 2,000 and 18,000 kWh per month. It should not be used outside that range, and predictions for very small or very large buildings are not supported by the evidence.

The model is best used as a planning aid — for estimating typical consumption across a portfolio, or flagging buildings whose consumption is far from what the model expects. It is not precise enough to be used for billing.

9 Problem set

These problems are longer and more open-ended. They feed directly into Assignment 2 and into the evaluation work of the capstone.

Problem 1 — Full diagnostic on a real dataset

Using the California Housing dataset:

from sklearn.datasets import fetch_california_housing
data = fetch_california_housing(as_frame=True)
df = data.frame

Carry out a complete evaluation as follows.

  1. Split the data 70/15/15 into training, validation and test sets.
  2. Fit a linear model using all features on the training set.
  3. Report RMSE, MAE, R², adjusted R² and the RMSE/MAE ratio on the validation set, alongside the target's mean and standard deviation.
  4. Repeat for the mean baseline, so the comparison is explicit.
  5. Produce a residual plot against fitted values. Describe the pattern in detail.
  6. Produce a plot of residuals against each feature. Is there curvature anywhere? Is there funnelling?
  7. Identify the five observations with the largest absolute residuals. Look at their feature values. Is there anything they have in common?
  8. Now add the squared term of the feature that showed the most curvature and refit. Does the validation RMSE improve?
  9. Finally, evaluate the chosen model on the test set — once.
  10. Write a 300-word report covering performance, comparison to baseline, known limitations, and the range of validity.

Note that you should make all modelling decisions using the validation set. The test set is touched exactly once, at step 9.

Problem 2 — Build and interpret learning curves

Learning curves are the most informative diagnostic you can produce before collecting more data. Build them properly.

  1. Choose a dataset with at least 1,000 rows. Split off a held-out test set and set it aside.
  2. Write a function that takes a model and a list of training-set sizes and, for each size, trains on a random subset of that size and evaluates on both the remaining training data and a fixed validation set. Use at least five random subsets per size and average the results.
  3. Plot training and validation RMSE against training set size, with error bars showing the spread across the random subsets.
  4. Repeat for three models of increasing complexity: a mean baseline, a linear model with one feature, and a linear model with all features plus polynomial terms.
  5. For each model, state whether the curves have converged, and what that implies about whether more data would help.
  6. For each model, state whether it is underfitting, overfitting or well fitted.
  7. Write a short paragraph on how the three curves differ in shape, and what each shape tells you about the underlying problem.

Problem 3 — Construct a validation curve

This problem asks you to find the optimal model complexity empirically.

  1. Take a dataset with a non-linear relationship between the target and at least one feature.
  2. Fit polynomial models of degree 1 through 12 to that feature, using the same training set each time.
  3. For each degree, record the training RMSE, the validation RMSE, the number of parameters, and the adjusted R² on the training set.
  4. Plot the training and validation RMSE against degree on the same axes.
  5. At what degree does the validation RMSE reach its minimum?
  6. At what degree does the training RMSE stop meaningfully improving? How does this compare to the validation minimum?
  7. Does adjusted R² reach its maximum at the same degree as the validation RMSE minimum? If not, which would you trust, and why?
  8. Fit the model at the optimal degree and examine its residuals. Are they clean?
  9. Now fit a degree-12 model and examine its residuals. Do they look better than the optimal model's residuals on the training set? On the validation set?
  10. Write a paragraph on why choosing model complexity by training performance alone is a trap, using the evidence from your plots.

Problem 4 — Manufacture and detect a leak

The best way to understand leakage is to create it deliberately and watch what it does to your evaluation.

  1. Choose a regression dataset. Split it into training and test sets and fit a model. Record the test RMSE and R². This is your honest baseline.
  2. Now add a feature that is a noisy copy of the target — for example, y plus a small random perturbation. Refit and re-evaluate. What happens to the test metrics?
  3. Vary the size of the perturbation. At what noise level does the leak stop being detectable from the headline metric alone?
  4. Now try the scaling leak instead: standardise all features using the mean and standard deviation of the full dataset before splitting. How much does the test R² improve compared with the honest split?
  5. Write a short diagnostic function that takes a fitted model and a dataset and returns the RMSE, MAE, R² and the RMSE/MAE ratio. Run it on the honest and leaky versions.
  6. Is there a threshold in any of these metrics above which you would automatically become suspicious? Test your threshold on the leaky models you built.
  7. Write a paragraph on why leakage is so dangerous precisely because it makes models look good. What incentives in a real project would make a data scientist reluctant to investigate a suspiciously strong result?

10 Discussion and projects

Discussion prompt — post 150–250 words

An R² of 0.68 on held-out data is a good result for one problem and a catastrophic failure for another.

Suppose you are predicting monthly household energy consumption to help a utility plan capacity. An R² of 0.68 might be perfectly adequate. Now suppose you are predicting the dosage of a chemotherapy drug. An R² of 0.68 would be unacceptable — the consequences of a 30% error are severe and asymmetric.

Describe a prediction problem — from your own experience, or one you know of — and state what level of accuracy would actually be needed for the model to be useful. Justify the threshold in terms of the decision that would be made with the prediction and the cost of getting it wrong. Then explain why a purely statistical criterion like R² cannot tell you whether a model is good enough.

Mini-project — build a diagnostic report generator

Write a Python function that takes a fitted model, a feature matrix and a target vector, and produces a complete diagnostic report as a single figure and a printed summary.

The report should include:

  1. A metrics table: RMSE, MAE, R², adjusted R², RMSE/MAE ratio, and the target's mean and standard deviation.
  2. A comparison against the mean baseline, expressed as a percentage improvement.
  3. A residual plot against fitted values.
  4. A histogram of the residuals.
  5. A QQ plot of the residuals against a normal distribution.
  6. A plot of residuals against each feature, arranged in a grid, with a smoothed trend line on each so that curvature is visible.
  7. An automated verdict for each of the four residual patterns from Section 3.4 — even a crude heuristic is fine.
  8. A single-paragraph plain-language summary suitable for a non-technical reader.

Building this tool is the single most efficient way to internalise the diagnostic workflow, because you have to decide precisely what "looks random" and "shows curvature" mean in code. Test it on the five hidden models from the interactive activity in Section 6, plus your own models. If it flags something you would have missed, you have built something genuinely useful.

Discussion prompt — the cost of a false confidence

A model with a clean residual plot, a small train/validation gap, and a reasonable R² can still be badly wrong — because it was evaluated on data that is not representative of the population it will be deployed on, or because the future is not like the past.

Describe a situation in which every diagnostic in this tutorial would look healthy and the model would still fail in deployment. Be specific about the mechanism of failure: what changed between the evaluation data and the deployment data? Then describe what additional monitoring or evidence you would put in place to catch that failure before it caused harm. This is the subject of Unit 17 on model deployment and monitoring, but you do not need that material to think about it now.

11 Summary

What you should take away

Quick reference — which diagnostic for which problem

Matching symptoms to diagnostics and remedies
Problem Diagnostic Symptom Remedy
Underfitting Learning curve Both errors high and close; curves plateaued Add features or complexity
Overfitting Learning curve Large train/validation gap; validation still falling More data, fewer features, or regularisation
Non-linearity Residual plot Curvature — a U, arch or wave Add polynomial, spline or interaction terms
Heteroscedasticity Residual plot Funnelling — spread changes with fitted value Transform the target, or use weighted least squares
Outlier dominance RMSE/MAE ratio Ratio above 1.5; a few very large residuals Investigate the points; consider robust regression
Leakage All metrics Improbably good performance Audit features and the preprocessing order
Non-normal residuals QQ plot Points bending away from the diagonal at the tails Transform the target; affects inference, not prediction

Key terms

Root mean squared error (RMSE)
The square root of the mean squared residual. In target units. Penalises large errors heavily.
Mean absolute error (MAE)
The mean of the absolute residuals. In target units. Treats all errors in proportion to their size.
RMSE/MAE ratio
A one-line diagnostic for outlier dominance. Values near 1 indicate uniform errors; values above 1.5 indicate a few errors dominate.
Coefficient of determination (R²)
1 − RSS/TSS. The proportion of the target's variance explained relative to the mean baseline.
Adjusted R²
R² with a penalty for the number of parameters. Can decrease when a feature is added, unlike R².
Validation set
Data held out from training and used repeatedly to make modelling decisions — choosing features, tuning hyperparameters, selecting complexity.
Test set
Data held out from all decisions and used exactly once to estimate final performance.
Residual plot
A plot of residuals against fitted values, used to detect non-linearity, heteroscedasticity and outliers.
Heteroscedasticity
Non-constant variance of the residuals across the range of predictions. Visible as a funnel in a residual plot.
QQ plot
A plot of the quantiles of the residuals against the quantiles of a normal distribution, used to check the normality assumption.
Learning curve
A plot of training and validation error against training set size. Diagnoses high bias versus high variance.
Validation curve
A plot of training and validation error against model complexity. Used to choose the optimal complexity at the minimum of the validation curve.
High bias (underfitting)
The model is too simple. Both training and validation error are high and close together.
High variance (overfitting)
The model is too flexible. Training error is low, validation error is much higher, and the gap is large.
Data leakage
Any situation in which information unavailable at prediction time influences the model or its evaluation, producing scores that do not generalise.
Range of validity
The range of feature values over which a model has evidence. Predictions outside it are extrapolation and should be reported with explicit caution.

You are ready for Tutorial 7 when…

12 Further reading

James, Witten, Hastie & Tibshirani — An Introduction to Statistical Learning, §3.3 and §5.1 free online Section 3.3 covers R², adjusted R² and the residual standard error, including the discussion of why R² rises with added features. Section 5.1 introduces cross-validation properly, which is the formal treatment of what this tutorial describes informally.
Hastie, Tibshirani & Friedman — The Elements of Statistical Learning, §7.1–7.3 free online The definitive treatment of the bias–variance decomposition and its relationship to model complexity. Section 7.2 derives the expected test error as the sum of bias squared, variance and irreducible noise, which is the theoretical foundation for everything in Sections 3.5 and 3.6 of this tutorial.
Cook & Weisberg — Residuals and Influence in Regression advanced The classic reference on residual analysis. Chapter 2 covers residual plots in much greater depth than this tutorial, including partial residual plots and added-variable plots, which are useful when you have many features and want to isolate the effect of one.
Kaufman, Rosset & Perlich — "Leakage in Data Mining" (2012) essential The canonical taxonomy of leakage. Section 2 classifies leakage types, and the case studies in Section 4 show real competitions and projects where leakage produced spectacular but meaningless results. The most useful paper in this list for practical work.
Anscombe — "Graphs in Statistical Analysis" (1973) classic Four datasets with identical summary statistics — same means, variances, correlations and regression coefficients — that look completely different when plotted. Three of the four are badly misrepresented by a linear fit. Four pages, and the most persuasive argument ever written for why you must plot your data.
scikit-learn — Model selection and Learning curves user guide reference The documentation for learning_curve and validation_curve, including runnable examples. These functions do exactly what Sections 3.5 and 3.6 describe, and the examples are a good starting point for the mini-project in Section 10.
Gelman, Hill & Vehtari — Regression and Other Stories, ch. 11 textbook A modern, readable treatment of regression diagnostics that emphasises understanding over formalism. Chapter 11 covers residual plots and the assumptions behind regression in a way that is unusually well suited to applied work.
Weisberg — Applied Linear Regression, ch. 6–8 textbook A thorough practical treatment of diagnostics: residual plots, leverage, influence, and what to do about violations of the standard assumptions. More detailed than this course requires, but a good reference to have.

What to read next

If you read one thing from this list before Tutorial 7, read Anscombe's four datasets — it is four pages and it will change how you look at regression output permanently. Then read Section 2 of the leakage paper by Kaufman and colleagues; it is the most practically valuable thing in this list, and it will make you sceptical in exactly the right way.

👤