Lesson 18 of 227 min
Time series and forecasting
Test a forecast the way you will use it, week after week on hours it has not seen, and keep it only if it beats copying last week.
After this lesson you can split by time, beat a naive baseline, and say what a pretrained forecasting model adds.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Pick the test that matches the job
Get hour.csv and day.csv from UCI Bike Sharing. We fill missing hours with zero, including the Sandy shutdown. In a live feed, check whether a gap means zero rentals or a missing reading.
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import TimeSeriesSplit, train_test_split
hourly = pd.read_csv("hour.csv", parse_dates=["dteday"])
hourly["time"] = hourly["dteday"] + pd.to_timedelta(hourly["hr"], unit="h")
hourly = hourly.set_index("time").asfreq("h").loc[:"2012-12-30"]rentals = hourly["cnt"].fillna(0)
X = pd.DataFrame({"hour": hourly.index.hour, "weekday": hourly.index.day_of_week})
X.index = hourly.index
for name in ["workingday", "holiday"]:
X[name] = hourly[name].groupby(hourly.index.normalize()).transform(lambda s: s.ffill().bfill())
X["workingday"] = X["workingday"].fillna(pd.Series(X.index.day_of_week < 5, index=X.index))
X["holiday"] = X["holiday"].fillna(0)
X["month"] = X.index.month
X["last_week"] = rentals.shift(168)
X["two_weeks_ago"] = rentals.shift(336)X, rentals = X.iloc[336:], rentals.iloc[336:]
def error(past, test):
model = HistGradientBoostingRegressor(random_state=0)
model.fit(X.iloc[past], rentals.iloc[past])
return mean_absolute_error(rentals.iloc[test], model.predict(X.iloc[test]).clip(min=0))
past, test = train_test_split(np.arange(len(X)), test_size=0.2, random_state=0)
walk = TimeSeriesSplit(n_splits=13, test_size=168)
print(round(error(past, test), 1), round(np.mean([error(a, b) for a, b in walk.split(X)]), 1))41.8 63.3
The shuffled score comes first. Adding year, month and day helps the trees place a shuffled hour among its neighbors.
Use the weather you knew on Monday
At the start of a week you know next Friday's calendar. For weather, you only have the prediction issued by then. Score with an archive of those predictions, one issue time per forecast date, or leave weather out. temp in the UCI data is the weather that happened.
weather = pd.DataFrame({"issued_at": pd.to_datetime(["2012-10-01", "2012-10-04"]),
"valid_on": pd.to_datetime(["2012-10-05"] * 2),
"high_c": [20, 23]})
monday = pd.Timestamp("2012-10-01")
known = weather.loc[weather["issued_at"] <= monday].sort_values("issued_at")
print(known.drop_duplicates("valid_on", keep="last")["high_c"].tolist())[20]
Give Chronos the holiday calendar
Chronos-2 can take a calendar for the week ahead in future_df. Give it the same holiday column in the history so it can see what happened on earlier holidays. Here are seven days at Thanksgiving. cnt comes from the historical rows alone. Install chronos-forecasting first. Chronos-2 model card
from chronos import Chronos2Pipeline
days = pd.read_csv("day.csv", parse_dates=["dteday"]).sort_values("dteday")
cut = pd.Timestamp("2012-11-19")
calendar = days.assign(item_id="capital").rename(columns={"dteday": "timestamp"})
history = calendar.loc[calendar["timestamp"] < cut, ["item_id", "timestamp", "holiday", "cnt"]]
future = calendar.loc[calendar["timestamp"] >= cut, ["item_id", "timestamp", "holiday"]].head(7)
model = Chronos2Pipeline.from_pretrained("amazon/chronos-2", device_map="cpu")
pred = model.predict_df(history, future_df=future, target="cnt", prediction_length=7,
quantile_levels=[0.1, 0.5, 0.9])Leave room for late data
If a count arrives two hours after it happened, leave two rows out of the end of each hourly training split. Check your lag columns too. gap moves the end of training, and each feature still has to be available when you make the forecast. TimeSeriesSplit
gapped = TimeSeriesSplit(n_splits=13, test_size=168, gap=2)
past, week = next(gapped.split(X))
print(X.index[past[-1]], X.index[week[0]])2012-09-30 21:00:00 2012-10-01 00:00:00
Keep each station's past together
For one forecast per station, give each station its own ID. Make the lag inside each station and keep a single date cutoff for all of them. One set of trees can train across stations with an encoded station column. With Chronos-2, each station becomes an item_id in the same input table.
stations = pd.DataFrame({"station": ["A", "A", "B", "B"],
"date": pd.to_datetime(["2012-10-01", "2012-10-08"] * 2),
"rentals": [40, 52, 5, 11]})
stations = stations.sort_values(["station", "date"])
stations["last_week"] = stations.groupby("station")["rentals"].shift(1)
print(stations.loc[stations["date"] == "2012-10-08", ["station", "last_week"]].to_dict("records"))[{'station': 'A', 'last_week': 40.0}, {'station': 'B', 'last_week': 5.0}]Score the range as well
A well-calibrated 10th-to-90th-percentile band covers about 80% of observations. Ours covered 67% of the video's hours. RMSE gives big misses more weight. To compare station sizes, divide each station's MAE by its baseline MAE when positive.
actual = calendar[["timestamp", "cnt"]].merge(pred, on="timestamp")
inside = actual["cnt"].between(actual["0.1"], actual["0.9"])
print(f"Thanksgiving week: {inside.sum()} of {len(inside)} days inside")Thanksgiving week: 4 of 7 days inside
Run on Python 3.13.3, pandas 3.1.1, scikit-learn 1.9.1 and chronos-forecasting 2.3.2. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Data leakage
A hospital's model predicts who will be admitted. One of its columns is "days in hospital". On a test set it never saw, its score is excellent. What is wrong?
2 of 3
The bike trees, with last week's hours as inputs, are tested two ways. On hours picked at random, they're off by 42 bikes an hour. Walked forward, week by week, by 63. Which miss should you expect next week?
3 of 3
The calendar's model learned the hour, the day, the holidays and the month from 2011, with nothing that says which year. 2012 is much busier. Walked forward in October 2012, its forecasts come out:
The ideas in this lesson
- The naive forecast
- A series that repeats each day and week can be forecast by copying the same hour last week; a model must beat it.
- Walk-forward testing
- Pick a moment, use only what came before it, forecast what comes next, score it, move forward, and average the scores.
- A pretrained forecaster
- A model trained in advance on many series reads your past values and forecasts the next ones with no training of its own.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Time series
Here's a bet. These are two years of bike rentals, hour by hour. One forecast just copies last week. Another is a model. It learned the hour, the day and the month from the past. Which one forecasts next week better?
Keep your guess
Hold on to your guess.
These are the bikes rented each hour of 2011 and 2012. They come from a bike-share program in Washington, D.C.
Numbers like these, measured one after another in time, are called a time series.
Seasons
Here are two weeks of those bike rentals, up close.
Each workday has two peaks: eight in the morning, and five in the evening. Those are the trips to work and back home.
On Saturday and Sunday, there's one long rise in the middle of the day.
Your own week probably looks like this too.
Every week repeats it, and every day too. A pattern that repeats like this is called a season.
And look at the whole picture. All of 2012 is busier than 2011.
Copy last week
Forecasting means guessing the coming hours from the past ones. The seasons give you the simplest forecast there is: copy the same hour from last week.
Take Monday, October first, at eight in the morning. Last Monday at eight, seven hundred and fifty bikes went out. So the copy says seven hundred and fifty. The real count was seven hundred and eighty-four.
This copy of last week is called the naive forecast. Any model has to beat it, before you use it.
Not hours at random
A forecast guesses the coming hours from the past ones. So how do you score one fairly? The usual test keeps some rows aside, picked at random. What goes wrong when the rows are hours?
Each test hour has neighbors: the hour before it, and the hour after it. They're in the training rows. So the model learns from hours that come after the hour it's tested on: the future. And its miss looks smaller than it really will be.
Walk forward
So test a forecast the way you'll use it. Pick a Monday. Use only the hours before it, forecast the week ahead, and score it once the week is over. Then move one week forward, and do it again. Here, thirteen weeks, from October to December 2012. This is called walking forward.
Its miss, week by week
The miss is how many bikes an hour a forecast is off, on average. Copying last week is off by seventy-six.
Always guessing the average of all the hours before is off by a hundred and fifty-eight. But look at the weeks. The copy is off by thirty-five in one week, and by a hundred and thirty-six in another.
One week alone can give you the wrong idea. So you average all thirteen.
The calendar's model loses
Now, your guess.
The model is boosted trees that learned the hour, the day of the week, holidays and the month. Call it the calendar's model. Walked forward, it's off by eighty-seven... worse than the copy. Why? It knows the month, but not which year it is. So it guesses October from the only October it learned: October 2011. In the first week, it forecast a hundred and sixty-six bikes an hour, on average. That week really had two hundred and seventy-four. 2012 was busier.
The past as inputs
So give the trees two more columns: the same hour last week, and the same hour the week before. Will that be enough to beat the copy?
Off by sixty-three, lower than the copy's seventy-six. The past tells the trees this year's level. And scored on hours picked at random, these same trees would look off by forty-two. That's the future leaking in, in numbers.
A pretrained forecaster
Every forecast here is tested by walking forward, one week at a time.
Now, a different kind of model. It was trained in advance, on a lot of series of numbers from many places. It reads the hours before the Monday, and gives the week ahead, with a shaded range where most hours should fall. It has never been trained on bikes. This is a pretrained forecaster. Better or worse than the trees?
Off by fifty-nine. The best of all five. And all thirteen weeks took a few seconds.
What no past shows
Now look at the week of October twenty-ninth, 2012. What happened here?
Hurricane Sandy shut down the bikes. That whole Monday, there were twenty-two rentals.
For the day, the copy said about seven thousand. The pretrained forecaster said about six thousand two hundred. Every forecast missed.
Then the week after.
The copy copied the storm: twenty-two, for a normal Monday of about five thousand three hundred. The pretrained forecaster reads months of hours, and two empty days look like a short break to it.
No week in the past had a storm like this.
A forecast only knows what its past shows.
In code
In real code, with scikit-learn. TimeSeriesSplit, with thirteen splits of a hundred and sixty-eight hours, one week each, walks forward. The copy is one line: the same hour, a hundred and sixty-eight hours back.
In the loop, the trees learn from each week's past, and get scored on that week, alongside the copy.
The misses print: seventy-six for the copy, sixty-three for the trees.
The pretrained forecaster takes a few lines. Load it, give it the past hours, and ask for a hundred and sixty-eight more.
Off by fifty-nine.
Use the same test whenever you forecast: stock in a store, staff at a help desk, or bikes at a station.
Three ideas
So: copying last week is the forecast to beat. Test any forecast by walking forward, on weeks it hasn't seen. And a pretrained forecaster reads the past, and doesn't need any training of its own.
Test it week by week
So test a forecast week by week, and beat copying last week. Now try it on this lesson's page, and take the quiz. Find a week the calendar's model wins.
You use this lesson in Lab 7: Next week's bikes, and what the forecast leans on, after Feature importance and SHAP.
Facts last checked on .
