Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

4.9 Time Series Forecasting

Forecasting means predicting the future values of a series from its past: atmospheric CO2_2, river discharge, glacier flow, groundwater levels. This notebook is a shootout. The model families of this book are pointed at one real series, evaluated on the same temporal split with the same metrics, and a table built in code decides.

ContestantFrom
Naive persistence and seasonal naivealways first
SARIMA (statsmodels)classical statistics
Gradient boosting on lag features (lightgbm)Chapter 3
A small LSTM and a small transformer encoder (torch)notebook 4.4

The series. Mauna Loa monthly CO2_2 (NOAA Global Monitoring Laboratory, 1958 to 2024): long, regular, strongly seasonal, with a smooth trend. Then three questions a single score hides: do the prediction intervals mean what they claim, where does skill run out with lead time, and are rare large events forecast at all (on a synthetic series where we know each event’s size).

The notebook ends with the class leaderboard: a public CO2_2 track (a diagnostic) and a hidden synthetic track (graded).

🖥️ Lecture slides — Session 26 (Wed Dec 2)

device: cpu

1. Data

1.1 Mauna Loa monthly CO2_2

The longest continuous direct measurement of atmospheric CO2_2, started by Charles Keeling in 1958. NOAA GML distributes monthly means as a text file; pooch downloads it once and caches it.

Downloading data from 'https://raw.githubusercontent.com/UW-MLGEO/MLGeo-dataset/main/data/data_co2.csv' to file '/home/runner/.cache/pooch/data_co2.csv'.
SHA256 hash of downloaded file: 871222f3f96a85edcbeeca8a5cc5beb7f8df1f20c9fb9cdcf98a186ecc3c32d1
Use this value as the 'known_hash' argument of 'pooch.retrieve' to ensure that the file hasn't changed if it is downloaded again in the future.
(798,) monthly values, 1958-03-01 to 2024-08-01

1.2 The leaderboard holdout: hands off the last 12 months

Before any modeling we remove the final 12 months, 2023-09 through 2024-08: they are the leaderboard holdout (section 6), scored once. Nothing before section 6 touches them.

holdout months: ['2023-09', '2023-10', '2023-11', '2023-12', '2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06', '2024-07', '2024-08']
working series: 1958-03-01 to 2023-08-01 (786 months)
<Figure size 1000x320 with 2 Axes>

A smooth, accelerating trend plus a sawtooth annual cycle: northern-hemisphere vegetation draws CO2_2 down each summer. A model that cannot beat “repeat last year’s shape” here has learned nothing.

2. Evaluation protocol

2.1 One temporal split for every model

A forecast is tested fairly only on data from after everything it was trained on. A random split lets the model interpolate between the neighbors of each test month, which inflates the score and predicts nothing. TEST is the final 48 months of the working series, 2019-09 through 2023-08; TRAIN is everything before. Every model forecasts the whole 48-month window in one go, without seeing any test value.

train 1958-03-01 .. 2019-08-01 (738 months), test 2019-09-01 .. 2023-08-01 (48 months)

2.2 Metrics

With forecast errors et=yt−y^te_t = y_t - \hat{y}_t over the nn test months:

MetricFormulaRead it as
MSE1n∑et2\frac{1}{n}\sum e_t^2squared units, dominated by large errors
RMSEMSE\sqrt{\mathrm{MSE}}data units, still dominated by large errors
MAE1n∑∣et∣\frac{1}{n}\sum \lvert e_t\rvertdata units, every error counts the same
MAPE100n∑∣et/yt∣\frac{100}{n}\sum \lvert e_t / y_t\rvertpercent; useless for series that cross zero
MASEMAE / MAE of the one-step naive forecast on the training seriesbelow 1: better than “repeat the last value”

MASE is unit-free and comparable across series, which is why the leaderboard uses it. One helper computes all five, and every table below is built from its output.

3. The shootout

3.1 Baselines first

  • Naive persistence: repeat the last training value over the 48 months.

  • Seasonal naive: repeat the last 12 training months four times. It copies last year’s shape but freezes the trend.

