Custom predictors for recursive multi-step forecasting¶
It may be interesting to include additional characteristics of the time series in addition to the lags, for example, the moving average of the n last values can be used to capture the trend of the series.
The ForecasterAutoregCustom class is very similar to the ForecasterAutoreg class described in the previous section, but it is the user who defines the function used to create the predictors.
# Custom function to create predictors# ==============================================================================defcreate_predictors(y):''' Create first 10 lags of a time series. Calculate moving average with window 20. '''lags=y[-1:-11:-1]mean=np.mean(y[-20:])predictors=np.hstack([lags,mean])returnpredictors
1 2 3 4 5 6 7 8 910
# Create and fit forecaster# ==============================================================================forecaster=ForecasterAutoregCustom(regressor=RandomForestRegressor(random_state=123),fun_predictors=create_predictors,window_size=20)forecaster.fit(y=data_train)forecaster
1 2 3 4 5 6 7 8 910111213141516
=======================
ForecasterAutoregCustom
=======================
Regressor: RandomForestRegressor(random_state=123)
Predictors created with function: create_predictors
Window size: 20
Included exogenous: False
Type of exogenous variable: None
Exogenous variables names: None
Training range: [Timestamp('1991-07-01 00:00:00'), Timestamp('2005-06-01 00:00:00')]
Training index type: DatetimeIndex
Training index frequency: MS
Regressor parameters: {'bootstrap': True, 'ccp_alpha': 0.0, 'criterion': 'squared_error', 'max_depth': None, 'max_features': 'auto', 'max_leaf_nodes': None, 'max_samples': None, 'min_impurity_decrease': 0.0, 'min_samples_leaf': 1, 'min_samples_split': 2, 'min_weight_fraction_leaf': 0.0, 'n_estimators': 100, 'n_jobs': None, 'oob_score': False, 'random_state': 123, 'verbose': 0, 'warm_start': False}
Creation date: 2021-12-06 23:30:30
Last fit date: 2021-12-06 23:30:31
Skforecast version: 0.4.0