ForecastingGridSearchCV
Perform grid-search cross-validation to find optimal model parameters.
Quickstart
from sktime.forecasting.model_selection import ForecastingGridSearchCV
estimator = ForecastingGridSearchCV(forecaster, cv, param_grid, scoring=None, strategy='refit', update_behaviour='full_refit', refit=True, tune_by_instance=False, tune_by_variable=False, verbose=0, return_n_best_forecasters=1, error_score=nan, backend='loky', backend_params=None, n_jobs='deprecated')Parameters(15)
- forecastersktime forecaster, BaseForecaster instance or interface compatible
The forecaster to tune, must implement the sktime forecaster interface. sklearn regressors can be used, but must first be converted to forecasters via one of the reduction compositors, e.g., via
make_reduction- cvsktime time series splitter
Re-sampling strategy for cross-validation, must be an instance of a sktime time series splitter, e.g.
SlidingWindowSplitter()- param_griddict or list of dictionaries
Model tuning parameters of the forecaster to evaluate
Encodes the search spaces for the parameters, a countable set of parameter combinations. Parsed as following:
if
dict, then the keys are parameter names (str) and the values are lists of parameter settings to try as values. Parameters not set are kept as defaults. A single non-default parameter setting can be provided as a list with one element, e.g.,{"window_length": [5]}.if
list of dict, then each element of the list is a separate dict as described above, and the search space is the union of the search spaces defined by each dict.
- scoringsktime metric (BaseMetric), str, or callable, optional (default=MAPE)
scoring metric to use in tuning the forecaster
sktime metric objects (BaseMetric) descendants can be searched with the
registry.all_estimatorssearch utility, for instance viaall_estimators("metric", as_dataframe=True)If callable, must have signature
(y_true: 1D np.ndarray, y_pred: 1D np.ndarray) -> float, withnp.ndarraybeing of the same length, and lower being better.If str, uses registry.resolve_alias to resolve to one of the above. Valid strings are valid registry.craft specs, which include string repr-s of any BaseMetric object, e.g., “MeanSquaredError()”; and keys of registry.ALIAS_DICT referring to metrics.
If None, defaults to
MeanAbsolutePercentageError()
- strategy{“refit”, “update”, “no-update_params”}, optional, default=”refit”
data ingestion strategy in fitting cv, passed to
evaluateinternally defines the ingestion mode when the forecaster sees new data when window expands"refit"= a new copy of the forecaster is fitted to each training window"update"= forecaster is updated with training window data, in sequence provided"no-update_params"= fit to first training window, re-used without fit or update
- update_behaviourstr, optional, default = “full_refit”
one of {“full_refit”, “inner_only”, “no_update”} behaviour of the forecaster when calling update
"full_refit"= both tuning parameters and inner estimator refit on all data seen"inner_only"= tuning parameters are not re-tuned, inner estimator is updated"no_update"= neither tuning parameters nor inner estimator are updated
- refitbool, optional (default=True)
Whether to refit the forecaster with the best parameters on the entire data.
True = refit the forecaster with the best parameters on the entire data in
fitFalse = no refitting takes place. The forecaster cannot be used to predict. This is to be used to tune the hyperparameters, and then use the estimator as a parameter estimator, e.g., via
get_fitted_paramsorPluginParamsForecaster.
- tune_by_instancebool, optional (default=False)
Whether to tune parameter by each time series instance separately, in case of
PanelorHierarchicaldata passed to the tuning estimator. Only applies if time series passed arePanelorHierarchical.If
True, clones of the forecaster will be fit to each instance separately, and are available in fields of the forecasters_ attribute. Has the same effect as applyingForecastByLevelwrapper to self.If
False, the same best parameter is selected for all instances.
- tune_by_variablebool, optional (default=False)
Whether to tune parameter by each time series variable separately, in case of multivariate data passed to the tuning estimator. Only applies if time series passed are strictly multivariate.
If
True, clones of the forecaster will be fit to each variable separately, and are available in fields of the forecasters_ attribute. Has the same effect as applyingColumnEnsembleForecasterwrapper to self.If
False, the same best parameter is selected for all variables.
- verbose: int, optional (default=0)
- Verbosity level. The higher, the more messages.
- return_n_best_forecastersint, default=1
In case the n best forecaster should be returned, this value can be set and the n best forecasters will be assigned to n_best_forecasters_. Set return_n_best_forecasters to -1 to return all forecasters.
- return_train_scorebool, optional (default=False)
Whether to include train scores in
cv_results_.If True, the
cv_results_attribute will store training scores for each parameter combination. This can be useful for diagnosing overfitting, but may increase the memory usage of the estimator.If False, the
cv_results_attribute will not be created.- error_score“raise” or numeric, default=np.nan
- Value to assign to the score if an exception occurs in estimator fitting. If set to “raise”, the exception is raised. If a numeric value is given, FitFailedWarning is raised.
- backend{“dask”, “loky”, “multiprocessing”, “threading”,”ray”}, by default “loky”.
Runs parallel evaluate if specified and
strategyis set as “refit”.“None”: executes loop sequentally, simple list comprehension
“loky”, “multiprocessing” and “threading”: uses
joblib.Parallelloops“joblib”: custom and 3rd party
joblibbackends, e.g.,spark“dask”: uses
dask, requiresdaskpackage in environment“ray”: uses
ray, requiresraypackage in environment
Recommendation: Use “dask” or “loky” for parallel evaluate. “threading” is unlikely to see speed ups due to the GIL and the serialization backend (
cloudpickle) for “dask” and “loky” is generally more robust than the standardpicklelibrary used in “multiprocessing”.- backend_paramsdict, optional
additional parameters passed to the backend as config. Directly passed to
utils.parallel.parallelize. Valid keys depend on the value ofbackend:“None”: no additional parameters,
backend_paramsis ignored“loky”, “multiprocessing” and “threading”: default
joblibbackends any valid keys forjoblib.Parallelcan be passed here, e.g.,n_jobs, with the exception ofbackendwhich is directly controlled bybackend. Ifn_jobsis not passed, it will default to-1, other parameters will default tojoblibdefaults.“joblib”: custom and 3rd party
joblibbackends, e.g.,spark. any valid keys forjoblib.Parallelcan be passed here, e.g.,n_jobs,backendmust be passed as a key ofbackend_paramsin this case. Ifn_jobsis not passed, it will default to-1, other parameters will default tojoblibdefaults.“dask”: any valid keys for
dask.computecan be passed, e.g.,scheduler“ray”: The following keys can be passed:
“ray_remote_args”: dictionary of valid keys for
ray.init- “shutdown_ray”: bool, default=True; False prevents
rayfrom shuttingdown after parallelization.
Examples
>>> from sktime.datasets import load_shampoo_sales
>>> from sktime.forecasting.model_selection import ForecastingGridSearchCV
>>> from sktime.split import ExpandingWindowSplitter
>>> from sktime.forecasting.naive import NaiveForecaster
>>> y = load_shampoo_sales ()
>>> fh = [1, 2, 3 ]
>>> cv = ExpandingWindowSplitter (fh = fh)
>>> forecaster = NaiveForecaster ()
>>> param_grid = { "strategy": ["last", "mean", "drift" ]}
>>> gscv = ForecastingGridSearchCV (
... forecaster = forecaster,
... param_grid = param_grid,
... cv = cv)
>>> gscv. fit (y) ForecastingGridSearchCV(
... )
>>> y_pred = gscv. predict (fh) Advanced model meta-tuning (model selection) with multiple forecasters together with hyper-parametertuning at same time using sklearn notation:
>>> from sktime.datasets import load_shampoo_sales
>>> from sktime.forecasting.exp_smoothing import ExponentialSmoothing
>>> from sktime.forecasting.naive import NaiveForecaster
>>> from sktime.split import ExpandingWindowSplitter
>>> from sktime.forecasting.model_selection import ForecastingGridSearchCV
>>> from sktime.forecasting.compose import TransformedTargetForecaster
>>> from sktime.forecasting.theta import ThetaForecaster
>>> from sktime.transformations.impute import Imputer
>>> y = load_shampoo_sales ()
>>> pipe = TransformedTargetForecaster (steps = [
... ("imputer", Imputer ()),
... ("forecaster", NaiveForecaster ())])
>>> cv = ExpandingWindowSplitter (
... initial_window = 24,
... step_length = 12,
... fh = [1, 2, 3 ])
>>> gscv = ForecastingGridSearchCV (
... forecaster = pipe,
... param_grid = [{
... "forecaster": [NaiveForecaster (sp = 12)],
... "forecaster__strategy": ["drift", "last", "mean" ],
... },
... {
... "imputer__method": ["mean", "drift" ],
... "forecaster": [ThetaForecaster (sp = 12)],
... },
... {
... "imputer__method": ["mean", "median" ],
... "forecaster": [ExponentialSmoothing (sp = 12)],
... "forecaster__trend": ["add", "mul" ],
... },
... ],
... cv = cv,
... )
>>> gscv. fit (y) ForecastingGridSearchCV(
... )
>>> y_pred = gscv. predict (fh = [1, 2, 3 ])