Your turn (1): the seasonal naive forecast

Write seasonal, an array of 48 values: the last 12 values of train_co2 repeated four times. One line, with np.tile and .values[-12:].

Answer below (click to open it).

Notebook Cell
naive -> {'MSE': np.float64(56.38), 'RMSE': np.float64(7.509), 'MAE': np.float64(6.679), 'MAPE (%)': np.float64(1.596), 'MASE': np.float64(6.09)}
seasonal naive -> {'MSE': np.float64(41.971), 'RMSE': np.float64(6.478), 'MAE': np.float64(5.961), 'MAPE (%)': np.float64(1.427), 'MASE': np.float64(5.436)}

3.2 SARIMA

SARIMA (seasonal ARIMA) models the differenced series with autoregressive and moving-average terms, plus seasonal counterparts at lag 12. We use the standard textbook order for Mauna Loa, (1,1,1)×(1,1,1)12(1,1,1)\times(1,1,1)_{12}: one regular difference for the trend, one seasonal difference for the annual cycle. We cap the optimizer iterations to keep the fit fast; this is a benchmark entry, not a tuning exercise.

SARIMA -> {'MSE': np.float64(0.129), 'RMSE': np.float64(0.359), 'MAE': np.float64(0.281), 'MAPE (%)': np.float64(0.067), 'MASE': np.float64(0.256)}

3.3 Gradient boosting on lag features

Tree ensembles know nothing about time. We hand them time explicitly, as a table where each row predicts one month from features built only from earlier months:

  • lags 1, 2, 3, 6, 12, 24 (the value kk months before the target),

  • the rolling mean of the 12 months before the target (i.e. shifted by one step so the target itself is excluded),

  • the calendar month (known in advance, so it is fair game).

One subtlety: a regression tree predicts averages of training targets, so it can never output a value outside the range it saw in training. CO2_2 keeps rising past every training value, so a tree that predicts the level saturates near the training maximum and the forecast goes flat. The fix is to predict the one-month change and add it to the previous value; monthly changes are roughly stationary and sit well inside the training range. The features stay the same past-only lags.

The model predicts one step ahead. To cover the 48-month test window we forecast recursively: predict the next change, add it to the last value, append that prediction to the history, build features again, and so on. Errors compound, which is honest; the model gets no real observations from the test period.

LightGBM -> {'MSE': np.float64(1.643), 'RMSE': np.float64(1.282), 'MAE': np.float64(1.03), 'MAPE (%)': np.float64(0.246), 'MASE': np.float64(0.939)}

3.4 A small LSTM

The deep models forecast directly: one forward pass maps a 36-month context window to all 48 horizon values at once (no recursion). Two practical points:

  • Anchoring. CO2_2 trends upward forever, so test windows sit at levels the network never saw in training. We subtract the last context value (“anchor”) from each window, train on the anchored shapes, and add the anchor back to the prediction. The network learns change relative to now, which is stationary enough to generalize.

  • Scaling. Anchored windows are divided by one global standard deviation from the training windows, keeping inputs O(1).

The model is small and trains for a few epochs; raise both on your own machine if you want.

655 training windows, scale = 3.35 ppm
LSTM -> {'MSE': np.float64(1.085), 'RMSE': np.float64(1.042), 'MAE': np.float64(0.886), 'MAPE (%)': np.float64(0.212), 'MASE': np.float64(0.808)}

3.5 A small transformer encoder

Same windows, same anchoring, same direct multi-step head; only the sequence model changes. We reuse the pattern from notebook 4.4: project each scalar to a small embedding, add sinusoidal positional encoding (attention itself is order-blind), run two encoder layers, average over time, and map to the 48 horizon values.

Transformer -> {'MSE': np.float64(0.262), 'RMSE': np.float64(0.511), 'MAE': np.float64(0.401), 'MAPE (%)': np.float64(0.096), 'MASE': np.float64(0.366)}
<Figure size 600x300 with 1 Axes>

3.6 The comparison

The table is built from results_co2, the dictionary that register() filled from the predictions.

Loading...
<Figure size 900x400 with 1 Axes>

