CPSC 330 Lecture 19: Time series

Varada Kolhatkar

Focus on the breath!

Announcements

  • HW8 has been released (due next week Monday)
    • Almost there! You’ve got this! 😊
  • Midterm 2 grading is in progress.

Recap: iClicker

Select all of the following statements which are TRUE.

    1. Bag-of-words represents a document using word counts and preserves the order of its words.
    1. TF–IDF gives more weight to a term that is frequent in a document but rare across the collection.
    1. Dense retrieval can find relevant text even when the query and document use different words for the same idea.
    1. Supplying retrieved passages in a RAG prompt updates the generator’s learned weights.
    1. A RAG system can generate an unsupported answer even when it retrieves relevant evidence.

Recap: Which model would you use?

Scenario Model/Method
You have user–item ratings (e.g., movie ratings) and want to predict missing ratings. ?
You have a collection of documents without any labels and want to group them into themes. ?
You want to find catalog descriptions relevant to a customer’s question, even when they use different words for the same idea. ?
You have a small dataset with ~500 images containing pictures and names of 20 different Computer Science faculty members from UBC. Your goal is to develop a reasonably accurate multi-class classification model for this task. ?

Today’s big questions

  1. What changes when our data has a time order?
  2. How can we evaluate forecasts without using future information?
  3. How can we turn past observations and time patterns into useful features?
  4. How can we forecast multiple steps into the future?

Time order \(\to\) evaluation \(\to\) temporal features \(\to\) forecasting

Loan default prediction

Each row describes a customer applying for a loan. What type of model would you use to predict default?

Customer Income ($k) Credit used (%) Late payments Employment Default
1 95 22 0 Salaried 0
2 45 78 3 Contract 1
3 120 30 1 Salaried 0
4 60 65 2 Self-employed 1

Target: default (1 = yes, 0 = no). Customer ID identifies the row.

For this example, we treat customers as independent: reordering rows does not change the prediction task.

Predict demand for bike rentals

Suppose you want to predict the bike rental demand for the next three-hour period at a station in New York City.

What features might help us make an accurate prediction?

Citi Bike data

starttime
2015-08-01 00:00:00     3
2015-08-01 03:00:00     0
2015-08-01 06:00:00     9
2015-08-01 09:00:00    41
2015-08-01 12:00:00    39
2015-08-01 15:00:00    27
Freq: 3h, Name: one, dtype: int64
  • Recorded every three hours; each timestamp marks the start of a period.
  • Target: rental count during that period.
  • Initially, our only input is datetime.
  • Nearby rental counts may be related: time order matters.

Using only the tools in your current toolbox, what model would you choose, and what challenges might you run into?

What do we know when we predict?

At 09:00, predict rentals during 09:00–12:00.

Past observations Prediction time Target period
03:00–06:00 and 06:00–09:00 counts are known 09:00 09:00–12:00 count is unknown
  • Each timestamp labels the start of a three-hour rental period.
  • We already know the hour and day of the week for 09:00–12:00.
  • We can use rental counts from completed periods, such as 06:00–09:00.

Every feature must be available when we make the prediction.

Models for time series

Two broad approaches:

  • Use sequence models that explicitly model temporal relationships, such as Transformers.
  • Use tabular models with engineered temporal features, such as Ridge, random forests, and gradient boosted trees.

Today: give familiar tabular models useful information about time.

Citi Bike data visualization

Start date: 2015-08-01 00:00:00, End date: 2015-08-31 21:00:00

Do you see any daily patterns? Weekly patterns? Noise?

⛔️ Incorrect data splitting

train_df, test_df = train_test_split(citibike, test_size=0.2, random_state=123)
print('Train largest date: ', train_df.index.max())
print('Test smallest date: ', test_df.index.min())
Train largest date:  2015-08-31 21:00:00
Test smallest date:  2015-08-01 12:00:00

⛔️ We should never train on the future to predict the past!

✅ Correct data splitting

