Suppose you manage a bicycle rental station in New York City. You want to predict how many rentals will occur during a future three-hour period so you can plan where bikes will be needed. Rental demand helps with planning, although predicting how many bikes will remain also requires information about returns and the station’s current inventory.
You already know several regression models. What would you use as features, and how would you evaluate the predictions?
We will use the Citi Bike example from Introduction to Machine Learning with Python, available through mglearn. Each timestamp marks the beginning of a three-hour rental-count interval.
rentals = mglearn.datasets.load_citibike().rename("rentals")display(rentals.head())print(f"{rentals.index.min()} to {rentals.index.max()}")ax = rentals.plot(figsize=(10, 3), ylabel="Rentals", xlabel="Interval start")ax.set_title("Bike rentals at one station, August 2015")plt.show()
What patterns do you notice? Demand changes with the time of day, and weekdays differ from weekends. These recurring patterns are examples of seasonality. Here, seasonality can be daily or weekly; it need not refer to seasons of the year.
A time series records observations in time order. Nearby observations often carry information about one another: a busy rental period may follow another busy period. This temporal dependence is useful information, but our familiar regressors do not use row order automatically. We must give them suitable features.
For our main task, we make a prediction at the beginning of each three-hour interval, using rental counts from completed intervals and calendar information for the interval ahead. We assume completed counts are available immediately. The forecast horizon describes how far ahead we predict. If counts arrive with a delay, our features must respect that delay too.
This is a univariate series: we observe one variable, rental count, over time. Recording weather as well would give us multiple variables. Recording rentals at many stations would give us multiple related series. A hierarchy adds aggregation relationships, such as station totals adding up to city totals. These distinctions matter when constructing lags and evaluating models.
We will adapt the supervised learning tools we already know. Specialized time-series models are another option, but they are outside this chapter’s scope.
Evaluating forecasts
How would you split this dataset? Our usual random split puts earlier and later observations in both sets. Let’s inspect what that means.
random_train, random_test = train_test_split(rentals, test_size=0.2, random_state=123)print("Latest training interval:", random_train.index.max())print("Earliest test interval:", random_test.index.min())
Latest training interval: 2015-08-31 21:00:00
Earliest test interval: 2015-08-01 12:00:00
Some training observations occur after test observations. This does not reproduce learning from the past to forecast the future. For this forecasting task, we instead hold out the last eight days and train on the first 23 days.
We still need to compare features and models without repeatedly consulting the final test set. TimeSeriesSplit constructs folds in which training observations precede validation observations. Its default training window expands as more observations become available. For this regularly spaced series, row counts also correspond to elapsed time.
We will compare models using mean absolute error (MAE), measured in rentals per interval. Lower is better. Before fitting a model, establish simple reference forecasts. A persistence forecast repeats the last observed count. A seasonal naive forecast repeats the count from the same interval one day earlier.
Our validation setup predicts one interval at a time. Observed counts become available between predictions, although the fitted model stays fixed during each validation fold. Therefore a later validation row may use an earlier validation count as a lag. That would be unavailable if we forecast the entire validation period at its beginning.
baseline_predictions = pd.DataFrame({"Previous interval": rentals.shift(1),"Same interval yesterday": rentals.shift(8),})baseline_scores = {}for name in baseline_predictions: errors = []for _, valid_rows in cv.split(train): errors.append(mean_absolute_error( train.iloc[valid_rows], baseline_predictions[name].iloc[valid_rows] )) baseline_scores[name] = np.mean(errors)display(pd.Series(baseline_scores, name="Validation MAE"))
A model uses yesterday’s rentals to predict today’s rentals. Is it valid to use observed rentals from the validation period?
It depends on the prediction task. They are available for later predictions if observations arrive each day. They are unavailable when forecasting the whole period in advance. A chronological split alone does not settle this question.
Engineering temporal features
Start with a numeric timestamp
A timestamp is not yet a useful numerical representation for every model. One possibility is elapsed seconds since the Unix epoch, often called POSIX time. Will a random forest learn the repeating rental pattern from this single increasing number? Predict the shape of its validation predictions before running the example.
Each comparison below plots observed and predicted rentals on the same last validation fold. The plot shows the final week of its training window and the following four validation days, with identical axes across models. All earlier training rows are still used for fitting. Training predictions show what the model can fit; validation predictions show which patterns carry forward. The printed cross-validation MAE averages over all three folds. The final test period remains untouched.
# Explicitly request seconds; do not assume the datetime storage resolution.calendar = pd.DataFrame({"elapsed_seconds": rentals.index.as_unit("s").asi8,"hour": rentals.index.hour,"weekday": rentals.index.dayofweek,}, index=rentals.index)y_train = train.to_numpy()validation_results = {}# Use the same last validation fold for every illustration.# Cross-validation scores still average over all three folds.plot_fit_rows, plot_valid_rows =list(cv.split(train))[-1]def compare(name, model, features): scores =-cross_val_score( model, features.iloc[:n_train], y_train, cv=cv, scoring="neg_mean_absolute_error", ) validation_results[name] = scores.mean() fitted = clone(model).fit(features.iloc[plot_fit_rows], train.iloc[plot_fit_rows]) fit_predictions = fitted.predict(features.iloc[plot_fit_rows]) valid_predictions = fitted.predict(features.iloc[plot_valid_rows]) fit_mae = mean_absolute_error(train.iloc[plot_fit_rows], fit_predictions) valid_mae = mean_absolute_error(train.iloc[plot_valid_rows], valid_predictions) fig, ax = plt.subplots(figsize=(11, 3.5)) ax.plot(train.index[plot_fit_rows], train.iloc[plot_fit_rows], color="C0", label="Training observations", alpha=0.65) ax.plot(train.index[plot_valid_rows], train.iloc[plot_valid_rows], color="C1", label="Validation observations", alpha=0.8) ax.plot(train.index[plot_fit_rows], fit_predictions, "--", color="C2", label="Training predictions") ax.plot(train.index[plot_valid_rows], valid_predictions, "--", color="C3", label="Validation predictions") boundary = train.index[plot_valid_rows[0]] ax.axvline(boundary, color="0.4", linestyle=":", label="Validation begins")# Zoom to the last training week and all four validation days. ax.set_xlim(boundary - pd.Timedelta(days=7), train.index[plot_valid_rows[-1]]) ax.set_ylim(-5, train.max() *1.1) ax.set(xlabel="Interval start", ylabel="Rentals", title=(f"{name}\nIllustrated fold MAE: train {fit_mae:.2f}, validation {valid_mae:.2f}" )) ax.legend(loc="upper left", bbox_to_anchor=(1.01, 1)) fig.autofmt_xdate() plt.show()print(f"Mean cross-validation MAE: {scores.mean():.2f} rentals")return fittedforest = RandomForestRegressor(n_estimators=100, random_state=123)timestamp_model = compare("Forest: timestamp", forest, calendar[["elapsed_seconds"]])
Mean cross-validation MAE: 11.40 rentals
All validation timestamps are later than the training timestamps. A regression tree sends these values into the same outermost leaf, whose prediction is an average of training targets. Averaging across trees still gives a constant prediction here.
A standard regression forest cannot extend an increasing or decreasing relationship beyond its learned partitions. It can accept new feature values, but it does not extrapolate a trend from this timestamp. We need features that expose the recurring patterns instead.
Calendar features and model choice
The plot suggests that hour and weekday matter. These features recur in future intervals, so a forest can reuse patterns learned from earlier days.
The hour-only model repeats the same daily profile. It can describe busy and quiet hours, but must use that same pattern on weekdays and weekends. Look at the training predictions: the missing day-to-day variation is a limitation of the representation, not simply a failure to generalize.
What additional calendar information could let the model distinguish a weekend afternoon from a weekday afternoon? Let’s add the day of the week.
Now the forest can use both hour and weekday in its splits. Compare the shapes of the daily peaks with the previous plot, and check the validation error rather than assuming that every added feature helps.
Do we need a forest to use these two features? Let’s try Ridge with exactly the same numeric inputs. Before running it, consider what one coefficient for hour and one for weekday allow the model to express.
Why might Ridge struggle even on the training data? Numeric hour gives it one coefficient: each additional hour changes the prediction by the same amount. That cannot describe morning and evening peaks. Numeric weekday imposes a similarly restrictive relationship.
One-hot encoding gives each hour and weekday its own effect. It does not explicitly tell the model that 21:00 and 00:00 are close in time. It does allow a separate prediction contribution for each observed hour.
Inspect the encoded rows alongside the prediction plot. Each row activates one hour category and one weekday category. Unlike a numeric hour coefficient, the model can assign unrelated effects to 06:00, 09:00, and 12:00.
This model still adds the same hourly effect on every weekday. What if the morning commute peak occurs on weekdays but not weekends? Interaction features let the effect of one feature depend on another. A weekday–hour interaction can represent a particular combination, such as Monday at 09:00.
The pipeline below fits encoding separately inside each training fold. PolynomialFeatures creates pairwise products; products between mutually exclusive categories are always zero, while hour–weekday products encode combinations.
Compare the one-hot model’s daily profiles with those from the interaction model. Without interactions, moving from a weekday to a weekend adds the same weekday effect at every hour. With interactions, the hourly profile itself can change.
We can inspect the corresponding feature products. The displayed interaction columns are active only when both the weekday and hour match.
A positive interaction coefficient contributes an upward adjustment for that combination; a negative one contributes a downward adjustment. The prediction also includes the intercept, main effects, and other active terms. Because some encoded features overlap and Ridge distributes their weights, an individual coefficient is not the total effect of that time period and should not be read as a causal explanation.
The comparison illustrates why model and representation must be chosen together. Forests can learn interactions through their splits. A linear model needs us to provide the corresponding features.
Learning from recent observations
Calendar features describe the usual pattern. What information are they missing about an unusually busy or quiet day? Recent rental counts may help. A lag feature supplies a past observation as an input for the current prediction.
def add_lags(frame, column, lags):"""Add past values; rows must be sorted and regularly spaced."""return frame.assign(**{f"{column}_lag{lag}": frame[column].shift(lag) for lag in lags })lagged = add_lags(rentals.to_frame(), "rentals", [1, 2, 3, 4, 5, 8])display(lagged.head(10))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) brings the previous row’s count into the current row. Here that means three hours earlier; shift(8) means one day earlier. The initial rows have missing lag values because our dataset contains no earlier observations. We use an imputer fitted only on each training fold. Dropping the initial incomplete rows is another reasonable option.
This interpretation assumes regular spacing. With missing timestamps, a previous row may be several intervals old. Check the spacing and, if necessary, align to a regular time grid before constructing interval-based lags. Filling missing timestamps creates missing observations; it does not make their values known.
Lag features describe the recent history rather than the position in the week. Inspect whether the linear model follows the peaks and troughs, and whether the validation pattern resembles its training fit. Its coefficients combine several recent counts, which may themselves be strongly related.
Would a nonlinear relationship between recent counts and the next count help? Keep the features unchanged and try a forest.
Compare both lag-only models with the calendar models. A model using recent counts may follow local changes while missing a recurring peak that is easier to anticipate from the clock.
Combining calendar and recent history
These two feature sets describe different information: when an interval occurs and what happened recently. Can their combination capture what either misses alone? First, keep the calendar interactions for Ridge and add the lag features.
Finally, combine numeric calendar features and lags for the forest. The forest can learn calendar interactions through its splits, so we do not need to supply the one-hot interaction expansion used for Ridge. Compare its training fit and validation predictions: a tighter training fit alone is not evidence of improvement.
Compare these errors with the simple baselines. More features do not guarantee better forecasts. Five recent intervals may contain little information beyond the calendar pattern, while a daily lag offers a different kind of history. The appropriate lag lengths depend on the sampling interval and the patterns we expect.
One final test
We now select among the candidates using validation MAE. This small dataset makes those comparisons uncertain, so small differences should not be treated as decisive. The test below evaluates the selected procedure once, under the same repeated one-step prediction setup.
Selected: Forest: hour + weekday
Final test MAE: 3.53 rentals
Forecasting multiple steps ahead
Imagine standing at the beginning of a three-hour interval and requesting predictions for the next five intervals. Can we use all the lag rows we constructed above?
No. For the first forecast we know the preceding counts. For the second, the most recent count belongs to an interval that has not finished yet. Our earlier evaluation allowed observations to arrive between predictions; this request does not.
Recursive forecasting
One option is to fit a one-step model and repeatedly feed its predictions back as lag inputs. This is recursive, or iterative, forecasting. The example below uses the first five lags. It fits on complete training rows and forecasts five intervals from one fixed origin. It does not read any test rental counts.
This reuses one model, but later inputs contain earlier prediction errors. Errors can propagate, and training on observed lags differs from predicting with estimated lags. Performance should be checked separately at each horizon using historical forecast origins.
Direct forecasting
Alternatively, train a separate model for each horizon. At origin \(t\), every model uses information already available at \(t\), but one predicts the interval starting at \(t\), another the interval starting three hours later, and so on. Construct each horizon’s target by shifting the outcome forward relative to the origin’s features. Exclude training examples whose target interval crosses the training cutoff.
Direct forecasting avoids feeding predictions back into inputs, but requires more models and leaves fewer complete training examples at longer horizons. Future calendar features are known in advance; future observed weather or rental counts are not. Weather forecasts could be inputs if equivalent forecasts were available when training and evaluating.
A third option is a multi-output model that predicts several horizons at once. Some such models share information across outputs; others fit outputs independently. We will not develop these models here.
NoteCheck your understanding
You forecast all of next week’s demand on Sunday evening. A validation feature for Thursday contains Wednesday’s observed demand. What is wrong?
Wednesday’s demand was unknown at the forecast origin. Use a prediction in a recursive approach, or construct a direct model using only information available on Sunday. Merely placing Thursday after the training dates does not prevent this leakage.
Seasonality, trends, and extrapolation
Calendar features capture recurring patterns, but what if the overall level changes over several years? A trend is a sustained upward or downward movement over time. It is different from seasonality: December peaks can recur while the level of sales also rises.
The monthly retail-sales series below comes from the Federal Reserve Bank of St. Louis. We use it to examine these two patterns, rather than repeat the full forecasting workflow.
An elapsed-time feature gives a linear model a way to represent a trend. A positive coefficient extends growth at a constant rate, including beyond the training period. That is an assumption, not a guarantee about future sales. Real trends can change, flatten, or reverse.
A standard random forest does not extend that slope. With elapsed time as its only feature, later timestamps reach outermost leaves. With calendar and lag features too, its predictions can vary, but it still does not extrapolate a growing trend in the way a linear model can. Regression-forest predictions are averages of training targets and remain within their observed range.
One possible approach is to estimate a trend and model the remaining variation separately. Both stages must be fitted inside each training fold. This adds assumptions and complexity; start by checking whether the forecast horizon and data support a stable trend.
Choosing an approach
Start by specifying the prediction time and available information. Inspect the sampling interval, gaps, recurring patterns, and changes in level. Establish simple baselines, then compare a small number of model–feature combinations with temporal validation. Calendar features are useful when behaviour repeats; lag features help when recent observations contain additional information. Choose the evaluation setup to match whether new observations arrive between predictions.
Our Rain in Australia demo applies this workflow to multiple locations and irregular observations. Specialized methods such as ARIMA and neural sequence models offer other ways to represent temporal structure. They still require careful definitions of the task, available information, and evaluation procedure.
Summary
Define the forecasting task before choosing a model. Specify when predictions are made, which future intervals they describe, and what information is available at prediction time.
Evaluate in time order. Use chronological holdouts and temporal cross-validation, fit preprocessing within each training fold, and compare against persistence or seasonal baselines. Reserve the final test period for evaluating the selected approach.
Choose temporal features that suit the model. Calendar features expose recurring patterns; one-hot encoding and interactions let linear models represent separate calendar effects and their combinations. Lag features supply information from past observations.
Check what a lag actually represents. A previous row is not necessarily a previous time interval. With multiple series, construct lags within each series and account for missing timestamps.
Match evaluation to the forecast horizon. Repeated one-step forecasts can use observations that arrive between predictions. Forecasting several steps at once cannot use those future observations: recursive forecasting feeds predictions back into inputs, while direct forecasting uses a separate model for each horizon.
Distinguish seasonality from trend. Seasonality repeats; a trend changes the overall level over time. A linear time feature can extend a trend, subject to its assumptions, while a standard regression forest does not extrapolate that trend beyond its learned partitions.
For a new forecasting problem, start with simple baselines and a small number of model–feature combinations. Use validation that reproduces the intended prediction process to decide whether additional features or complexity help.