What to look for:

  • Naive persistence ignores trend and season. Its MASE is large because a 48-month horizon is much harder than the one-step game MASE is scaled by.

  • Seasonal naive copies the annual shape but freezes the trend, so it drifts below the observations by about the trend times the horizon. It still beats some trained models.

  • SARIMA encodes exactly what this series is made of, a differenced trend and a 12-month cycle, in a handful of parameters. On this kind of series it is very hard to beat.

  • LightGBM, LSTM, transformer must learn trend and season from examples. Recursive feedback (LightGBM) and little training data (the deep pair) both cost accuracy over four years. Capacity is not the bottleneck; the structure of the problem is.

3.7 From point forecasts to intervals: the pinball loss, coverage, and CRPS

Every model so far answers “what will CO2_2 be?” with one number per month. No serious user of a forecast settles for that: a reservoir operator, a carbon-budget analyst, and every operational weather center ask for the range of outcomes and how probable each is. The machinery is a small change to what we already have.

A model learns the quantile qτq_\tau of the outcome when it is trained on the pinball loss (quantile loss)

Lτ(y,q)=max⁡(τ (y−q), (τ−1)(y−q)),\mathcal{L}_\tau(y, q) = \max\big(\tau\,(y - q),\ (\tau - 1)(y - q)\big),

which charges τ\tau per unit of under-prediction and 1−τ1-\tau per unit of over-prediction; the minimizer of its expectation is exactly the τ\tau-quantile. Predict q0.05q_{0.05} and q0.95q_{0.95} and you have a 90% prediction interval; q0.5q_{0.5} is a median point forecast for free.

We give the LSTM from 3.4 a quantile head: instead of 48 numbers it emits 48×1948 \times 19 — one per horizon step per quantile level 0.05,0.10,…,0.950.05, 0.10, \dots, 0.95 — trained on the pinball loss averaged over levels. Same windows, same anchoring, same epochs. That buys us a verifiable claim, and verification is the point:

  • Empirical coverage: over the 48 test months, how often does the observation actually fall inside the 90% interval? A calibrated forecast covers about 90%. Less means the model is overconfident; much more means the intervals are too wide to inform any decision. This is the same calibration discipline as the reliability curves of Chapter 3 and notebook 4.7, applied to intervals.

  • One wrinkle: quantile outputs trained independently can cross (q^0.40>q^0.45\hat q_{0.40} > \hat q_{0.45} for some month). Sorting along the quantile axis at prediction time is the standard one-line repair, and we apply it below.

Your turn (2): the coverage of the 90% interval

lo and hi hold the 5% and 95% quantiles for each of the 48 test months. Write inside, a boolean array that is True where the observation test_co2.values falls between lo and hi (inclusive). Its mean is the empirical coverage. One line.

Answer below (click to open it).

Notebook Cell
empirical coverage of the 90% interval: 91.7% (44/48 test months inside)
interval width: 2.30 ppm at 1 month -> 6.28 ppm at 48 months
<Figure size 900x400 with 1 Axes>

In this run the 90% interval catches 44 of 48 test months — 91.7% empirical coverage against a nominal 90%. That is a calibrated interval, and it was not guaranteed: quantile regression aims at calibration but nothing enforces it out of sample, which is why you compute coverage instead of asserting it. Two honest caveats. First, 48 consecutive months from a single forecast origin are strongly correlated, so this coverage estimate is itself noisy — a different test window could easily return 80% or 100%. Second, look at the printed widths: the interval grows from about 2.3 ppm at one month to about 6.3 ppm at four years. The model learned from the training windows that uncertainty compounds with lead time; nobody told it.

CRPS. Coverage checks one interval at one level. The continuous ranked probability score (CRPS) — the standard scoring rule of forecast verification, the number atmospheric ensemble systems report — scores the entire predictive distribution FF against the outcome yy:

CRPS(F,y)=∫−∞∞(F(z)−1{z≥y})2 dz  =  2∫01Lτ(y,qτ) dτ.\mathrm{CRPS}(F, y) = \int_{-\infty}^{\infty} \big(F(z) - \mathbf{1}\{z \ge y\}\big)^2\, dz \;=\; 2\int_0^1 \mathcal{L}_\tau\big(y, q_\tau\big)\, d\tau .