Use the first 23 days for development and hold out the last eight days for one final test. Choose features and models using temporal validation within the development period.

n_train = 184
train = train_df = rentals.iloc[:n_train]
test = test_df = rentals.iloc[n_train:]

Cross-validation with time series

  • Each validation window comes after its training window.
  • Use three expanding folds within the first 23 days; each validation window covers four days.
Time →   Training grows; validation moves forward
Fold 1   [Train: 11 days][Valid: 4 days]
Fold 2   [Train:     15 days][Valid: 4 days]
Fold 3   [Train:         19 days][Valid: 4 days]
cv = TimeSeriesSplit(n_splits=3, test_size=32)
for fold, (fit_rows, valid_rows) in enumerate(cv.split(train), start=1):
    print(f"Fold {fold}: train {fit_rows[0]}–{fit_rows[-1]}, "
          f"validate {valid_rows[0]}–{valid_rows[-1]}")
Fold 1: train 0–87, validate 88–119
Fold 2: train 0–119, validate 120–151
Fold 3: train 0–151, validate 152–183

The final eight-day test period is excluded from every fold.

How will we compare forecasts?

Mean absolute error (MAE) is the average absolute prediction error, measured in rentals per three-hour interval.

  • An MAE of 5 means predictions miss by five rentals on average.
  • Lower is better. Compare mean validation MAE over the same three folds.
  • Start with simple forecasts before fitting more complex models.

Simple forecasting baselines

  • Persistence: repeat the previous interval’s count (shift(1)).
  • Seasonal naive: repeat the same interval yesterday (shift(8)).
Previous interval          13.041667
Same interval yesterday     7.677083
Name: Validation MAE, dtype: float64

These are successive one-step forecasts: completed counts become available between predictions.

What does shift do?

shift(k) puts the value from \(k\) rows earlier alongside the current row.

shift_example = pd.DataFrame({
    "Original": rentals,
    "shift(1)": rentals.shift(1),
    "shift(8)": rentals.shift(8),
})
  • 1 row = 3 hours in this dataset.
  • 8 rows = 24 hours: the same interval yesterday.
  • Leading NaN values mean no earlier observation is available.
shift_example.head(12)
Original shift(1) shift(8)
starttime
2015-08-01 00:00:00 3 NaN NaN
2015-08-01 03:00:00 0 3.0 NaN
2015-08-01 06:00:00 9 0.0 NaN
2015-08-01 09:00:00 41 9.0 NaN
2015-08-01 12:00:00 39 41.0 NaN
2015-08-01 15:00:00 27 39.0 NaN
2015-08-01 18:00:00 12 27.0 NaN
2015-08-01 21:00:00 4 12.0 NaN
2015-08-02 00:00:00 3 4.0 3.0
2015-08-02 03:00:00 4 3.0 0.0
2015-08-02 06:00:00 6 4.0 9.0
2015-08-02 09:00:00 30 6.0 41.0

At a row labeled 2015-08-02 09:00:00, which earlier interval does shift(8) refer to?

Reading the model comparisons

  • Mean validation MAE: averaged over all three temporal folds.
  • Plots: the same final fold for every model, showing the last training week and four validation days.
  • Preprocessing: fitted only on each fold’s training rows, using pipelines.
  • Final test: reserved until we have selected a model.

Training fit shows what a model can represent; validation error shows what carries forward.

Feature engineering for time series

From timestamps to useful features

  • In this toy data, we just have a single feature: the date time feature.
  • Note that ML models do not have a built-in concept of time. We have to give it to them.
  • Start with a numeric timestamp, then add calendar patterns, interactions, and recent observations.

POSIX time feature

A simple numeric encoding is seconds since the Unix epoch, January 1, 1970, 00:00 UTC.

Will a random forest learn repeating demand from one increasing number?

calendar[["elapsed_seconds"]].head(6)
elapsed_seconds
starttime
2015-08-01 00:00:00 1438387200
2015-08-01 03:00:00 1438398000
2015-08-01 06:00:00 1438408800
2015-08-01 09:00:00 1438419600
2015-08-01 12:00:00 1438430400
2015-08-01 15:00:00 1438441200

