ExtendedIsolationForest¶
- class ExtendedIsolationForest(n_estimators: int = 100, max_samples='auto', extension_level: int | None = None, random_state: int | RandomState | None = None, window_size: int = 10, stride: int = 1)[source]¶
Bases:
BaseSeriesAnomalyDetectorExtended Isolation Forest (EIF) for anomaly detection.
The Extended Isolation Forest [1] generalises the Isolation Forest [2] by isolating observations with randomly oriented hyperplanes instead of axis-parallel cuts. Axis-parallel splitting introduces artefacts in the resulting anomaly score map (bands of low score aligned with the feature axes); using random hyperplanes removes this bias and yields a more consistent score field, while retaining the linear-time isolation mechanism.
Anomalies are isolated closer to the root of each tree and therefore have shorter expected path lengths. The anomaly score of a point
xiss(x) = 2 ** (-E[h(x)] / c(psi)), whereE[h(x)]is the mean path length ofxacross the forest,psiis the sub-sampling size andcis the expected path length of an unsuccessful binary-search-tree search. Scores approach1for anomalies and0.5or below for normal points.The detector operates on sliding windows of the input series (see
window_sizeandstride). For multivariate series the channels within a window are stacked into a single feature vector, so each window haswindow_size * n_channelsfeatures.- Parameters:
- n_estimatorsint, default=100
The number of isolation trees in the ensemble.
- max_samplesint, float or “auto”, default=”auto”
The number of windows to draw (without replacement) to train each tree.
If
int, drawmax_sampleswindows.If
float, drawmax_samples * n_windowswindows.If
"auto", usemin(256, n_windows).
- extension_levelint or None, default=None
The degree of freedom of the splitting hyperplanes. Must be between
0andn_features - 1, wheren_features = window_size * n_channels.0recovers the standard axis-parallel Isolation Forest;n_features - 1uses fully extended hyperplanes. IfNone, the maximum valuen_features - 1is used.- random_stateint, np.random.RandomState or None, default=None
Seed or random state for reproducibility of the sub-sampling and the random hyperplanes.
- window_sizeint, default=10
Size of the sliding window.
- strideint, default=1
Stride of the sliding window.
Notes
Capabilities ¶ Missing Values
No
Multithreading
No
Univariate
Yes
Multivariate
Yes
References
[1]Hariri, S., Kind, M. C., & Brunner, R. J. (2021). Extended Isolation Forest. IEEE Transactions on Knowledge and Data Engineering, 33(4), 1479-1489. https://doi.org/10.1109/TKDE.2019.2947676
[2]Liu, F. T., Ting, K. M., & Zhou, Z. H. (2008). Isolation Forest. In 2008 Eighth IEEE International Conference on Data Mining (pp. 413-422).
Examples
>>> import numpy as np >>> from aeon.anomaly_detection.series.outlier_detection import ( ... ExtendedIsolationForest, ... ) >>> rng = np.random.default_rng(0) >>> X = rng.normal(size=200) >>> X[100] = 10.0 >>> detector = ExtendedIsolationForest(window_size=1, random_state=0) >>> scores = detector.fit_predict(X) >>> int(np.argmax(scores)) 100
Methods
clone([random_state])Obtain a clone of the object with the same hyperparameters.
fit(X[, y, axis])Fit time series anomaly detector to X.
fit_predict(X[, y, axis])Fit time series anomaly detector and find anomalies for X.
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.
predict(X[, axis])Find anomalies in X.
reset([keep])Reset the object to a clean post-init state.
set_fit_request(*[, axis])Configure whether metadata should be requested to be passed to the
fitmethod.set_params(**params)Set the parameters of this estimator.
set_predict_request(*[, axis])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(X, y=None, axis=1)[source]¶
Fit time series anomaly detector to X.
If the tag
fit_is_emptyis true, this just sets theis_fittedtag to true. Otherwise, it checksselfcan handleX, formatsXinto the structure required byselfthen passesX(and possiblyy) to_fit.- Parameters:
- Xone of aeon.base._base_series.VALID_SERIES_INPUT_TYPES
The time series to fit the model to. A valid aeon time series data structure. See aeon.base._base_series.VALID_SERIES_INPUT_TYPES for aeon supported types.
- yone of aeon.base._base_series.VALID_SERIES_INPUT_TYPES, default=None
The target values for the time series. A valid aeon time series data structure. See aeon.base._base_series.VALID_SERIES_INPUT_TYPES for aeon supported types.
- axisint
The time point axis of the input series if it is 2D. If
axis==0, it is assumed each column is a time series and each row is a time point. i.e. the shape of the data is(n_timepoints, n_channels).axis==1indicates the time series are in rows, i.e. the shape of the data is(n_channels, n_timepoints).
- Returns:
- BaseSeriesAnomalyDetector
The fitted estimator, reference to self.
- fit_predict(X, y=None, axis=1) ndarray[source]¶
Fit time series anomaly detector and find anomalies for X.
- Parameters:
- Xone of aeon.base._base_series.VALID_SERIES_INPUT_TYPES
The time series to fit the model to. A valid aeon time series data structure. See aeon.base._base_series.VALID_INPUT_TYPES for aeon supported types.
- yone of aeon.base._base_series.VALID_SERIES_INPUT_TYPES, default=None
The target values for the time series. A valid aeon time series data structure. See aeon.base._base_series.VALID_SERIES_INPUT_TYPES for aeon supported types.
- axisint, default=1
The time point axis of the input series if it is 2D. If
axis==0, it is assumed each column is a time series and each row is a time point. i.e. the shape of the data is(n_timepoints, n_channels).axis==1indicates the time series are in rows, i.e. the shape of the data is(n_channels, n_timepoints).
- Returns:
- np.ndarray
A boolean, int or float array of length len(X), where each element indicates whether the corresponding subsequence is anomalous or its anomaly score.
- 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)¶
Get parameters for this estimator.
- Parameters:
- deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns:
- paramsdict
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.
- predict(X, axis=1) ndarray[source]¶
Find anomalies in X.
- Parameters:
- Xone of aeon.base._base_series.VALID_SERIES_INPUT_TYPES
The time series to fit the model to. A valid aeon time series data structure. See aeon.base._base_series.VALID_SERIES_INPUT_TYPES for aeon supported types.
- axisint, default=1
The time point axis of the input series if it is 2D. If
axis==0, it is assumed each column is a time series and each row is a time point. i.e. the shape of the data is(n_timepoints, n_channels).axis==1indicates the time series are in rows, i.e. the shape of the data is(n_channels, n_timepoints).
- Returns:
- np.ndarray
A boolean, int or float array of length len(X), where each element indicates whether the corresponding subsequence is anomalous or its anomaly score.
- 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 temporary callback context attached by scikit-learn
- 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$') ExtendedIsolationForest¶
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.
- Returns:
- selfobject
The updated object.
- set_params(**params)¶
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline). The latter have parameters of the form<component>__<parameter>so that it’s possible to update each component of a nested object.- Parameters:
- **paramsdict
Estimator parameters.
- Returns:
- selfestimator instance
Estimator instance.
- set_predict_request(*, axis: bool | None | str = '$UNCHANGED$') ExtendedIsolationForest¶
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.
- Returns:
- selfobject
The updated object.