It has the units of the data (ppm here), and for a forecast collapsed to a single point it reduces exactly to the absolute error — so mean CRPS is directly comparable to a point forecast’s MAE, and it rewards both calibration and sharpness at once. The second identity is also the estimator: average the pinball loss over a dense quantile grid and double it. We already predict 19 quantiles, so the implementation is a few lines.

mean CRPS, quantile LSTM       : 0.766 ppm
MAE of its median (q50)        : 1.050 ppm
point forecasts (CRPS = MAE):
  LSTM        : 0.886 ppm
  SARIMA      : 0.281 ppm

Read the three numbers together. The quantile LSTM’s mean CRPS (0.766 ppm) beats the MAE of its own median forecast (1.051 ppm) and of the point-forecast LSTM from 3.4 (0.886 ppm): spreading probability over the range where the outcome may fall earns real score even when the center is imperfect. That comparison is the entire argument for probabilistic forecasting, in one line of output. But SARIMA’s point forecast still wins at 0.281 ppm — a well-placed point beats an honestly wide distribution. Calibration does not excuse a biased or diffuse center; the verification community’s slogan is sharpness subject to calibration, and the natural next contestant would be SARIMA’s own forecast distribution (get_forecast(...).conf_int() gives its intervals — try scoring them).

3.8 Error vs lead time: the skill horizon

A single 48-month MAE flattens an entire dimension of forecast quality: how fast skill decays with lead time. Atmospheric verification never reports one number; it reports error as a function of lead, because a model that is excellent at 1 month and useless at 12 serves different decisions than one that is mediocre everywhere.

We measure it with a rolling-origin evaluation, the way operational systems are scored. The models stay frozen exactly as trained on data through 2019-08 — no retraining. The forecast origin then slides month by month through the test window; at each origin the model sees the observed history up to that month (an operational forecaster always has the latest observations) and issues forecasts for leads 1 through 12. Averaging the absolute error at each lead over all origins gives an error-vs-lead-time curve — with 37 origins per lead rather than the single sample per lead that one 48-month forecast provides.

The vocabulary to take away: the skill horizon is the lead time beyond which a model stops beating the reference forecast (persistence, here). Beyond it, the model adds nothing over “no change”. Weather models hit their skill horizon around two weeks; the question is where these models hit theirs on CO2_2.

<Figure size 700x350 with 1 Axes>
seasonal naive  beats persistence at leads: [3, 4, 5, 6, 7, 8, 9]
LightGBM        beats persistence at leads: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
LSTM            beats persistence at leads: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

The curve and the printed check answer the skill-horizon question, and on CO2_2 the answer is the opposite of weather. Persistence degrades steadily with lead — the trend and the seasonal cycle pull the series ever further from “no change” — while the trained models’ error grows far more slowly. LightGBM and the LSTM beat persistence at every lead from 1 to 12 months: their skill horizon lies beyond a year, past the longest lead we measured. Weather models lose to climatology in about two weeks because atmospheric chaos destroys the information in the initial state; monthly CO2_2 keeps its skill because the structure that carries the forecast (trend plus annual cycle) never stops applying. The skill horizon is a property of the series as much as of the model.

The reference forecasts are still instructive. Seasonal naive beats persistence only at intermediate leads (3 through 9 in this run): at leads 1-2 last month’s value is simply very close to the truth, and near lead 12 persistence lands back in the same season, closing most of the gap. So even the choice of reference depends on lead time — one more reason a single-number summary of forecast skill hides more than it shows.

3.9 Is the ranking stable? Seed spread

Every number in the 3.6 table came from one training run; a table entry is a sample from a distribution over seeds, and reporting a sample as if it were the mean is the same sin as reporting a point forecast without an interval.