Random forest with POSIX time

Mean cross-validation MAE: 11.40 rentals

The forest fits the training data, but predicts a constant for later timestamps. Why?

Trees cannot extrapolate!

  • Tree-based models only make predictions within the range of values they’ve seen during training.
  • Trees partition the feature space into fixed regions and predictions inside each region are averages of training labels.
  • If your future timestamps are larger than the ones in the training set trees cannot “see beyond” the training range and they will flatline or behave unpredictably.

This is exactly what happens with POSIX time encoded as a single numeric feature!

Seasonality

Seasonality refers to a repeating pattern that occurs at regular, predictable intervals.

  • Example 1: Bike rentals tend to peak at the same hours each day (daily seasonality).
  • Example 2: Retail sales consistently spike before the December holidays (annual seasonality).
  • Recognizing seasonality helps a model anticipate recurring patterns rather than mistake them for noise.
  • We can capture seasonality by adding features such as: rush_hour, is_weekend, and is_holiday

Extracting date and time information

  • Note that our index is of this special type: DateTimeIndex. We can extract all kinds of interesting information from it.
print(citibike.index[0])
print(citibike.index[0].month_name())
print(citibike.index[0].dayofweek)
print(citibike.index[0].hour)
2015-08-01 00:00:00
August
5
0

Hour of day

Hour-of-day values recur in future intervals, allowing a model to reuse daily patterns.

calendar[["hour"]].head(6)
hour
starttime
2015-08-01 00:00:00 0
2015-08-01 03:00:00 3
2015-08-01 06:00:00 6
2015-08-01 09:00:00 9
2015-08-01 12:00:00 12
2015-08-01 15:00:00 15

Random forest with hour of day

Mean cross-validation MAE: 6.97 rentals

The model repeats one daily profile. What weekday–weekend differences does it miss?

Hour of day + day of week

Add weekday so the model can distinguish a weekend afternoon from a weekday afternoon.

