EnsembleForecaster¶
- class EnsembleForecaster(forecasters, weights=None, averaging_method='mean', iterative_strategy='component')[source]¶
Bases:
ComposableEstimatorMixin,BaseForecaster,IterativeForecastingMixinEnsemble forecaster that combines predictions from multiple forecasters.
Fits each component forecaster independently on the same series and combines their point forecasts using a specified averaging method. Equal weights and the mean are used by default; the median is recommended when robustness to a single poorly-fitted component is desired (as in SCUM).
- Parameters:
- forecasterslist of BaseForecaster or list of (str, BaseForecaster) tuples
Forecaster instances to include in the ensemble. Each element can be a forecaster instance or a
(name, estimator)pair. Names must be unique when supplied.- weightsarray-like of float or None, default=None
Per-forecaster weights used when
averaging_method="mean". Must be non-negative and have the same length asforecasters. Weights are normalised to sum to one before use. Ignored whenaveraging_method="median"oraveraging_methodis callable. IfNone, equal weights are used.- averaging_method{“mean”, “median”} or callable, default=”mean”
How to average the component forecasts at each horizon: -
"mean": (weighted) arithmetic mean. -"median": element-wise median;weightsis ignored. - callable : receives an array of shape(n_forecasters, prediction_horizon)(or(n_forecasters,)for a single-step prediction) and must return a scalar or array of shape(prediction_horizon,)respectively.- iterative_strategy{“component”, “ensemble”}, default=”component”
Strategy used by
iterative_forecast. If"component", each component forecaster is iterated forward independently using its own forecasts and the resulting forecast paths are aggregated at each horizon. If"ensemble", the ensemble prediction at each step is appended to a shared history and passed to each fitted component’spredictmethod. The default"component"strategy is the safer general-purpose choice for stateful forecasters, because it delegates multi-step recursion to each component.
- Attributes:
- forecasters_list of (str, BaseForecaster) tuples
Fitted copies of the component forecasters.
- weights_np.ndarray or None
Normalised weights used for combination, or
Nonewhenaveraging_methodis not"mean"or whenweightswas not supplied.- n_forecasters_int
Number of component forecasters.
See also
aeon.forecasting.stats.SCUMSimple Combination of Univariate Models forecaster.
Notes
Capabilities ¶ Missing Values
No
Multithreading
No
Univariate
Yes
Multivariate
No
Horizon
No
Exogenous
No
References
[1]Petropoulos, F. and Svetunkov, I. (2020). A simple combination of univariate models. International Journal of Forecasting, 36(1), 110-115.
Examples
>>> import numpy as np >>> from aeon.forecasting import NaiveForecaster >>> from aeon.forecasting.ensembles import EnsembleForecaster >>> y = np.array([1.0, 2.0, 3.0, 4.0, 5.0]) >>> forecasters = [ ... ("last", NaiveForecaster(strategy="last")), ... ("mean", NaiveForecaster(strategy="mean")), ... ] >>> ens = EnsembleForecaster(forecasters=forecasters, averaging_method="mean") >>> preds = ens.iterative_forecast(y, prediction_horizon=3) >>> preds.shape (3,)
Methods
clone([random_state])Obtain a clone of the object with the same hyperparameters.
fit(y[, exog, axis])Fit forecaster to series y.
forecast(y[, exog, axis])Forecast the next horizon steps ahead of
y.get_class_tag(tag_name[, raise_error, ...])Get tag value from estimator class (only class tags).
Get class tags from estimator class and all its parent classes.
get_fitted_params([deep])Get fitted parameters.
get_params([deep])Get parameters for this estimator.
get_tag(tag_name[, raise_error, ...])Get tag value from estimator class.
get_tags()Get tags from estimator.
iterative_forecast(y, prediction_horizon[, ...])Forecast
prediction_horizonsteps ahead by combining component forecasts.predict(y[, exog, axis])Predict the next horizon steps ahead.
reset([keep])Reset the object to a clean post-init state.
set_fit_request(*[, axis, exog])Configure whether metadata should be requested to be passed to the
fitmethod.set_params(**params)Set estimator parameters, including nested forecaster parameters.
set_predict_request(*[, axis, exog])Configure whether metadata should be requested to be passed to the
predictmethod.set_tags(**tag_dict)Set dynamic tags to given values.
- clone(random_state=None)[source]¶
Obtain a clone of the object with the same hyperparameters.
A clone is a different object without shared references, in post-init state. This function is equivalent to returning
sklearn.cloneofself. Equal in value totype(self)(**self.get_params(deep=False)).- Parameters:
- random_stateint, RandomState instance, or None, default=None
Sets the random state of the clone. If
None, the random state is not set. Ifint,random_stateis the seed used by the random number generator. IfRandomStateinstance,random_stateis the random number generator.
- Returns:
- estimatorobject
Instance of
type(self), clone of self (see above)
- fit(y, exog=None, axis=1)[source]¶
Fit forecaster to series y.
Fit a forecaster to predict self.horizon steps ahead using y.
- Parameters:
- ynp.ndarray
A time series on which to learn a forecaster to predict horizon ahead.
- exognp.ndarray, default =None
Optional target-time exogenous values aligned with
y.
- Returns:
- self
Fitted BaseForecaster.
- forecast(y, exog=None, axis=1) float[source]¶
Forecast the next horizon steps ahead of
y.By default this is simply fit followed by predict.
- Parameters:
- ynp.ndarray
A time series to predict the next horizon value for. Must be of shape
(n_channels, n_timepoints)if a multivariate time series.- exognp.ndarray, default =None
Optional target-time exogenous values aligned with
y.
- Returns:
- float
single prediction self.horizon steps ahead of y.
- classmethod get_class_tag(tag_name, raise_error=True, tag_value_default=None)[source]¶
Get tag value from estimator class (only class tags).
- Parameters:
- tag_namestr
Name of tag value.
- raise_errorbool, default=True
Whether a
ValueErroris raised when the tag is not found.- tag_value_defaultany type, default=None
Default/fallback value if tag is not found and error is not raised.
- Returns:
- tag_value
Value of the
tag_nametag in cls. If not found, returns an error ifraise_errorisTrue, otherwise it returnstag_value_default.
- Raises:
- ValueError
if
raise_errorisTrueandtag_nameis not inself.get_tags().keys()
Examples
>>> from aeon.classification import DummyClassifier >>> DummyClassifier.get_class_tag("capability:multivariate") True
- classmethod get_class_tags()[source]¶
Get class tags from estimator class and all its parent classes.
- Returns:
- collected_tagsdict
Dictionary of tag name and tag value pairs. Collected from
_tagsclass attribute via nested inheritance. These are not overridden by dynamic tags set byset_tagsor class__init__calls.
- get_fitted_params(deep=True)[source]¶
Get fitted parameters.
- State required:
Requires state to be “fitted”.
- Parameters:
- deepbool, default=True
If
True, will return the fitted parameters for this estimator and contained subobjects that are estimators.
- Returns:
- fitted_paramsdict
Fitted parameter names mapped to their values.
- get_params(deep=True)[source]¶
Get parameters for this estimator.
Returns the parameters given in the constructor as well as the estimators contained within the composable estimator if deep.
- Parameters:
- deepbool, default=True
If
True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns:
- paramsmapping of string to any
Parameter names mapped to their values.
- get_tag(tag_name, raise_error=True, tag_value_default=None)[source]¶
Get tag value from estimator class.
Includes dynamic and overridden tags.
- Parameters:
- tag_namestr
Name of tag to be retrieved.
- raise_errorbool, default=True
Whether a
ValueErroris raised when the tag is not found.- tag_value_defaultany type, default=None
Default/fallback value if tag is not found and error is not raised.
- Returns:
- tag_value
Value of the
tag_nametag in self. If not found, returns an error ifraise_errorisTrue, otherwise it returnstag_value_default.
- Raises:
- ValueError
if raise_error is
Trueandtag_nameis not inself.get_tags().keys()
Examples
>>> from aeon.classification import DummyClassifier >>> d = DummyClassifier() >>> d.get_tag("capability:multivariate") True
- get_tags()[source]¶
Get tags from estimator.
Includes dynamic and overridden tags.
- Returns:
- collected_tagsdict
Dictionary of tag name and tag value pairs. Collected from
_tagsclass attribute via nested inheritance and then any overridden and new tags from__init__orset_tags.
- iterative_forecast(y, prediction_horizon, exog=None, *, future_exog=None)[source]¶
Forecast
prediction_horizonsteps ahead by combining component forecasts.The
iterative_strategyparameter controls the recursive semantics. With"component", each component forecaster produces its own full forecast path, then paths are aggregated horizon by horizon. With"ensemble", the ensemble produces one aggregated prediction at a time and appends that prediction to a shared history passed topredict. Components are fitted once on the original history; whether the extended context affects later steps depends on the component’spredictimplementation.- Parameters:
- ynp.ndarray
The in-sample series.
- prediction_horizonint
Number of future steps to forecast.
- exognp.ndarray or None, default=None
Exogenous series are not currently supported by
EnsembleForecaster; non-None values are rejected during validation.- future_exognp.ndarray or None, default=None
Future exogenous values are not currently supported by
EnsembleForecaster; non-None values are rejected during validation.
- Returns:
- np.ndarray
Shape
(prediction_horizon,)combined forecast.
- predict(y, exog=None, axis=1) float[source]¶
Predict the next horizon steps ahead.
- Parameters:
- ynp.ndarray
A time series to predict the next horizon value for.
- exognp.ndarray, default =None
Optional exogenous values for the prediction target. For models fitted with exogenous variables, this should contain the exogenous values needed to make the next prediction.
- Returns:
- float
single prediction self.horizon steps ahead of y.
- reset(keep=None)[source]¶
Reset the object to a clean post-init state.
After a
self.reset()call,selfis equal or similar in value totype(self)(**self.get_params(deep=False)), assuming no other attributes were kept usingkeep.- Detailed behaviour:
- removes any object attributes, except:
hyper-parameters (arguments of
__init__) object attributes containing double-underscores, i.e., the string “__”
runs
__init__with current values of hyperparameters (result ofget_params)- Not affected by the reset are:
object attributes containing double-underscores class and object methods, class attributes any attributes specified in the
keepargument
- Parameters:
- keepNone, str, or list of str, default=None
If
None, all attributes are removed except hyperparameters. Ifstr, only the attribute with this name is kept. Iflistofstr, only the attributes with these names are kept.
- Returns:
- selfobject
Reference to self.
- Raises:
- TypeError
If ‘keep’ is not a string or a list of strings.
- set_fit_request(*, axis: bool | None | str = '$UNCHANGED$', exog: bool | None | str = '$UNCHANGED$') EnsembleForecaster¶
Configure whether metadata should be requested to be passed to the
fitmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.Added in version 1.3.
- Parameters:
- axisstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
axisparameter infit.- exogstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
exogparameter infit.
- Returns:
- selfobject
The updated object.
- set_predict_request(*, axis: bool | None | str = '$UNCHANGED$', exog: bool | None | str = '$UNCHANGED$') EnsembleForecaster¶
Configure whether metadata should be requested to be passed to the
predictmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed topredictif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topredict.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.Added in version 1.3.
- Parameters:
- axisstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
axisparameter inpredict.- exogstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
exogparameter inpredict.
- Returns:
- selfobject
The updated object.