ForecastingOptunaSearchCV
Perform Optuna search cross-validation to find optimal model hyperparameters.
Quickstart
from sktime.forecasting.model_selection import ForecastingOptunaSearchCV
estimator = ForecastingOptunaSearchCV(forecaster, cv, param_grid, scoring=None, strategy='refit', update_behaviour='full_refit', refit=True, verbose=0, return_n_best_forecasters=1, backend='loky', error_score=nan, n_evals=100, sampler=None)Parameters(13)
- 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 of optuna samplers
- Dictionary with parameters names as keys and lists of parameter distributions from which to sample parameter values. e.g. {“forecaster”: optuna.distributions.CategoricalDistribution((STLForecaster(), ThetaForecaster())}
- 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.
- verbose: int, optional (default=0)
- Verbosity level. The higher, the more messages.
- return_n_best_forecastersint, default=1
- Number of best forecasters to return.
- backendstr, default=”loky”
Backend to use when running the fit.
Backend must be one supported by
optuna:“loky” (default): joblib’s LokyBackend.
“threading”: joblib’s ThreadingBackend.
“multiprocessing”: joblib’s MultiprocessingBackend.
- error_score‘raise’ or numeric, default=np.nan
- Value to assign to the score if an error occurs in estimator fitting.
- n_evalsint, default=100
- Number of parameter settings that are sampled. n_iter trades off runtime vs quality of the solution.
- samplerOptuna sampler, optional (default=None)
- e.g. optuna.samplers.TPESampler(seed=42)
Examples
>>> from sktime.forecasting.model_selection import (
... ForecastingOptunaSearchCV,
... )
>>> from sktime.datasets import load_shampoo_sales
>>> import warnings
>>> warnings. simplefilter (action = "ignore", category = FutureWarning)
>>> from sktime.forecasting.base import ForecastingHorizon
>>> from sktime.split import ExpandingWindowSplitter
>>> from sktime.split import temporal_train_test_split
>>> from sklearn.preprocessing import MinMaxScaler, RobustScaler
>>> from sktime.forecasting.compose import TransformedTargetForecaster
>>> from sktime.transformations.adapt import TabularToSeriesAdaptor
>>> from sktime.transformations.detrend import Deseasonalizer, Detrender
>>> from sktime.forecasting.naive import NaiveForecaster
>>> from sktime.forecasting.trend import STLForecaster, TrendForecaster
>>> import optuna
>>> from optuna.distributions import CategoricalDistribution
>>> y = load_shampoo_sales ()
>>> y_train, y_test = temporal_train_test_split (y = y, test_size = 6)
>>> fh = ForecastingHorizon (y_test. index, is_relative = False). to_relative (
... cutoff = y_train. index [- 1 ]
... )
>>> cv = ExpandingWindowSplitter (fh = fh, initial_window = 24, step_length = 1)
>>> forecaster = TransformedTargetForecaster (
... steps = [
... ("detrender", Detrender ()),
... ("scaler", RobustScaler ()),
... ("minmax2", MinMaxScaler ((1, 10))),
... ("forecaster", NaiveForecaster ()),
... ]
... )
>>> param_grid = {
... "scaler__with_scaling": CategoricalDistribution (
... (True, False)
... ),
... "forecaster": CategoricalDistribution (
... (NaiveForecaster (), TrendForecaster ())
... ),
... }
>>> gscv = ForecastingOptunaSearchCV (
... forecaster = forecaster,
... param_grid = param_grid,
... cv = cv,
... n_evals = 10,
... )
>>> gscv. fit (y) ForecastingOptunaSearchCV(
... )
>>> print (f " { gscv. best_params_ =} ")