calendar_features = calendar[["hour", "weekday"]]
hour weekday
starttime
2015-08-01 00:00:00 0 5
2015-08-01 03:00:00 3 5
2015-08-01 06:00:00 6 5
2015-08-01 09:00:00 9 5
2015-08-01 12:00:00 12 5
2015-08-01 15:00:00 15 5
2015-08-01 18:00:00 18 5
2015-08-01 21:00:00 21 5
2015-08-02 00:00:00 0 6
2015-08-02 03:00:00 3 6
2015-08-02 06:00:00 6 6
2015-08-02 09:00:00 9 6
2015-08-02 12:00:00 12 6
2015-08-02 15:00:00 15 6
2015-08-02 18:00:00 18 6
2015-08-02 21:00:00 21 6
2015-08-03 00:00:00 0 0
2015-08-03 03:00:00 3 0
2015-08-03 06:00:00 6 0
2015-08-03 09:00:00 9 0
2015-08-03 12:00:00 12 0
2015-08-03 15:00:00 15 0
2015-08-03 18:00:00 18 0
2015-08-03 21:00:00 21 0
2015-08-04 00:00:00 0 1
2015-08-04 03:00:00 3 1
2015-08-04 06:00:00 6 1
2015-08-04 09:00:00 9 1
2015-08-04 12:00:00 12 1
2015-08-04 15:00:00 15 1
2015-08-04 18:00:00 18 1
2015-08-04 21:00:00 21 1
2015-08-05 00:00:00 0 2
2015-08-05 03:00:00 3 2
2015-08-05 06:00:00 6 2
2015-08-05 09:00:00 9 2
2015-08-05 12:00:00 12 2
2015-08-05 15:00:00 15 2
2015-08-05 18:00:00 18 2
2015-08-05 21:00:00 21 2
2015-08-06 00:00:00 0 3
2015-08-06 03:00:00 3 3
2015-08-06 06:00:00 6 3
2015-08-06 09:00:00 9 3
2015-08-06 12:00:00 12 3
2015-08-06 15:00:00 15 3
2015-08-06 18:00:00 18 3
2015-08-06 21:00:00 21 3
2015-08-07 00:00:00 0 4
2015-08-07 03:00:00 3 4
2015-08-07 06:00:00 6 4
2015-08-07 09:00:00 9 4
2015-08-07 12:00:00 12 4
2015-08-07 15:00:00 15 4
2015-08-07 18:00:00 18 4
2015-08-07 21:00:00 21 4
2015-08-08 00:00:00 0 5
2015-08-08 03:00:00 3 5
2015-08-08 06:00:00 6 5
2015-08-08 09:00:00 9 5
2015-08-08 12:00:00 12 5
2015-08-08 15:00:00 15 5
2015-08-08 18:00:00 18 5
2015-08-08 21:00:00 21 5
2015-08-09 00:00:00 0 6
2015-08-09 03:00:00 3 6
2015-08-09 06:00:00 6 6
2015-08-09 09:00:00 9 6
2015-08-09 12:00:00 12 6
2015-08-09 15:00:00 15 6
2015-08-09 18:00:00 18 6
2015-08-09 21:00:00 21 6
2015-08-10 00:00:00 0 0
2015-08-10 03:00:00 3 0
2015-08-10 06:00:00 6 0
2015-08-10 09:00:00 9 0
2015-08-10 12:00:00 12 0
2015-08-10 15:00:00 15 0
2015-08-10 18:00:00 18 0
2015-08-10 21:00:00 21 0
2015-08-11 00:00:00 0 1
2015-08-11 03:00:00 3 1
2015-08-11 06:00:00 6 1
2015-08-11 09:00:00 9 1
2015-08-11 12:00:00 12 1
2015-08-11 15:00:00 15 1
2015-08-11 18:00:00 18 1
2015-08-11 21:00:00 21 1
2015-08-12 00:00:00 0 2
2015-08-12 03:00:00 3 2
2015-08-12 06:00:00 6 2
2015-08-12 09:00:00 9 2
2015-08-12 12:00:00 12 2
2015-08-12 15:00:00 15 2
2015-08-12 18:00:00 18 2
2015-08-12 21:00:00 21 2
2015-08-13 00:00:00 0 3
2015-08-13 03:00:00 3 3
2015-08-13 06:00:00 6 3
2015-08-13 09:00:00 9 3
2015-08-13 12:00:00 12 3
2015-08-13 15:00:00 15 3
2015-08-13 18:00:00 18 3
2015-08-13 21:00:00 21 3
2015-08-14 00:00:00 0 4
2015-08-14 03:00:00 3 4
2015-08-14 06:00:00 6 4
2015-08-14 09:00:00 9 4
2015-08-14 12:00:00 12 4
2015-08-14 15:00:00 15 4
2015-08-14 18:00:00 18 4
2015-08-14 21:00:00 21 4
2015-08-15 00:00:00 0 5
2015-08-15 03:00:00 3 5
2015-08-15 06:00:00 6 5
2015-08-15 09:00:00 9 5
2015-08-15 12:00:00 12 5
2015-08-15 15:00:00 15 5
2015-08-15 18:00:00 18 5
2015-08-15 21:00:00 21 5
2015-08-16 00:00:00 0 6
2015-08-16 03:00:00 3 6
2015-08-16 06:00:00 6 6
2015-08-16 09:00:00 9 6
2015-08-16 12:00:00 12 6
2015-08-16 15:00:00 15 6
2015-08-16 18:00:00 18 6
2015-08-16 21:00:00 21 6
2015-08-17 00:00:00 0 0
2015-08-17 03:00:00 3 0
2015-08-17 06:00:00 6 0
2015-08-17 09:00:00 9 0
2015-08-17 12:00:00 12 0
2015-08-17 15:00:00 15 0
2015-08-17 18:00:00 18 0
2015-08-17 21:00:00 21 0
2015-08-18 00:00:00 0 1
2015-08-18 03:00:00 3 1
2015-08-18 06:00:00 6 1
2015-08-18 09:00:00 9 1
2015-08-18 12:00:00 12 1
2015-08-18 15:00:00 15 1
2015-08-18 18:00:00 18 1
2015-08-18 21:00:00 21 1
2015-08-19 00:00:00 0 2
2015-08-19 03:00:00 3 2
2015-08-19 06:00:00 6 2
2015-08-19 09:00:00 9 2
2015-08-19 12:00:00 12 2
2015-08-19 15:00:00 15 2
2015-08-19 18:00:00 18 2
2015-08-19 21:00:00 21 2
2015-08-20 00:00:00 0 3
2015-08-20 03:00:00 3 3
2015-08-20 06:00:00 6 3
2015-08-20 09:00:00 9 3
2015-08-20 12:00:00 12 3
2015-08-20 15:00:00 15 3
2015-08-20 18:00:00 18 3
2015-08-20 21:00:00 21 3
2015-08-21 00:00:00 0 4
2015-08-21 03:00:00 3 4
2015-08-21 06:00:00 6 4
2015-08-21 09:00:00 9 4
2015-08-21 12:00:00 12 4
2015-08-21 15:00:00 15 4
2015-08-21 18:00:00 18 4
2015-08-21 21:00:00 21 4
2015-08-22 00:00:00 0 5
2015-08-22 03:00:00 3 5
2015-08-22 06:00:00 6 5
2015-08-22 09:00:00 9 5
2015-08-22 12:00:00 12 5
2015-08-22 15:00:00 15 5
2015-08-22 18:00:00 18 5
2015-08-22 21:00:00 21 5
2015-08-23 00:00:00 0 6
2015-08-23 03:00:00 3 6
2015-08-23 06:00:00 6 6
2015-08-23 09:00:00 9 6
2015-08-23 12:00:00 12 6
2015-08-23 15:00:00 15 6
2015-08-23 18:00:00 18 6
2015-08-23 21:00:00 21 6
2015-08-24 00:00:00 0 0
2015-08-24 03:00:00 3 0
2015-08-24 06:00:00 6 0
2015-08-24 09:00:00 9 0
2015-08-24 12:00:00 12 0
2015-08-24 15:00:00 15 0
2015-08-24 18:00:00 18 0
2015-08-24 21:00:00 21 0
2015-08-25 00:00:00 0 1
2015-08-25 03:00:00 3 1
2015-08-25 06:00:00 6 1
2015-08-25 09:00:00 9 1
2015-08-25 12:00:00 12 1
2015-08-25 15:00:00 15 1
2015-08-25 18:00:00 18 1
2015-08-25 21:00:00 21 1
2015-08-26 00:00:00 0 2
2015-08-26 03:00:00 3 2
2015-08-26 06:00:00 6 2
2015-08-26 09:00:00 9 2
2015-08-26 12:00:00 12 2
2015-08-26 15:00:00 15 2
2015-08-26 18:00:00 18 2
2015-08-26 21:00:00 21 2
2015-08-27 00:00:00 0 3
2015-08-27 03:00:00 3 3
2015-08-27 06:00:00 6 3
2015-08-27 09:00:00 9 3
2015-08-27 12:00:00 12 3
2015-08-27 15:00:00 15 3
2015-08-27 18:00:00 18 3
2015-08-27 21:00:00 21 3
2015-08-28 00:00:00 0 4
2015-08-28 03:00:00 3 4
2015-08-28 06:00:00 6 4
2015-08-28 09:00:00 9 4
2015-08-28 12:00:00 12 4
2015-08-28 15:00:00 15 4
2015-08-28 18:00:00 18 4
2015-08-28 21:00:00 21 4
2015-08-29 00:00:00 0 5
2015-08-29 03:00:00 3 5
2015-08-29 06:00:00 6 5
2015-08-29 09:00:00 9 5
2015-08-29 12:00:00 12 5
2015-08-29 15:00:00 15 5
2015-08-29 18:00:00 18 5
2015-08-29 21:00:00 21 5
2015-08-30 00:00:00 0 6
2015-08-30 03:00:00 3 6
2015-08-30 06:00:00 6 6
2015-08-30 09:00:00 9 6
2015-08-30 12:00:00 12 6
2015-08-30 15:00:00 15 6
2015-08-30 18:00:00 18 6
2015-08-30 21:00:00 21 6
2015-08-31 00:00:00 0 0
2015-08-31 03:00:00 3 0
2015-08-31 06:00:00 6 0
2015-08-31 09:00:00 9 0
2015-08-31 12:00:00 12 0
2015-08-31 15:00:00 15 0
2015-08-31 18:00:00 18 0
2015-08-31 21:00:00 21 0