The seed sensitivity differs by model class, and that is part of the lesson:

  • naive, seasonal naive, SARIMA are deterministic: no seed, no spread.

  • LightGBM takes a random_state, but as configured here (no row or feature subsampling) the algorithm is deterministic too — the seed is an inert knob until you enable bagging. We run 5 seeds to demonstrate that, not to estimate a spread.

  • LSTM and transformer are stochastic twice over: weight initialization and batch shuffling (plus dropout, for the transformer). These are the entries whose table position you should distrust from a single run. They are also the slow entries, so we use 3 seeds each rather than 5 and say so.

Loading...

The spread table sharpens the 3.6 ranking rather than overturning it — and shows exactly where the randomness lives:

  • LightGBM posts the identical MASE for all five seeds (std 0.000), as promised: with no row or feature subsampling the algorithm is deterministic, and “we varied the seed” is evidence of robustness only when the algorithm actually consumes the seed.

  • LSTM spans 0.808-0.856 (mean 0.827, std 0.021); the transformer spans 0.327-0.403 (mean 0.356, std 0.034) — a tenth of its own mean, from initialization, batch order, and dropout alone.

  • The ranges do not overlap each other, SARIMA’s deterministic 0.256, or LightGBM’s 0.939, so on this run the shootout order survives the seeds. That conclusion now rests on evidence, and it is not a general law: on a short series the gaps between models can be the size of these spreads. Report mean and spread; let the reader see whether the gaps beat the noise.

4. Rare events break bulk metrics

The defining data problem of the geosciences is a field that varies smoothly for years and then does something extreme for three days: floods on a discharge record, eruptions on a tremor record, offsets on a strain record. Every metric in this notebook so far averages over all test samples, and quiet samples outnumber event samples by roughly twelve to one — so a model can post an excellent MAE while missing every event that matters.

To show this cleanly we need ground truth about the events, so we build the series ourselves with mlgeo_synth.inject_rare_events: eight years of a daily seasonal background, punctuated by ~6 events per year lasting 2-6 days, with amplitudes drawn from a generalized Pareto distribution (tail="gpd", shape ξ=0.5\xi = 0.5). That is a power-law tail — the extreme-value regime of real flood and surge records, where the variance is infinite and the largest event in any future window is routinely several times larger than the largest one yet observed. The generator returns an amplitude column: the true drawn size of each event, exactly the ground truth a bulk metric never sees.

The forecaster is deliberately given every advantage: one-step-ahead LightGBM (yesterday’s value is always in the feature set), trained on six years, tested on the last two. Then, instead of one MAE, we stratify the test error by the ground-truth amplitude.

                        n samples     MAE
all test samples              730   0.969
quiet (no event)              674   0.621
event, amplitude < 10          43   2.458
event, amplitude 10-25          7  10.577
event, amplitude >= 25          6  18.274

largest single miss: 50.8 (event amplitude 50.2)
<Figure size 1000x350 with 2 Axes>

A naive reading of the first row says the model is excellent: MAE 0.97 on a series whose seasonal swing alone is 6 units. The stratified rows tell the real story. Quiet days score 0.62 — the noise floor, as good as one-step forecasting gets. Small events (amplitude below 10) already cost 2.5. The seven samples in mid-size events cost about 10.6, the six samples in the largest events 18.3, and the single largest event — amplitude 50.2 — is missed by 50.8: the model predicted the seasonal background and the flood happened anyway. The right panel makes it systematic: peak error per event tracks the true amplitude along the error-equals-amplitude line. What the model has never seen, it misses in full.

Both causes are structural, not bugs. Event onsets are unpredictable from lag features — no yesterday-value tells you a spike starts tomorrow — and the GPD tail (ξ=0.5\xi = 0.5) guarantees that the test window contains amplitudes beyond every training example, so the model is extrapolating precisely on the samples that matter most. Meanwhile the bulk metric hides all of it: event samples are 56 of 730 test days (about one in thirteen), so the overall MAE (0.97) sits within a factor of 1.6 of the quiet-day floor while the top stratum is thirty times worse. A leaderboard scored on overall MAE would congratulate this model.

