AI from scratch · Elective · Time series and forecasting
Time series and forecasting
How many people will ride the subway next Tuesday? How much power will the city draw tomorrow at 6 pm? How many orders will the warehouse ship next week? Forecasting is one of the most common jobs a junior ML engineer gets, and it breaks the rules most of this path took for granted: the examples aren't independent, the order matters, and the future may not look like the past. This lesson works on real data, every day of NYC subway ridership from March 2020 to January 2025: a pandemic collapse, a slow recovery, a weekly rhythm and the holidays.
Data: MTA Daily Ridership Data: 2020–2025, Metropolitan Transportation Authority, data.ny.gov (New York State open data).
1. A series has parts
daily riders 7-day average (the trend)
Look at the whole range, then zoom in. Three parts stack up: a trend (the collapse in spring 2020 to about 0.4 million a day and the climb back past 3 million), a season (every week: weekdays high, Saturdays lower, Sundays lowest), and events (holidays, storms). What's left is noise. The 7-day average smooths out exactly one week's season, so it shows the trend alone.
A time series is trend plus season plus events plus noise, and most of forecasting is modeling the first three.
2. Baselines that are hard to beat
Before any model, the simple forecasts, scored on October 2024 to January 2025 by mean absolute error (MAE: the average miss, in riders):
| Forecast for a day | MAE | Why it's that good or bad |
|---|---|---|
| Same as yesterday | 658,000 | Monday after a Sunday is off by a million |
| Average of the last 7 days | 713,000 | Throws away the weekly pattern entirely |
| Same weekday last week (seasonal naive) | 382,000 | Copies the weekly pattern; about 11% of an average 3.4 million day |
The seasonal naive forecast wins because ridership correlates 0.83 with the same day a week earlier, but only 0.49 with the day before. Any model you build has to beat it, by a margin you can measure; papers and teams that skip this step regularly publish models worse than "last week".
A forecast for hourly electricity use is scored against "same hour yesterday" and against "same hour last week". Which is likely the harder baseline to beat on weekdays?
- Same hour last week
- Same hour yesterday: a weekday follows a weekday with the same daily rhythm and nearly the same weather
- They're always equally hard
Score every forecast against the naive ones, especially "same time last season": they're surprisingly strong.
Why copying last week works so well
- Write a day's riders as \(y_t = \text{trend}_t + s_{w(t)} + \varepsilon_t\): a slowly moving trend, a weekday effect \(s\), noise.
- Same weekday last week: \(\hat y_t = y_{t-7} = \text{trend}_{t-7} + s_{w(t)} + \varepsilon_{t-7}\). The weekday effect is copied exactly.
- So the error is \(y_t - \hat y_t = (\text{trend}_t - \text{trend}_{t-7}) + (\varepsilon_t - \varepsilon_{t-7})\): a week of trend change plus two days of noise.
- Trends move slowly, so the first part is small; the second has twice the noise's variance (two independent days, Probability 4). That's the floor this baseline can't get under.
- Yesterday's value has the same noise term but a different weekday effect: \(s_{\text{Mon}} - s_{\text{Sun}}\) is about a million riders here. That's why it loses by so much.
3. Forecasting as regression: lags and calendars
Any regression model (chapter 13's boosted trees) can forecast, once each day becomes a row of features known in advance: lags (riders 7, 14, 21, 28 days before), rolling statistics (the average of the week before that), and the calendar (weekday, month, a holiday flag). For a forecast 7 days ahead every feature must be at least 7 days old: a lag of 1 would be the future.
About 285,000 against 382,000: a quarter better than last week. Without the holiday flag the same model scores 340,000, so one column bought half the gain. The biggest misses are still holidays: Thanksgiving, the Friday after it (not a federal holiday, so the flag doesn't know), Christmas Eve.
Forecasting becomes regression with features from the past (lags, rolling stats) and the calendar; every feature must be old enough for the forecast horizon.
4. Evaluating a forecast honestly
- Never shuffle. A random split puts tomorrow in the training data (features and leakage). Train on the past, test on what came after.
- Walk forward. One test window is one roll of the dice. Backtesting repeats it: train to March, test April; train to April, test May; and so on. Scikit-learn's
TimeSeriesSplitdoes this (toolkit 2). - Match the horizon. A model judged one day ahead but used two weeks ahead is judged on the wrong question; errors grow with the horizon (in the notebook: 227,000 a day ahead, 312,000 eight weeks ahead, though not smoothly in between: one test window is noisy).
- Give a range. A forecast with an interval ("3.1 to 3.6 million, 90% of the time") lets planners size trains. One simple way: the spread of the model's past errors on a recent validation window.
A team computes a centered 7-day moving average (3 days before, the day, 3 days after) and uses it as a feature to forecast tomorrow. What's wrong?
- A centered window includes days after the one being predicted: leakage from the future
- 7 days is too short
- Averages can't be features
Evaluate forecasts on the future only, repeatedly (walk-forward), at the horizon you'll use, and give a range, not just a number.
Where it breaks: the future that doesn't rhyme
- Regime changes. A model trained on 2019 would have forecast 5 million riders for April 2020; there were 0.4 million. No feature in the past predicts a pandemic, a strike or a new fare system. Watch errors (MLOps) and retrain on the new regime, or say plainly that the forecast doesn't cover shocks.
- Intervals from calm times. 90% intervals built from summer 2024's errors covered only 59% of the October–January days: the holidays make bigger errors than summer ever did. Build intervals from comparable seasons, and check their coverage.
- Moving holidays. Thanksgiving's date moves, Easter moves more, and Lunar New Year follows another calendar. A day-of-year feature can't see them; explicit holiday flags (and the days around them) can.
- Forecasts that change the future. If extra trains are scheduled because a crowd is forecast, the crowd may spread out, and next year's data reflects the response, not the demand.
5. What to carry forward
- Trend, season, events, noise: plot first, at several zoom levels.
- Beat the seasonal naive forecast, by a measured margin.
- Lags, trailing rolling stats and calendar features turn forecasting into regression; mind the horizon.
- Walk-forward evaluation, never shuffled; intervals checked for coverage.
- Shocks and moving holidays are where forecasts fail; monitor and say so.
All lessons: AI from scratch. Hyndman and Athanasopoulos, "Forecasting: Principles and Practice" (free online) is the standard text.
Last updated