Random forest with hour of day + day of week

Mean cross-validation MAE: 4.36 rentals

Compare validation MAE with the hour-only model. Does adding weekday help?

Ridge with hour of day + day of week

Mean cross-validation MAE: 10.00 rentals

One coefficient for hour imposes the same change per hour. Can that describe morning and evening peaks?

One-hot encoding hour and day

Learn a separate effect for each hour and weekday category.

calendar_ridge = make_pipeline(
    OneHotEncoder(handle_unknown="ignore", sparse_output=False),
    Ridge(),
)

The pipeline fits the encoder separately inside each training fold. One-hot encoding does not explicitly encode closeness across midnight.

Ridge with one-hot calendar features

Mean cross-validation MAE: 6.93 rentals

One-hot encoding gives each hour its own effect, but the 09:00 effect is still the same on Monday and Sunday.

Add interaction features

Does 09:00 mean the same rental demand on Monday and Sunday?

Interactions add features for combinations such as 09:00 × Monday and 09:00 × Sunday.

interaction_ridge = make_pipeline(
    OneHotEncoder(handle_unknown="ignore", sparse_output=False),
    PolynomialFeatures(interaction_only=True, include_bias=False),
    Ridge(),
)

A feature that switches on only on Monday at 09:00

Multiply the two one-hot indicators:

Hour = 09:00 Monday Product
Time
Monday 09:00 1 1 1
Monday 12:00 0 1 0
Sunday 09:00 1 0 0

The new feature is 1 only when both conditions hold.

Ridge can learn an extra adjustment for Monday at 09:00.

Ridge with one-hot and interaction features

Mean cross-validation MAE: 4.79 rentals

Do hour–weekday interactions improve validation MAE over one-hot features alone?

Interpretation

Interaction coefficients adjust predictions for particular hour–weekday combinations.

Coefficient
hour_12 weekday_6 15.241781
hour_9 weekday_5 14.338772
hour_6 weekday_2 14.318346
hour_12 weekday_5 14.143566
hour_6 weekday_5 -13.476297
hour_6 weekday_6 -17.378082

The full prediction includes the intercept and other active terms. A coefficient is neither the total effect nor a causal effect.

iClicker 19.2

Select all of the following statements which are TRUE.

    1. One-hot encoding the hour of day allows a linear model to learn a separate effect for each hour category.
    1. Useful temporal features and an encoding suited to the model can improve forecasting performance.
    1. Tree-based models are good at predicting values beyond the range of the training set because they can extrapolate trends.

Lag-based features

Calendar features describe when. Lag features describe what happened recently.

rentals
starttime
2015-08-01 00:00:00 3
2015-08-01 03:00:00 0
2015-08-01 06:00:00 9
2015-08-01 09:00:00 41
2015-08-01 12:00:00 39
2015-08-01 15:00:00 27
  • In time series data there is temporal dependence; observations close in time tend to be correlated.
  • Currently we’re using current time to predict the number of bike rentals in the next three hours.
  • But, what if the number of bike rentals is also related to bike rentals three hours ago or 6 hours ago and so on?
  • Such features are called lagged features.

