### Example Setup for Modeltime Source: https://business-science.github.io/modeltime/reference/prophet_boost.html Provides a basic setup for using modeltime, including loading necessary libraries for data manipulation, date handling, modeling, and time series analysis. ```r library(dplyr) library(lubridate) library(parsnip) library(rsample) library(timetk) ``` -------------------------------- ### Setup and Data Preparation for Recursive Forecasting Source: https://business-science.github.io/modeltime/reference/recursive.html Example setup including library loading, future frame creation, and a transformation function for recursive updates. ```R library(tidymodels) library(dplyr) library(tidyr) library(timetk) library(slider) FORECAST_HORIZON <- 24 m750_extended <- m750 %>% group_by(id) %>% future_frame( .length_out = FORECAST_HORIZON, .bind_data = TRUE ) %>% ungroup() lag_roll_transformer <- function(data){ data %>% # Lags tk_augment_lags(value, .lags = 1:12) %>% # Rolling Features mutate(rolling_mean_12 = lag(slide_dbl( value, .f = mean, .before = 12, .complete = FALSE ), 1)) } # Data Preparation m750_rolling <- m750_extended %>% lag_roll_transformer() %>% select(-id) train_data <- m750_rolling %>% drop_na() future_data <- m750_rolling %>% filter(is.na(value)) # Modeling # Straight-Line Forecast model_fit_lm <- linear_reg() %>% set_engine("lm") %>% # Use only date feature as regressor fit(value ~ date, data = train_data) ``` -------------------------------- ### Prophet Model Setup Source: https://business-science.github.io/modeltime/reference/prophet_reg.html Example of preparing data and initializing a prophet model specification in Modeltime. ```R library(dplyr) library(parsnip) library(rsample) library(timetk) # Data m750 <- m4_monthly %>% filter(id == "M750") m750 #> # A tibble: 306 × 3 #> id date value #> #> 1 M750 1990-01-01 6370 #> 2 M750 1990-02-01 6430 #> 3 M750 1990-03-01 6520 #> 4 M750 1990-04-01 6580 #> 5 M750 1990-05-01 6620 #> 6 M750 1990-06-01 6690 #> 7 M750 1990-07-01 6000 #> 8 M750 1990-08-01 5450 #> 9 M750 1990-09-01 6480 #> 10 M750 1990-10-01 6820 #> # ℹ 296 more rows # Split Data 80/20 splits <- initial_time_split(m750, prop = 0.8) # ---- PROPHET ---- # Model Spec model_spec <- prophet_reg() %>% set_engine("prophet") ``` -------------------------------- ### Example: Basic Temporal Hierarchy Model Setup Source: https://business-science.github.io/modeltime/reference/temporal_hierarchy.html This example demonstrates how to set up a temporal hierarchy model specification using the 'thief' engine. It includes loading necessary libraries, preparing sample data, and creating the model specification. ```R library(dplyr) library(parsnip) library(rsample) library(timetk) library(thief) # Data m750 <- m4_monthly %>% filter(id == "M750") m750 #> # A tibble: 306 × 3 #> id date value #> #> 1 M750 1990-01-01 6370 #> 2 M750 1990-02-01 6430 #> 3 M750 1990-03-01 6520 #> 4 M750 1990-04-01 6580 #> 5 M750 1990-05-01 6620 #> 6 M750 1990-06-01 6690 #> 7 M750 1990-07-01 6000 #> 8 M750 1990-08-01 5450 #> 9 M750 1990-09-01 6480 #> 10 M750 1990-10-01 6820 #> # ℹ 296 more rows # Split Data 80/20 splits <- initial_time_split(m750, prop = 0.8) # ---- HIERARCHICAL ---- # Model Spec - The default parameters are all set # to "auto" if none are provided model_spec <- temporal_hierarchy() %>% set_engine("thief") ``` -------------------------------- ### Install modeltime.ensemble (Development) Source: https://business-science.github.io/modeltime.ensemble Install the latest development version of the modeltime.ensemble package from GitHub. ```r remotes::install_github("business-science/modeltime.ensemble") ``` -------------------------------- ### Example Usage of Season Parameter Source: https://business-science.github.io/modeltime/reference/exp_smoothing_params.html Demonstrates how to call the season() function to get information about the season term parameter. ```R season() #> Season Term (qualitative) #> 3 possible values include: #> 'additive', 'multiplicative', and 'none' ``` -------------------------------- ### Combining Modeltime Tables Example Source: https://business-science.github.io/modeltime/reference/combine_modeltime_tables.html Full example demonstrating the creation of two separate Modeltime Tables and merging them into one. ```R library(tidymodels) library(timetk) library(dplyr) library(lubridate) # Setup m750 <- m4_monthly %>% filter(id == "M750") splits <- time_series_split(m750, assess = "3 years", cumulative = TRUE) #> Using date_var: date model_fit_arima <- arima_reg() %>% set_engine("auto_arima") %>% fit(value ~ date, training(splits)) #> frequency = 12 observations per 1 year model_fit_prophet <- prophet_reg() %>% set_engine("prophet") %>% fit(value ~ date, 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. # Multiple Modeltime Tables model_tbl_1 <- modeltime_table(model_fit_arima) model_tbl_2 <- modeltime_table(model_fit_prophet) # Combine combine_modeltime_tables(model_tbl_1, model_tbl_2) #> # Modeltime Table #> # A tibble: 2 × 3 #> .model_id .model .model_desc #> #> 1 1 ARIMA(0,1,1)(0,1,1)[12] #> 2 2 PROPHET ``` -------------------------------- ### Install Development Version of modeltime.resample Source: https://business-science.github.io/modeltime.resample Install the latest features and updates by installing the development version directly from GitHub using remotes. ```r remotes::install_github("business-science/modeltime.resample") ``` -------------------------------- ### Install Modeltime (Development Version) Source: https://business-science.github.io/modeltime/index.html Installs the development version of the modeltime package directly from GitHub. This is useful for accessing the latest features and bug fixes. ```r remotes::install_github("business-science/modeltime", dependencies = TRUE) ``` -------------------------------- ### Example Usage of Trend Parameter Source: https://business-science.github.io/modeltime/reference/exp_smoothing_params.html Demonstrates how to call the trend() function to get information about the trend term parameter. ```R trend() #> Trend Term (qualitative) #> 3 possible values include: #> 'additive', 'multiplicative', and 'none' ``` -------------------------------- ### Inspect Prophet Parameter Defaults Source: https://business-science.github.io/modeltime/reference/prophet_params.html Examples showing the default configuration and ranges for specific Prophet tuning parameters. ```R growth() #> Growth Trend (qualitative) #> 2 possible values include: #> 'linear' and 'logistic' changepoint_num() #> Number of Possible Trend Changepoints (quantitative) #> Range: [0, 50] season() #> Season Term (qualitative) #> 3 possible values include: #> 'additive', 'multiplicative', and 'none' prior_scale_changepoints() #> Prior Scale Changepoints (quantitative) #> Transformer: log-10 [1e-100, Inf] #> Range (transformed scale): [-3, 2] ``` -------------------------------- ### Modeltime Workflow Example Source: https://business-science.github.io/modeltime/reference/modeltime_table.html Demonstrates the full lifecycle of creating a model, organizing it into a Modeltime Table, calibrating against test data, and generating forecasts. ```R library(dplyr) library(timetk) library(parsnip) library(rsample) # Data m750 <- m4_monthly %>% filter(id == "M750") # Split Data 80/20 splits <- initial_time_split(m750, prop = 0.9) # --- MODELS --- # Model 1: prophet ---- model_fit_prophet <- prophet_reg() %>% 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. # ---- MODELTIME TABLE ---- # Make a Modeltime Table models_tbl <- modeltime_table( model_fit_prophet ) # Can also convert a list of models list(model_fit_prophet) %>% as_modeltime_table() #> # Modeltime Table #> # A tibble: 1 × 3 #> .model_id .model .model_desc #> #> 1 1 PROPHET # ---- CALIBRATE ---- calibration_tbl <- models_tbl %>% modeltime_calibrate(new_data = testing(splits)) # ---- ACCURACY ---- calibration_tbl %>% modeltime_accuracy() #> # A tibble: 1 × 9 #> .model_id .model_desc .type mae mape mase smape rmse rsq #> #> 1 1 PROPHET Test 175. 1.67 0.596 1.67 232. 0.881 # ---- FORECAST ---- calibration_tbl %>% modeltime_forecast( new_data = testing(splits), actual_data = m750 ) #> # Forecast Results #> #> Conf Method: conformal_default | Conf Interval: 0.95 | Conf By ID: FALSE #> (GLOBAL CONFIDENCE) #> # A tibble: 337 × 7 #> .model_id .model_desc .key .index .value .conf_lo .conf_hi #> #> 1 NA ACTUAL actual 1990-01-01 6370 NA NA #> 2 NA ACTUAL actual 1990-02-01 6430 NA NA #> 3 NA ACTUAL actual 1990-03-01 6520 NA NA #> 4 NA ACTUAL actual 1990-04-01 6580 NA NA #> 5 NA ACTUAL actual 1990-05-01 6620 NA NA #> 6 NA ACTUAL actual 1990-06-01 6690 NA NA #> 7 NA ACTUAL actual 1990-07-01 6000 NA NA #> 8 NA ACTUAL actual 1990-08-01 5450 NA NA #> 9 NA ACTUAL actual 1990-09-01 6480 NA NA #> 10 NA ACTUAL actual 1990-10-01 6820 NA NA #> # ℹ 327 more rows ``` -------------------------------- ### Install GitHub Version and Python Dependencies Source: https://business-science.github.io/modeltime.gluonts Install the GitHub version of modeltime.gluonts and its required Python dependencies. This is the recommended installation method as the package is maintained on GitHub. ```r # Install GitHub Version remotes::install_github("business-science/modeltime.gluonts") # Install Python Dependencies modeltime.gluonts::install_gluonts() ``` -------------------------------- ### Example usage of num_networks Source: https://business-science.github.io/modeltime/reference/nnetar_params.html Displays the default configuration and range for the num_networks parameter. ```R num_networks() #> Number of Neural Networks to Average (quantitative) #> Range: [1, 100] ``` -------------------------------- ### Execute seasonal_period example Source: https://business-science.github.io/modeltime/reference/time_series_params.html Displays the possible values for the seasonal period parameter. ```R seasonal_period() #> Period (Seasonal Frequency) (qualitative) #> 4 possible values include: #> 'none', 'daily', 'weekly', and 'yearly' ``` -------------------------------- ### Prepare Nested Modeltime Data Example Source: https://business-science.github.io/modeltime/reference/prep_nested.html Demonstrates the 3-step process of preparing nested time series data: extending, nesting, and splitting. This example uses `dplyr` and `timetk` to process weekly sales data. ```R library(dplyr) library(timetk) nested_data_tbl <- walmart_sales_weekly %>% select(id, date = Date, value = Weekly_Sales) %>% # Step 1: Extends the time series by id extend_timeseries( .id_var = id, .date_var = date, .length_future = 52 ) %>% # Step 2: Nests the time series into .actual_data and .future_data nest_timeseries( .id_var = id, .length_future = 52 ) %>% # Step 3: Adds a column .splits that contains training/testing indices split_nested_timeseries( .length_test = 52 ) nested_data_tbl #> # A tibble: 7 × 4 #> id .actual_data .future_data .splits #> #> 1 1_1 #> 2 1_3 #> 3 1_8 #> 4 1_13 #> 5 1_38 #> 6 1_93 #> 7 1_95 # Helpers: Getting the Train/Test Sets extract_nested_train_split(nested_data_tbl, .row_id = 1) #> # A tibble: 91 × 2 #> date value #> #> 1 2010-02-05 24924. #> 2 2010-02-12 46039. #> 3 2010-02-19 41596. #> 4 2010-02-26 19404. #> 5 2010-03-05 21828. #> 6 2010-03-12 21043. #> 7 2010-03-19 22137. #> 8 2010-03-26 26229. #> 9 2010-04-02 57258. #> 10 2010-04-09 42961. #> # ℹ 81 more rows ``` -------------------------------- ### Install modeltime.ensemble (CRAN) Source: https://business-science.github.io/modeltime.ensemble Install the stable version of the modeltime.ensemble package from CRAN. ```r install.packages("modeltime.ensemble") ``` -------------------------------- ### Start Parallel Clusters Source: https://business-science.github.io/modeltime/reference/parallel_start.html Starts parallel processing clusters using specified methods and configurations. ```APIDOC ## parallel_start() ### Description Starts parallel clusters/plans for processing. ### Method FUNCTION ### Endpoint N/A (R Function) ### Parameters #### Arguments - **...** (numeric or other) - Optional - Parameters passed to underlying functions. For `.method = "future"`, this can be the worker count. - **.method** (character) - Optional - The method to create the parallel backend. Supports: "future", "parallel", "spark". Defaults to "parallel". - **.export_vars** (list or NULL) - Optional - Environment variables to send to workers (not needed for "future"). - **.packages** (list or NULL) - Optional - Packages to send to workers (auto-handled by "future"). ### Request Example ```R # Starts 2 clusters using the default method parallel_start(2) # Starts a future-based cluster with 4 workers parallel_start(4, .method = "future") # Starts a parallel cluster with specific exported variables and packages parallel_start(cores = 4, .export_vars = c("my_var"), .packages = c("dplyr")) ``` ### Response #### Success Response (None explicitly defined, function modifies global state) #### Response Example (None explicitly defined) ``` -------------------------------- ### Prophet Model Fitting and Calibration Example Source: https://business-science.github.io/modeltime/reference/modeltime_calibrate.html Demonstrates fitting a Prophet model, creating a Modeltime table, calibrating it with test data, and then calculating accuracy and generating forecasts. Includes necessary library calls and data preparation. ```R library(dplyr) library(lubridate) library(timetk) library(parsnip) library(rsample) # Data m750 <- m4_monthly %>% filter(id == "M750") # Split Data 80/20 splits <- initial_time_split(m750, prop = 0.8) # --- MODELS --- # Model 1: prophet ---- model_fit_prophet <- prophet_reg() %>% 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. # ---- MODELTIME TABLE ---- models_tbl <- modeltime_table( model_fit_prophet ) # ---- CALIBRATE ---- calibration_tbl <- models_tbl %>% modeltime_calibrate( new_data = testing(splits) ) # ---- ACCURACY ---- calibration_tbl %>% modeltime_accuracy() #> # A tibble: 1 × 9 #> .model_id .model_desc .type mae mape mase smape rmse rsq #> #> 1 1 PROPHET Test 266. 2.68 0.791 2.62 359. 0.812 # ---- FORECAST ---- calibration_tbl %>% modeltime_forecast( new_data = testing(splits), actual_data = m750 ) #> # Forecast Results #> #> Conf Method: conformal_default | Conf Interval: 0.95 | Conf By ID: FALSE #> (GLOBAL CONFIDENCE) #> # A tibble: 368 × 7 #> .model_id .model_desc .key .index .value .conf_lo .conf_hi #> #> 1 NA ACTUAL actual 1990-01-01 6370 NA NA #> 2 NA ACTUAL actual 1990-02-01 6430 NA NA #> 3 NA ACTUAL actual 1990-03-01 6520 NA NA #> 4 NA ACTUAL actual 1990-04-01 6580 NA NA #> 5 NA ACTUAL actual 1990-05-01 6620 NA NA #> 6 NA ACTUAL actual 1990-06-01 6690 NA NA #> 7 NA ACTUAL actual 1990-07-01 6000 NA NA #> 8 NA ACTUAL actual 1990-08-01 5450 NA NA #> 9 NA ACTUAL actual 1990-09-01 6480 NA NA #> 10 NA ACTUAL actual 1990-10-01 6820 NA NA #> # ℹ 358 more rows ``` -------------------------------- ### Example Usage of Temporal Hierarchical Parameters Source: https://business-science.github.io/modeltime/reference/temporal_hierarchy_params.html Displays the available options for combination methods and forecasting models. ```R combination_method() #> Combination method of temporal hierarchies. (qualitative) #> 6 possible values include: #> 'struc', 'mse', 'ols', 'bu', 'shr', and 'sam' use_model() #> Model used for forecasting each aggregation level. (qualitative) #> 5 possible values include: #> 'ets', 'arima', 'theta', 'naive', and 'snaive' ``` -------------------------------- ### Install Modeltime (CRAN) Source: https://business-science.github.io/modeltime/index.html Installs the latest stable version of the modeltime package from CRAN. Ensure dependencies are installed. ```r install.packages("modeltime", dependencies = TRUE) ``` -------------------------------- ### Fit Interface Examples Source: https://business-science.github.io/modeltime/reference/exp_smoothing.html Basic syntax for fitting models using formula and XY interfaces. ```R fit(y ~ date) ``` ```R fit_xy(x = data[,"date"], y = data$y) ``` ```R fit(y ~ date + month.lbl) ``` ```R fit_xy(data[,c("date", "month.lbl")], y = data$y) ``` -------------------------------- ### Example Usage of Error Parameter Source: https://business-science.github.io/modeltime/reference/exp_smoothing_params.html Demonstrates how to call the error() function to get information about the error term parameter. ```R error() #> Error Term (qualitative) #> 2 possible values include: #> 'additive' and 'multiplicative' ``` -------------------------------- ### Example of get_arima_description Source: https://business-science.github.io/modeltime/reference/get_arima_description.html Demonstrates fitting an Arima model and retrieving its description. ```R library(forecast) #> #> Attaching package: ‘forecast’ #> The following object is masked from ‘package:yardstick’: #> #> accuracy arima_fit <- forecast::Arima(1:10) get_arima_description(arima_fit) #> [1] "ARIMA(0,0,0) with non-zero mean" ``` -------------------------------- ### Install Modeltime H2O Development Version Source: https://business-science.github.io/modeltime.h2o Use this command to install the latest development version of the package from GitHub. ```R # Install Development Version devtools::install_github("business-science/modeltime.h2o") ``` -------------------------------- ### Install CRAN version of modeltime.resample Source: https://business-science.github.io/modeltime.resample Use this command to install the stable version of the modeltime.resample package from CRAN. ```r install.packages("modeltime.resample") ``` -------------------------------- ### Start 2 Parallel Clusters Source: https://business-science.github.io/modeltime/reference/parallel_start.html Initiates parallel processing by starting two clusters. This is a common use case for speeding up computations. ```R parallel_start(2) ``` -------------------------------- ### Example of Summarizing Accuracy Metrics Source: https://business-science.github.io/modeltime/reference/summarize_accuracy_metrics.html This example demonstrates how to use `summarize_accuracy_metrics` with a sample tibble of predictions. It groups the data by model and computes default forecast accuracy metrics. ```R library(dplyr) predictions_tbl <- tibble( group = c("model 1", "model 1", "model 1", "model 2", "model 2", "model 2"), truth = c(1, 2, 3, 1, 2, 3), estimate = c(1.2, 2.0, 2.5, 0.9, 1.9, 3.3) ) predictions_tbl %>% dplyr::group_by(group) %>% summarize_accuracy_metrics( truth, estimate, metric_set = default_forecast_accuracy_metric_set() ) ``` -------------------------------- ### Inspect ADAM Parameter Definitions Source: https://business-science.github.io/modeltime/reference/adam_params.html Examples of calling parameter functions to view their descriptions and possible values. ```R use_constant() #> Logical, determining, whether the constant is needed in the model or not #> (qualitative) #> 2 possible values include: #> FALSE and TRUE regressors_treatment() #> The variable defines what to do with the provided explanatory variables. #> (qualitative) #> 3 possible values include: #> 'use', 'select', and 'adapt' distribution() #> What density function to assume for the error term. (qualitative) #> 8 possible values include: #> 'default', 'dnorm', 'dlaplace', 'ds', 'dgnorm', 'dlnorm', 'dinvgauss', and #> 'dgamma' ``` -------------------------------- ### Start Parallel Processing with `parallel_start()` Source: https://business-science.github.io/modeltime/news/index.html Initialize multicore processing for parallel computations using the `parallel_start()` helper function. Ensure to call `parallel_stop()` when finished. ```R parallel_start() ``` -------------------------------- ### Adding a model to a Modeltime Table example Source: https://business-science.github.io/modeltime/reference/add_modeltime_model.html Demonstrates fitting an ETS model and appending it to an existing Modeltime Table. ```R library(tidymodels) model_fit_ets <- exp_smoothing() %>% set_engine("ets") %>% fit(value ~ date, training(m750_splits)) m750_models %>% add_modeltime_model(model_fit_ets) ``` -------------------------------- ### Generate Interactive Accuracy Table Source: https://business-science.github.io/modeltime/reference/table_modeltime_accuracy.html This example demonstrates how to generate an interactive accuracy table using `table_modeltime_accuracy`. It involves setting up data, fitting a Prophet model, creating a modeltime table, calibrating, calculating accuracy, and finally displaying the interactive table. ```r library(dplyr) library(lubridate) library(timetk) library(parsnip) library(rsample) # Data m750 <- m4_monthly %>% filter(id == "M750") # Split Data 80/20 splits <- initial_time_split(m750, prop = 0.9) # --- MODELS --- # Model 1: prophet ---- model_fit_prophet <- prophet_reg() %>% set_engine(engine = "prophet") %>% fit(value ~ date, data = training(splits)) ``` ```r # ---- MODELTIME TABLE ---- models_tbl <- modeltime_table( model_fit_prophet ) # ---- ACCURACY ---- models_tbl %>% modeltime_calibrate(new_data = testing(splits)) %>% modeltime_accuracy() %>% table_modeltime_accuracy() ``` -------------------------------- ### NNETAR Model Training Example Source: https://business-science.github.io/modeltime/reference/nnetar_reg.html Complete workflow for splitting data and fitting an NNETAR model using the parsnip and modeltime ecosystem. ```R library(dplyr) library(parsnip) library(rsample) library(timetk) # Data m750 <- m4_monthly %>% filter(id == "M750") m750 #> # A tibble: 306 × 3 #> id date value #> #> 1 M750 1990-01-01 6370 #> 2 M750 1990-02-01 6430 #> 3 M750 1990-03-01 6520 #> 4 M750 1990-04-01 6580 #> 5 M750 1990-05-01 6620 #> 6 M750 1990-06-01 6690 #> 7 M750 1990-07-01 6000 #> 8 M750 1990-08-01 5450 #> 9 M750 1990-09-01 6480 #> 10 M750 1990-10-01 6820 #> # ℹ 296 more rows # Split Data 80/20 splits <- initial_time_split(m750, prop = 0.8) # ---- NNETAR ---- # Model Spec model_spec <- nnetar_reg() %>% set_engine("nnetar") # Fit Spec set.seed(123) model_fit <- model_spec %>% fit(log(value) ~ date, data = training(splits)) #> frequency = 12 observations per 1 year model_fit #> parsnip model object #> #> Series: outcome #> Model: NNAR(1,1,10)[12] #> Call: forecast::nnetar(y = outcome, p = p, P = P, size = size, repeats = repeats, #> xreg = xreg_matrix, decay = decay, maxit = maxit) #> #> Average of 20 networks, each of which is #> a 2-10-1 network with 41 weights #> options were - linear output units #> #> sigma^2 estimated as 0.0005869 ``` -------------------------------- ### Visualize model residuals with plot_modeltime_residuals Source: https://business-science.github.io/modeltime/reference/plot_modeltime_residuals.html Example workflow demonstrating data preparation, model fitting, calibration, and residual plotting. ```R library(dplyr) library(timetk) library(parsnip) library(rsample) # Data m750 <- m4_monthly %>% filter(id == "M750") # Split Data 80/20 splits <- initial_time_split(m750, prop = 0.9) # --- MODELS --- # Model 1: prophet ---- model_fit_prophet <- prophet_reg() %>% 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. # ---- MODELTIME TABLE ---- models_tbl <- modeltime_table( model_fit_prophet ) # ---- RESIDUALS ---- residuals_tbl <- models_tbl %>% modeltime_calibrate(new_data = testing(splits)) %>% modeltime_residuals() residuals_tbl %>% plot_modeltime_residuals( .type = "timeplot", .interactive = FALSE ) ``` -------------------------------- ### Calculate residual statistical tests Source: https://business-science.github.io/modeltime/reference/modeltime_residuals_test.html Example demonstrating how to calibrate a model, extract residuals, and perform statistical tests on both in-sample and out-of-sample data. ```R library(dplyr) library(timetk) library(parsnip) library(rsample) # Data m750 <- m4_monthly %>% filter(id == "M750") # Split Data 80/20 splits <- initial_time_split(m750, prop = 0.9) # --- MODELS --- # Model 1: prophet ---- model_fit_prophet <- prophet_reg() %>% 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. # ---- MODELTIME TABLE ---- models_tbl <- modeltime_table( model_fit_prophet ) # ---- RESIDUALS ---- # In-Sample models_tbl %>% modeltime_calibrate(new_data = training(splits)) %>% modeltime_residuals() %>% modeltime_residuals_test() #> # A tibble: 1 × 6 #> .model_id .model_desc shapiro_wilk box_pierce ljung_box durbin_watson #> #> 1 1 PROPHET 0.0000486 0 0 0.921 # Out-of-Sample models_tbl %>% modeltime_calibrate(new_data = testing(splits)) %>% modeltime_residuals() %>% modeltime_residuals_test() #> # A tibble: 1 × 6 #> .model_id .model_desc shapiro_wilk box_pierce ljung_box durbin_watson #> #> 1 1 PROPHET 0.00185 0.190 0.170 1.34 ``` -------------------------------- ### Load Required R Packages Source: https://business-science.github.io/modeltime/articles/extending-modeltime.html Installs and loads necessary R packages for time series analysis and modeling with Modeltime. ```r library(parsnip) library(forecast) library(rsample) library(modeltime) library(tidyverse) library(timetk) library(rlang) ``` -------------------------------- ### Example ARIMA Model Usage Source: https://business-science.github.io/modeltime/reference/arima_params.html Demonstrates the usage of ARIMA model parameters, showing default ranges for non-seasonal AR, differencing, and MA terms. ```R ets_model() #> ETS Model (qualitative) #> 6 possible values include: #> 'ZZZ', 'XXX', 'YYY', 'CCC', 'PPP', and 'FFF' ``` -------------------------------- ### Load Required Libraries Source: https://business-science.github.io/modeltime/articles/modeltime-conformal-prediction.html Initialize the environment by loading the necessary packages for data manipulation, modeling, and time series analysis. ```R library(tidyverse) ``` ```R library(tidymodels) library(modeltime) library(timetk) # This toggles plots from plotly (interactive) to ggplot (static) interactive <- FALSE ``` -------------------------------- ### Load Required Libraries Source: https://business-science.github.io/modeltime/articles/nested-forecasting.html Initialize the environment by loading the necessary packages for time series modeling and data manipulation. ```R library(modeltime) library(tidymodels) library(tidyverse) library(timetk) ``` -------------------------------- ### Load Modeltime Libraries Source: https://business-science.github.io/modeltime/articles/getting-started-with-modeltime.html Initializes the environment with required packages for time series analysis and forecasting. ```R library(xgboost) library(tidymodels) library(modeltime) library(tidyverse) library(timetk) # This toggles plots from plotly (interactive) to ggplot (static) interactive <- FALSE ``` -------------------------------- ### Initialize Parallel Backend Source: https://business-science.github.io/modeltime/articles/parallel-processing.html Configure parallel processing backends for model training. ```R parallel_start(2, .method = "parallel") ``` ```R # OPTIONAL - Run using spark backend library(sparklyr) sc <- spark_connect(master = "local") parallel_start(sc, .method = "spark") ``` -------------------------------- ### Prepare Data for Forecasting Source: https://business-science.github.io/modeltime/articles/modeltime-conformal-prediction.html Load the Walmart sales dataset, format the ID column, and visualize the time series. ```R # Data walmart_sales_tbl <- timetk::walmart_sales_weekly %>% select(id, Date, Weekly_Sales) %>% mutate(id = forcats::as_factor(id)) ``` ```R walmart_sales_tbl %>% group_by(id) %>% plot_time_series( Date, Weekly_Sales, .facet_ncol = 2, .interactive = interactive, ) ``` -------------------------------- ### Create a Modeltime Table Source: https://business-science.github.io/modeltime.ensemble Demonstrates how to create a Modeltime Table, which is a prerequisite for building ensembles. This table typically contains multiple fitted time series models. ```r m750_models #> # Modeltime Table #> # A tibble: 3 × 3 #> .model_id .model .model_desc #> #> 1 1 ARIMA(0,1,1)(0,1,1)[12] #> 2 2 PROPHET #> 3 3 GLMNET ``` -------------------------------- ### Register Spark Backend Source: https://business-science.github.io/modeltime/articles/modeltime-spark.html Initialize the Spark backend to enable parallel execution via the foreach adapter. ```R parallel_start(sc, .method = "spark") ``` -------------------------------- ### Load and Visualize Data Source: https://business-science.github.io/modeltime/articles/parallel-processing.html Prepare the walmart_sales_weekly dataset for modeling and visualize the time series. ```R dataset_tbl <- walmart_sales_weekly %>% select(id, Date, Weekly_Sales) dataset_tbl %>% group_by(id) %>% plot_time_series( .date_var = Date, .value = Weekly_Sales, .facet_ncol = 2, .interactive = FALSE ) ``` -------------------------------- ### Get Model Description - R Source: https://business-science.github.io/modeltime/reference/get_model_description.html Use this function to get a human-readable description of a parsnip or workflow model. It can indicate if the model has been trained and whether the description should be in upper or lower case. ```r library(dplyr) library(timetk) library(parsnip) # Model Specification ---- arima_spec <- arima_reg() %>% set_engine("auto_arima") get_model_description(arima_spec, indicate_training = TRUE) #> [1] "AUTO_ARIMA (NOT TRAINED)" # Fitted Model ---- m750 <- m4_monthly %>% filter(id == "M750") arima_fit <- arima_spec %>% fit(value ~ date, data = m750) #> frequency = 12 observations per 1 year get_model_description(arima_fit, indicate_training = TRUE) #> [1] "ARIMA(0,1,1)(0,1,1)[12] (TRAINED)" ``` -------------------------------- ### GET modeltime_residuals Source: https://business-science.github.io/modeltime/reference/modeltime_residuals.html Extracts residuals from a Modeltime Table object, typically after calibration. ```APIDOC ## modeltime_residuals ### Description A convenience function to unnest model residuals from a Modeltime Table. ### Parameters #### Arguments - **object** (Modeltime Table) - Required - A Modeltime Table object. - **new_data** (tibble) - Optional - A tibble to predict and calculate residuals on. If provided, overrides any calibration data. - **quiet** (boolean) - Optional - Hide errors (TRUE, the default), or display them as they occur. - **...** (dots) - Optional - Not currently used. ### Value A tibble containing the calculated residuals. ### Request Example modeltime_residuals(object = models_tbl, new_data = testing_data) ### Response #### Success Response - **tibble** (object) - A tibble containing the residuals data. ``` -------------------------------- ### Fit Forecasting Models Source: https://business-science.github.io/modeltime/articles/getting-started-with-modeltime.html Demonstrates fitting various time series models including ARIMA, Boosted ARIMA, ETS, and Prophet. ```R # Model 1: auto_arima ---- model_fit_arima_no_boost <- arima_reg() %>% set_engine(engine = "auto_arima") %>% fit(value ~ date, data = training(splits)) ``` ```R # Model 2: arima_boost ---- model_fit_arima_boosted <- arima_boost( 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)) ``` ```R # Model 3: ets ---- model_fit_ets <- exp_smoothing() %>% set_engine(engine = "ets") %>% fit(value ~ date, data = training(splits)) ``` ```R # Model 4: prophet ---- model_fit_prophet <- prophet_reg() %>% set_engine(engine = "prophet") %>% fit(value ~ date, data = training(splits)) ``` -------------------------------- ### GET /m750_models Source: https://business-science.github.io/modeltime/reference/m750_models.html Retrieves the Modeltime Table containing the three models trained on the M750 dataset. ```APIDOC ## GET /m750_models ### Description Retrieves a Modeltime Table object containing three pre-trained models (ARIMA, Prophet, and GLMNET) based on the M750 training set. ### Method GET ### Endpoint /m750_models ### Response #### Success Response (200) - **.model_id** (int) - Unique identifier for the model. - **.model** (list) - The fitted workflow object. - **.model_desc** (string) - Description of the model configuration. #### Response Example { "model_id": 1, "model_desc": "ARIMA(0,1,1)(0,1,1)[12]" } ``` -------------------------------- ### Prepare Data for Prophet Model Source: https://business-science.github.io/modeltime/reference/modeltime_forecast.html Loads and splits time series data for model training and testing using initial_time_split. Ensure the necessary libraries are loaded. ```r library(dplyr) library(timetk) library(parsnip) library(rsample) # Data m750 <- m4_monthly %>% filter(id == "M750") # Split Data 80/20 splits <- initial_time_split(m750, prop = 0.9) ``` -------------------------------- ### Create Model Grids with `create_model_grid()` Source: https://business-science.github.io/modeltime/news/index.html Generate model specifications with filled-in parameters from a parameter grid using `create_model_grid()`. This is useful for creating multiple model configurations efficiently. ```R create_model_grid() ``` -------------------------------- ### Initialize Modeltime Table Source: https://business-science.github.io/modeltime/reference/modeltime_table.html Create a Modeltime Table from individual fitted models or convert a list of models into the required format. ```R modeltime_table(...) as_modeltime_table(.l) ``` -------------------------------- ### Configure Prophet Model with Logistic Growth Source: https://business-science.github.io/modeltime/news/index.html Use `prophet_reg()` or `prophet_boost()` with `growth = 'logistic'` to enable logistic growth. Set `logistic_cap` and/or `logistic_floor` for saturation boundaries. ```r prophet_reg( growth = 'logistic', logistic_cap = 100, logistic_floor = 0 ) ``` -------------------------------- ### num_networks() Source: https://business-science.github.io/modeltime/reference/nnetar_params.html Defines the number of neural networks to fit with different random starting weights. These networks are then averaged to produce forecasts. ```APIDOC ## Function: num_networks ### Description Specifies the number of neural networks to fit with different random starting weights. The forecasts from these networks are averaged. ### Usage ```R num_networks(range = c(1L, 100L), trans = NULL) ``` ### Arguments * `range` (numeric vector): A two-element vector specifying the minimum and maximum number of networks. Defaults to `c(1L, 100L)`. * `trans` (scales transformation object, optional): A transformation object from the `scales` package (e.g., `scales::transform_log10()`). If `NULL`, no transformation is applied. ### Details This parameter controls the number of networks that are trained and averaged. A higher number can potentially lead to more robust forecasts but increases computation time. ### Examples ```R num_networks() #> Number of Neural Networks to Average (quantitative) #> Range: [1, 100] ``` ``` -------------------------------- ### Update Modeltime Table Description Example Source: https://business-science.github.io/modeltime/reference/update_model_description.html Demonstrates updating the description of a model with ID 2 in an existing Modeltime Table. ```R m750_models %>% update_modeltime_description(2, "PROPHET - No Regressors") ``` -------------------------------- ### Load Libraries and Prepare Data Source: https://business-science.github.io/modeltime/reference/arima_reg.html Loads necessary libraries and filters the M4 monthly dataset for a specific series (M750). ```r library(dplyr) library(parsnip) library(rsample) library(timetk) # Data m750 <- m4_monthly %>% filter(id == "M750") m750 #> # A tibble: 306 × 3 #> id date value #> #> 1 M750 1990-01-01 6370 #> 2 M750 1990-02-01 6430 #> 3 M750 1990-03-01 6520 #> 4 M750 1990-04-01 6580 #> 5 M750 1990-05-01 6620 #> 6 M750 1990-06-01 6690 #> 7 M750 1990-07-01 6000 #> 8 M750 1990-08-01 5450 #> 9 M750 1990-09-01 6480 #> 10 M750 1990-10-01 6820 #> # ℹ 296 more rows # Split Data 80/20 splits <- initial_time_split(m750, prop = 0.8) ```