The repair is in the metric, not the model: if events are what your forecast exists for — floods, eruptions, offsets — score them separately. Stratified tables like this one, event-window recall, or amplitude-weighted losses all work; averaging over the quiet days does not. This is the same fair-evaluation discipline as the hidden leaderboard track below: what you measure is what you optimize, so measure the thing that matters.

5. Exercises

Exercise 1. In the CO2_2 LightGBM entry, remove lag_12 and lag_24 from the lag list and rerun. What happens to the MASE, and why?

Exercise 2. The deep models forecast all 48 months in one shot (direct multi-step); LightGBM predicts one month at a time and feeds predictions back in (recursive). Name one advantage of each strategy.

Exercise 3. Rerun section 4 twice: once with tail="uniform" (the generator’s default: amplitudes uniform on 5-20) and once keeping tail="gpd" but raising rate_per_year to 24. Which change does more for the large-event stratum, and what does that tell you about the difference between rare and heavy-tailed?

6. The class leaderboard: two tracks

Now the 12 months we removed in section 1.2 come back into play — but first, an honest disclosure about what a public leaderboard can and cannot measure.

Track A — CO2_2 (diagnostic).

  1. Produce a 12-month CO2_2 forecast for 2023-09 through 2024-08, the held-out months, using any model trained on data up to 2023-08 only. On your honor — see the box above for why cheating here only defeats the diagnostic.

  2. Save it to results/forecast_<uwnetid>.csv with exactly two columns: date (as YYYY-MM) and co2_ppm.

  3. Submit it via a pull request to the course book repository, https://github.com/geo-smart/mlgeo-book. CI scores each PR and posts the standings.

Scoring is MASE against the held-out months, scaled by the naive one-step MAE of the training series (the same convention as forecast_metrics in section 2.2 — the denominator comes from the pre-holdout record, not from the holdout itself).

Track B — the hidden synthetic series (graded). The file leaderboard/synth_forecast_history.csv in the course repository holds a daily displacement series from mlgeo_synth.gnss_series — secular trend, annual and semi-annual cycles, and colored noise, like the GNSS records of Chapter 2 — generated from a private seed and regenerated every year. Forecast the 90 days after the last history date and save results/forecast_hidden_<uwnetid>.csv with columns date (YYYY-MM-DD) and disp_mm, submitted in the same pull request. The truth series is never committed; the public leaderboard lists your submission as received, and the instructor’s run produces the scored table. Same metric: MASE, scaled by the history’s naive one-step error.

The cells below write an example file for each track using the recursive LightGBM model. Replace example with your UW NetID and the forecasts with your own.

wrote results/forecast_example.csv
   date  co2_ppm
2023-09   418.23
2023-10   418.42
2023-11   419.86
2023-12   421.29
2024-01   422.44
2024-02   423.25
2024-03   424.07
2024-04   425.49
2024-05   426.23
2024-06   425.65
2024-07   423.90
2024-08   421.89
history: 2832 days ending 2022-10-02; forecast 2022-10-03 .. 2022-12-31
wrote results/forecast_hidden_example.csv
Loading...

Summary

  • Baselines first: naive and seasonal naive set the bar, and MASE measures every model against the one-step naive forecast.

  • One temporal split, one metric helper, one table built in code.

  • On a long, structured series like CO2_2, a well-chosen classical model (SARIMA) is hard to beat; deep models need anchoring and scaling just to compete.

  • Recursive (LightGBM) and direct (LSTM, transformer) multi-step forecasting are a real design choice.

  • A point forecast is the start. A quantile head trained on the pinball loss gives an interval whose coverage you measure; CRPS scores the whole distribution on the scale of the MAE.

  • Error depends on lead time; plot it. The skill horizon is the lead at which a model stops beating persistence.

  • A ranking from one seed is one sample: report the mean and the spread over seeds.

  • A bulk MAE can look excellent while every large rare event is missed. Score events separately.

Reflection

Two or three sentences each.

  1. What you learned. Which result of the shootout surprised you most?

  2. What you learned from the agents. If an assistant wrote part of your leaderboard model, what did you check before submitting?

  3. How to improve it. What would make this notebook more useful for the forecasting part of your project?