Creating lag features

def add_lags(frame, column, lags):
    return frame.assign(**{
        f"{column}_lag{lag}": frame[column].shift(lag) for lag in lags
    })

lagged = add_lags(rentals_df, "rentals", [1, 2, 3, 4, 5, 8])
lag_features = lagged.drop(columns="rentals")
rentals rentals_lag1 rentals_lag2 rentals_lag3 rentals_lag4 rentals_lag5 rentals_lag8
starttime
2015-08-01 00:00:00 3 NaN NaN NaN NaN NaN NaN
2015-08-01 03:00:00 0 3.0 NaN NaN NaN NaN NaN
2015-08-01 06:00:00 9 0.0 3.0 NaN NaN NaN NaN
2015-08-01 09:00:00 41 9.0 0.0 3.0 NaN NaN NaN
2015-08-01 12:00:00 39 41.0 9.0 0.0 3.0 NaN NaN
2015-08-01 15:00:00 27 39.0 41.0 9.0 0.0 3.0 NaN
2015-08-01 18:00:00 12 27.0 39.0 41.0 9.0 0.0 NaN
2015-08-01 21:00:00 4 12.0 27.0 39.0 41.0 9.0 NaN
2015-08-02 00:00:00 3 4.0 12.0 27.0 39.0 41.0 3.0
2015-08-02 03:00:00 4 3.0 4.0 12.0 27.0 39.0 0.0

shift(1) = three hours; shift(8) = yesterday, only with regular spacing. Initial missing values are imputed using training-fold statistics.

How do we evaluate predictions with lags?

We make successive one-step forecasts within each validation fold (and later, the final test).

  1. At 09:00, use completed rental counts to predict 09:00–12:00.
  2. At 12:00, observe the actual 09:00–12:00 count.
  3. Use that newly observed count to predict 12:00–15:00.

The model stays fixed; the available observations grow.

Ridge with lag features

Mean cross-validation MAE: 7.75 rentals

Can recent counts alone anticipate the recurring peaks? Compare with the calendar models and baselines.

Random forest with lag features

Mean cross-validation MAE: 6.05 rentals

Does a nonlinear model use these same lags more effectively? Check validation MAE.

Ridge with all features

Calendar columns use one-hot encoding + interactions; lag columns use imputation. Both transformations are fitted within each fold. Combine weekday-specific hourly patterns with recent demand. Does validation MAE improve?

Mean cross-validation MAE: 5.09 rentals

Random forest with all features

The forest learns calendar interactions through its splits. Adding history is useful only if it improves validation performance.

Mean cross-validation MAE: 5.56 rentals

What did the feature comparisons show?

Compare models and baselines on the same validation windows.

Validation MAE (rentals)
Forest: hour + weekday 4.36
Ridge: calendar interactions 4.79
Ridge: calendar + lags 5.09
Forest: calendar + lags 5.56
Forest: lags 6.05
Ridge: one-hot calendar 6.93
Forest: hour 6.97
Baseline: seasonal naive (yesterday) 7.68
Ridge: lags 7.75
Ridge: numeric calendar 10.00
Forest: timestamp 11.40
Baseline: persistence (previous interval) 13.04

The hour + weekday forest has the lowest validation MAE; adding lags does not improve it here. Small differences on this short series may be uncertain.

One final test

Select the model with the lowest validation MAE, refit its full pipeline on all 23 development days, then evaluate once on the final eight days.

Selected: Forest: hour + weekday
Final test MAE: 3.53 rentals

Successive one-step forecasts still use completed counts as they arrive. Do not use this test result to choose another model.

Forecasting further into the future

What changes when we forecast further ahead?

  • At 00:00 on September 1, suppose we need predictions for the next five three-hour periods, through 12:00–15:00.
  • The count for 21:00–00:00 is known.
  • Counts for periods starting at 00:00, 03:00, 06:00, and 09:00 are not yet known.

