Forecasting with tidymodels
made easy! This short
tutorial shows how you can use:
arima_reg()
,
arima_boost()
, exp_smoothing()
,
prophet_reg()
, prophet_boost()
, and morelinear_reg()
,
mars()
, svm_rbf()
, rand_forest()
,
boost_tree()
and more…to perform classical time series analysis and machine learning
in one framework! See “Model
List” for the full list of modeltime
models.
For those that prefer video tutorials, we have an 11-minute YouTube Video that walks you through the Modeltime Workflow.
(Click to Watch on YouTube)
Here’s the general process and where the functions fit.
Just follow the modeltime
workflow, which is detailed in
6 convenient steps:
Let’s go through a guided tour to kick the tires on
modeltime
.
Load libraries to complete this short tutorial.
library(xgboost)
library(tidymodels)
library(modeltime)
library(tidyverse)
library(lubridate)
library(timetk)
# This toggles plots from plotly (interactive) to ggplot (static)
<- FALSE interactive
# Data
<- m4_monthly %>% filter(id == "M750") m750
We can visualize the dataset.
%>%
m750 plot_time_series(date, value, .interactive = interactive)
Let’s split the data into training and test sets using
initial_time_split()
# Split Data 80/20
<- initial_time_split(m750, prop = 0.9) splits
We can easily create dozens of forecasting models by combining
modeltime
and parsnip
. We can also use the
workflows
interface for adding preprocessing! Your
forecasting possibilities are endless. Let’s get a few basic models
developed:
Important note: Handling Date Features
Modeltime models (e.g. arima_reg()
) are created
with a date or date time feature in the model. You will see that most
models include a formula like fit(value ~ date, data)
.
Parsnip models (e.g. linear_reg()
) typically
should not have date features, but may contain derivatives of dates
(e.g. month, year, etc). You will often see formulas like
fit(value ~ as.numeric(date) + month(date), data)
.
First, we create a basic univariate ARIMA model using “Auto Arima”
using arima_reg()
# Model 1: auto_arima ----
<- arima_reg() %>%
model_fit_arima_no_boost set_engine(engine = "auto_arima") %>%
fit(value ~ date, data = training(splits))
#> frequency = 12 observations per 1 year
Next, we create a boosted ARIMA using arima_boost()
.
Boosting uses XGBoost to model the ARIMA errors. Note that model formula
contains both a date feature and derivatives of date - ARIMA uses the
date - XGBoost uses the derivatives of date as regressors
Normally I’d use a preprocessing workflow for the month features
using a function like step_timeseries_signature()
from
timetk
to help reduce the complexity of the parsnip formula
interface.
# Model 2: arima_boost ----
<- arima_boost(
model_fit_arima_boosted min_n = 2,
learn_rate = 0.015
%>%
) set_engine(engine = "auto_arima_xgboost") %>%
fit(value ~ date + as.numeric(date) + factor(month(date, label = TRUE), ordered = F),
data = training(splits))
#> frequency = 12 observations per 1 year
Next, create an Error-Trend-Season (ETS) model using an Exponential
Smoothing State Space model. This is accomplished with
exp_smoothing()
.
# Model 3: ets ----
<- exp_smoothing() %>%
model_fit_ets set_engine(engine = "ets") %>%
fit(value ~ date, data = training(splits))
#> frequency = 12 observations per 1 year
We’ll create a prophet
model using
prophet_reg()
.
# Model 4: prophet ----
<- prophet_reg() %>%
model_fit_prophet set_engine(engine = "prophet") %>%
fit(value ~ date, data = training(splits))
#> Disabling weekly seasonality. Run prophet with weekly.seasonality=TRUE to override this.
#> Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.
We can model time series linear regression (TSLM) using the
linear_reg()
algorithm from parsnip
. The
following derivatives of date are used:
as.numeric(date)
month(date)
# Model 5: lm ----
<- linear_reg() %>%
model_fit_lm set_engine("lm") %>%
fit(value ~ as.numeric(date) + factor(month(date, label = TRUE), ordered = FALSE),
data = training(splits))
We can model a Multivariate Adaptive Regression Spline model using
mars()
. I’ve modified the process to use a
workflow
to standardize the preprocessing of the features
that are provided to the machine learning model (mars).
# Model 6: earth ----
<- mars(mode = "regression") %>%
model_spec_mars set_engine("earth")
<- recipe(value ~ date, data = training(splits)) %>%
recipe_spec step_date(date, features = "month", ordinal = FALSE) %>%
step_mutate(date_num = as.numeric(date)) %>%
step_normalize(date_num) %>%
step_rm(date)
<- workflow() %>%
wflw_fit_mars add_recipe(recipe_spec) %>%
add_model(model_spec_mars) %>%
fit(training(splits))
OK, with these 6 models, we’ll show how easy it is to forecast.
The next step is to add each of the models to a Modeltime Table using
modeltime_table()
. This step does some basic checking to
make sure each of the models are fitted and that organizes into a
scalable structure called a “Modeltime Table”
that is used as part of our forecasting workflow.
We have 6 models to add. A couple of notes before moving on:
modeltime_table()
will complain (throw an informative
error) saying you need to fit()
the model.<- modeltime_table(
models_tbl
model_fit_arima_no_boost,
model_fit_arima_boosted,
model_fit_ets,
model_fit_prophet,
model_fit_lm,
wflw_fit_mars
)
models_tbl#> # Modeltime Table
#> # A tibble: 6 × 3
#> .model_id .model .model_desc
#> <int> <list> <chr>
#> 1 1 <fit[+]> ARIMA(0,1,1)(0,1,1)[12]
#> 2 2 <fit[+]> ARIMA(0,1,1)(0,1,1)[12] W/ XGBOOST ERRORS
#> 3 3 <fit[+]> ETS(M,A,A)
#> 4 4 <fit[+]> PROPHET
#> 5 5 <fit[+]> LM
#> 6 6 <workflow> EARTH
Calibrating adds a new column, .calibration_data
, with
the test predictions and residuals inside. A few notes on
Calibration:
<- models_tbl %>%
calibration_tbl modeltime_calibrate(new_data = testing(splits))
calibration_tbl#> # Modeltime Table
#> # A tibble: 6 × 5
#> .model_id .model .model_desc .type .calibration_da…
#> <int> <list> <chr> <chr> <list>
#> 1 1 <fit[+]> ARIMA(0,1,1)(0,1,1)[12] Test <tibble>
#> 2 2 <fit[+]> ARIMA(0,1,1)(0,1,1)[12] W/ XGBOOS… Test <tibble>
#> 3 3 <fit[+]> ETS(M,A,A) Test <tibble>
#> 4 4 <fit[+]> PROPHET Test <tibble>
#> 5 5 <fit[+]> LM Test <tibble>
#> 6 6 <workflow> EARTH Test <tibble>
There are 2 critical parts to an evaluation.
Visualizing the Test Error is easy to do using the interactive plotly visualization (just toggle the visibility of the models using the Legend).
%>%
calibration_tbl modeltime_forecast(
new_data = testing(splits),
actual_data = m750
%>%
) plot_modeltime_forecast(
.legend_max_width = 25, # For mobile screens
.interactive = interactive
)
From visualizing the test set forecast:
We can use modeltime_accuracy()
to collect common
accuracy metrics. The default reports the following metrics using
yardstick
functions:
mae()
mape()
mase()
smape()
rmse()
rsq()
These of course can be customized following the rules for creating
new yardstick metrics, but the defaults are very useful. Refer to
default_forecast_accuracy_metrics()
to learn more.
To make table-creation a bit easier, I’ve included
table_modeltime_accuracy()
for outputing results in either
interactive (reactable
) or static (gt
)
tables.
%>%
calibration_tbl modeltime_accuracy() %>%
table_modeltime_accuracy(
.interactive = interactive
)
Accuracy Table | ||||||||
---|---|---|---|---|---|---|---|---|
.model_id | .model_desc | .type | mae | mape | mase | smape | rmse | rsq |
1 | ARIMA(0,1,1)(0,1,1)[12] | Test | 151.33 | 1.41 | 0.52 | 1.43 | 197.71 | 0.93 |
2 | ARIMA(0,1,1)(0,1,1)[12] W/ XGBOOST ERRORS | Test | 147.04 | 1.37 | 0.50 | 1.39 | 191.84 | 0.93 |
3 | ETS(M,A,A) | Test | 77.00 | 0.73 | 0.26 | 0.73 | 90.27 | 0.98 |
4 | PROPHET | Test | 172.05 | 1.65 | 0.59 | 1.65 | 230.06 | 0.88 |
5 | LM | Test | 629.12 | 6.01 | 2.15 | 5.81 | 657.19 | 0.91 |
6 | EARTH | Test | 709.83 | 6.59 | 2.42 | 6.86 | 782.82 | 0.55 |
From the accuracy metrics:
The final step is to refit the models to the full dataset using
modeltime_refit()
and forecast them forward.
<- calibration_tbl %>%
refit_tbl modeltime_refit(data = m750)
%>%
refit_tbl modeltime_forecast(h = "3 years", actual_data = m750) %>%
plot_modeltime_forecast(
.legend_max_width = 25, # For mobile screens
.interactive = interactive
)
The models have all changed! (Yes - this is the point of refitting)
This is the (potential) benefit of refitting.
More often than not refitting is a good idea. Refitting:
min_n = 2
,
learn_rate = 0.015
.We just showcased the Modeltime Workflow. But this is a simple problem. And, there’s a lot more to learning time series.
Your probably thinking how am I ever going to learn time series forecasting. Here’s the solution that will save you years of struggling.
Become the forecasting expert for your organization
High-Performance Time Series Course
Time series is changing. Businesses now need 10,000+ time series forecasts every day. This is what I call a High-Performance Time Series Forecasting System (HPTSF) - Accurate, Robust, and Scalable Forecasting.
High-Performance Forecasting Systems will save companies by improving accuracy and scalability. Imagine what will happen to your career if you can provide your organization a “High-Performance Time Series Forecasting System” (HPTSF System).
I teach how to build a HPTFS System in my High-Performance Time Series Forecasting Course. You will learn:
Modeltime
- 30+ Models (Prophet, ARIMA, XGBoost, Random
Forest, & many more)GluonTS
(Competition Winners)Become the Time Series Expert for your organization.