# IsolationForest

### *class* cuml.ensemble.IsolationForest(, n_estimators=100, max_samples='auto', max_depth=None, max_features=1.0, bootstrap=False, random_state=None, contamination='auto', verbose=False, output_type=None)

GPU-accelerated Isolation Forest for anomaly detection.

Isolation Forest is an unsupervised learning algorithm for anomaly detection
that works by isolating anomalies rather than profiling normal data points.
It uses the concept that anomalies are few and different, so they are easier
to isolate.

The algorithm builds an ensemble of isolation trees where each tree is
constructed by randomly selecting a feature and then randomly selecting a
split value between the minimum and maximum values of the selected feature.
Anomalies have shorter average path lengths in the trees because they are
easier to isolate.

* **Parameters:**
  **n_estimators**
  : The number of isolation trees in the ensemble.

  **max_samples**
  : The number of samples to draw from X to train each isolation tree.
    - If int, then draw `max_samples` samples.
    - If float, then draw `max_samples * n_samples` samples.
    - If “auto”, then `max_samples=min(256, n_samples)`.

  **max_depth**
  : Maximum depth of each isolation tree. If None, depth is set to
    `ceil(log2(max_samples))`, which is the theoretical maximum depth
    needed to isolate any sample.

  **max_features**
  : The number of features to draw from X to train each isolation tree.
    - If int, draw exactly `max_features` features.
    - If float, draw `max_features * n_features` features.

  **bootstrap**
  : If True, individual trees are fit on random subsets of the training
    data sampled with replacement. Otherwise, sampling is without
    replacement.

  **random_state**
  : Controls random row sampling and split selection. Pass an int for
    reproducible results across runs.

  **contamination**
  : The proportion of outliers in the data set, used to define the offset
    for `decision_function` and `predict`.
    - If `"auto"`, the offset is set to -0.5.
    - If float, must be in the range (0, 0.5] and the offset is set to
      the corresponding training-score quantile.

  **verbose**
  : Sets logging level. It must be one of `cuml.common.logger.level_*`.
    See [Verbosity Levels](../../cuml/index.html.md#verbosity-levels) for more info.

  **output_type**
  : Return results and set estimator attributes to the indicated output
    type. If None, the output type set at the module level
    (`cuml.global_settings.output_type`) will be used. See
    [Output Data Type Configuration](../../cuml/index.html.md#output-data-type-configuration) for more info.
* **Attributes:**
  **n_features_in_**
  : Number of features seen during fit.

  **offset_**
  : Offset used to compute [`decision_function`](#cuml.ensemble.IsolationForest.decision_function) from raw anomaly scores.

  **max_samples_**
  : The actual number of samples used to train each tree.

### Methods

| [`as_nvforest`](#cuml.ensemble.IsolationForest.as_nvforest)(self[, layout, ...])   | Create a nvForest model from the Treelite-exported Isolation Forest.   |
|-------------------------------------------------------------------------------------|------------------------------------------------------------------------|
| [`as_treelite`](#cuml.ensemble.IsolationForest.as_treelite)(self)                  | Converts this estimator to a Treelite model.                           |
| [`decision_function`](#cuml.ensemble.IsolationForest.decision_function)(self, X)         | Compute the decision function of X.                                    |
| [`fit`](#cuml.ensemble.IsolationForest.fit)(self, X[, y])                  | Fit the Isolation Forest model.                                        |
| [`fit_predict`](#cuml.ensemble.IsolationForest.fit_predict)(self, X[, y])          | Fit the model and predict on X.                                        |
| [`predict`](#cuml.ensemble.IsolationForest.predict)(self, X)                   | Predict if samples are anomalies or not.                               |
| [`score_samples`](#cuml.ensemble.IsolationForest.score_samples)(self, X)             | Compute the anomaly score of X.                                        |

### Notes

The implementation is based on the original Isolation Forest paper:
Liu, F. T., Ting, K. M., & Zhou, Z. H. (2008). Isolation forest.
In 2008 Eighth IEEE International Conference on Data Mining (pp. 413-422).

**Scoring**

The anomaly score is computed as: s(x) = 2^(-E[h(x)] / c(n))

where:

- h(x) is the path length of sample x in an isolation tree
- E[h(x)] is the average path length over all trees
- c(n) is the average path length in an unsuccessful search in a BST

Higher values of s indicate more anomalous samples. `score_samples()`
returns the negative of s, so lower values indicate more anomalous samples.
`decision_function()` subtracts `offset_` from these scores; negative
decision-function values are predicted as anomalies.

Fitted models can be exported to Treelite with `as_treelite()` and loaded
into nvForest with `as_nvforest()`. `as_sklearn()` converts a fitted
model into an equivalent `sklearn.ensemble.IsolationForest`;
`estimators_samples_` is not available on the converted model because
cuML does not record per-tree sample indices.

### Examples

```python
>>> import cupy as cp
>>> from cuml.ensemble import IsolationForest

>>> # Create synthetic data with some outliers
>>> rng = cp.random.default_rng(42)
>>> X_inliers = rng.standard_normal((100, 2), dtype=cp.float32)
>>> X_outliers = rng.uniform(low=-4, high=4, size=(20, 2)).astype(cp.float32)
>>> X = cp.vstack([X_inliers, X_outliers])

>>> # Fit the model
>>> clf = IsolationForest(n_estimators=100, random_state=42)
>>> clf.fit(X)
IsolationForest(random_state=42)

>>> # Predict anomalies (-1 for anomaly, 1 for normal)
>>> predictions = clf.predict(X)

>>> # Get anomaly scores (lower = more anomalous)
>>> scores = clf.score_samples(X)
```

<!-- !! processed by numpydoc !! -->

#### as_nvforest(self, layout='depth_first', default_chunk_size=None, align_bytes=None)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/ensemble/isolation_forest.pyx#L717)

Create a nvForest model from the Treelite-exported Isolation Forest.

* **Returns:**
  **nvforest_model**
  : A forest inference model that predicts average path length.

<!-- !! processed by numpydoc !! -->

#### as_sklearn()[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/interop.py#L206)

Convert this estimator into an equivalent scikit-learn (or scikit-learn
extension) estimator.

* **Returns:**
  sklearn.base.BaseEstimator
  : A scikit-learn compatible estimator instance that mirrors the trained
    state of the current estimator.

<!-- !! processed by numpydoc !! -->

#### as_treelite(self)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/ensemble/isolation_forest.pyx#L702)

Converts this estimator to a Treelite model.

The exported Treelite model predicts average path length across the
isolation trees.

* **Returns:**
  treelite.Model

<!-- !! processed by numpydoc !! -->

#### decision_function(self, X)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/ensemble/isolation_forest.pyx#L818)

Compute the decision function of X.

The decision function is `score_samples(X) - offset_`.
Negative values indicate anomalies.

* **Parameters:**
  **X**
  : The input samples.
* **Returns:**
  **scores**
  : The decision function. Negative values indicate anomalies.

<!-- !! processed by numpydoc !! -->

#### fit(self, X, y=None)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/ensemble/isolation_forest.pyx#L472)

Fit the Isolation Forest model.

* **Parameters:**
  **X**
  : The input samples. Internally, it will be converted to float32
    or float64.

  **y**
  : Not used, present for API consistency.
* **Returns:**
  **self**
  : Fitted estimator.

<!-- !! processed by numpydoc !! -->

#### fit_predict(self, X, y=None)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/ensemble/isolation_forest.pyx#L858)

Fit the model and predict on X.

* **Parameters:**
  **X**
  : The input samples.

  **y**
  : Not used, present for API consistency.
* **Returns:**
  **labels**
  : 1 for inliers, -1 for outliers.

<!-- !! processed by numpydoc !! -->

#### *classmethod* from_sklearn(model)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/interop.py#L222)

Create a cuml estimator from a scikit-learn estimator.

* **Parameters:**
  **model**
  : A compatible scikit-learn (or scikit-learn extension) estimator.
* **Returns:**
  cls
  : A new instance of this cuml estimator class that mirrors the
    state of the input estimator.

### Notes

`output_type` of the estimator is set to “numpy” by default, as these
cannot be inferred from training arguments. If something different is
required, then please use cuml’s output_type configuration utilities.

<!-- !! processed by numpydoc !! -->

#### get_params(deep=True)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/base.py#L191)

Returns a dict of all params owned by this class. If the child class
has appropriately overridden the `_get_param_names` method and does not
need anything other than what is there in this method, then it doesn’t
have to override this method

<!-- !! processed by numpydoc !! -->

#### predict(self, X)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/ensemble/isolation_forest.pyx#L838)

Predict if samples are anomalies or not.

Returns -1 for anomalies and 1 for normal samples.

* **Parameters:**
  **X**
  : The input samples.
* **Returns:**
  **labels**
  : 1 for inliers, -1 for outliers.

<!-- !! processed by numpydoc !! -->

#### score_samples(self, X)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/ensemble/isolation_forest.pyx#L787)

Compute the anomaly score of X.

Lower scores indicate more anomalous samples. The returned scores are
the negative of the anomaly scores defined in the original Isolation
Forest paper.

* **Parameters:**
  **X**
  : The input samples.
* **Returns:**
  **scores**
  : The anomaly scores. Lower values indicate more anomalous samples.
    Typical range is approximately [-1.0, 0.0], where values below
    `offset_` are predicted as anomalies.

<!-- !! processed by numpydoc !! -->

#### set_params(\*\*params)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/base.py#L200)

Accepts a dict of params and updates the corresponding ones owned by
this class. If the child class has appropriately overridden the
`_get_param_names` method and does not need anything other than what is,
there in this method, then it doesn’t have to override this method

<!-- !! processed by numpydoc !! -->