How can we build lag features for later predictions without those actual counts?

Approach 1: Iterative forecasting

Train one model that predicts 3 hours ahead. At prediction time, move forward step by step, using your own predictions as future lag inputs.

Example:

  • Predict rentals at 00:00 on 2015-09-01.
  • Use that prediction as the lag to predict rentals at 03:00.
  • Use both predictions to predict rentals at 06:00.
  • Continue until you reach 12:00.

This method works, but errors accumulate as we step forward. The longer the horizon, the more uncertainty grows.

Approach 2: Direct forecasting (multiple horizons)

  • Train separate models for each horizon:
    • Model 1 \(\rightarrow\) predict 3 hours ahead
    • Model 2 \(\rightarrow\) predict 6 hours ahead
    • Model 3 \(\rightarrow\) predict 9 hours ahead

All models use observations available at the same forecast origin.

For each horizon, shift the target forward while keeping lag inputs in the known past. Future calendar features are also available.

Optional: Multi-output forecasting

  • Train one model that predicts several future steps at once, e.g.:

    y = [rentals_in_3h, rentals_in_6h, rentals_in_9h, ...]

  • Some models share information across future steps; others fit outputs independently.

  • Note: Multi-output forecasting is powerful, but outside the scope of CPSC 330.

Days since feature

Encode long-term change as elapsed time from a fixed reference date.

first_day_retail = retail_df["date"].min()
retail_with_time = retail_df.assign(
    Days_since=(retail_df["date"] - first_day_retail).dt.days
)
retail_with_time.head(6)
date sales Days_since
0 1992-01-01 6938 0
1 1992-02-01 7524 31
2 1992-03-01 8475 60
3 1992-04-01 9401 91
4 1992-05-01 9558 121
5 1992-06-01 9182 152

A linear model can learn a slope for this feature. A random forest still cannot extrapolate a trend beyond its training range.

Optional: Types of time series

Univariate time series: Bike rentals

A univariate time series tracks one variable over time. Here, we only measure the number of bike rentals at each timestamp.

starttime rentals
2015-08-26 12:00:00 30
2015-08-12 09:00:00 10
2015-08-19 03:00:00 2
2015-08-07 12:00:00 22
2015-08-03 09:00:00 9

Multivariate time series

A multivariate time series records several variables at each timestamp. Here, we track bike rentals along with weather and local traffic conditions.

datetime rentals temp_C humidity wind_kmh traffic_level
2015-08-01 09:00 12 18 65 10 2
2015-08-01 12:00 28 22 55 8 3
2015-08-01 15:00 35 24 50 12 4
2015-08-01 18:00 30 21 60 20 3
2015-08-02 09:00 10 17 70 15 1

Hierarchical time series

Related time series form an aggregation hierarchy: store sales add up to city sales, and city sales add up to company sales.

city store_id date bike_sales
Vancouver S1 2024-01-01 12
Vancouver S1 2024-01-02 15
Vancouver S2 2024-01-01 9
Vancouver S2 2024-01-02 11
Victoria M1 2024-01-01 7
Victoria M1 2024-01-02 8
Victoria M2 2024-01-01 14
Victoria M2 2024-01-02 13
Company
 ├── Vancouver
 │    ├── S1 time series
 │    └── S2 time series
 └── Victoria
      ├── M1 time series
      └── M2 time series

Check out the demo

Back to today’s big questions

  1. What changes with time order? Recent observations, repeating patterns (seasonality), and long-term trends can inform predictions.
  2. How do we evaluate forecasts? Compare baselines and models using temporal validation MAE; fit preprocessing within folds, then evaluate the selected model once on the final test.
  3. Which features help? Calendar, interaction, lag, and elapsed-time features; their encoding must suit the model. Trees cannot extrapolate trends.
  4. How do we forecast further ahead? Use predictions as future lag inputs (iterative) or train a model for each horizon (direct).

Baseline \(\to\) temporal validation \(\to\) model selection \(\to\) one final test.