Skip to main content

IsolationForest

Struct IsolationForest 

Source
#[non_exhaustive]
pub struct IsolationForest { /* private fields */ }
Expand description

Isolation Forest for anomaly detection.

Builds an ensemble of random isolation trees. Points that are isolated in fewer splits (shorter path lengths) receive higher anomaly scores.

§Algorithm

  1. Fit: Build n_estimators isolation trees, each trained on a random subsample of max_samples points.
  2. Score: For each point, compute the average path length across all trees. Normalize to [0, 1] using score = 2^(-E[h(x)] / c(max_samples)).
  3. Label: Scores above the threshold (determined by contamination) are labelled as anomalies (-1), others as normal (1).

§Examples

use scry_learn::anomaly::IsolationForest;

let mut ifo = IsolationForest::new()
    .n_estimators(100)
    .contamination(0.05);
ifo.fit(&data).unwrap();
let labels = ifo.predict_labels(&data);

Implementations§

Source§

impl IsolationForest

Source

pub fn new() -> Self

Create a new IsolationForest with default parameters.

Defaults: 100 estimators, 256 max samples, 0.1 contamination.

Source

pub fn n_estimators(self, n: usize) -> Self

Set the number of isolation trees (default: 100).

Source

pub fn max_samples(self, n: usize) -> Self

Set the subsample size per tree (default: 256).

Source

pub fn contamination(self, c: f64) -> Self

Set the expected contamination ratio (default: 0.1).

Must be in (0, 0.5]. Used to determine the anomaly score threshold.

Source

pub fn random_state(self, seed: u64) -> Self

Set the random seed for reproducibility.

Source

pub fn seed(self, s: u64) -> Self

Alias for random_state (consistent with other models).

Source

pub fn fit(&mut self, features: &[Vec<f64>]) -> Result<()>

Build isolation trees on the provided feature matrix.

features is row-major: features[sample_idx][feature_idx].

§Errors

Returns ScryLearnError::EmptyDataset if features is empty. Returns ScryLearnError::InvalidParameter if contamination is out of range.

Source

pub fn predict(&self, features: &[Vec<f64>]) -> Vec<f64>

Compute anomaly scores for each sample.

Returns a Vec<f64> where values closer to 1.0 indicate anomalies and values closer to 0.0 indicate normal points.

Score formula: score = 2^(-E[h(x)] / c(ψ)) where E[h(x)] is the average path length and c(ψ) is the average BST path length for the training subsample size ψ.

Source

pub fn predict_labels(&self, features: &[Vec<f64>]) -> Vec<i8>

Predict anomaly labels: 1 for normal, -1 for anomaly.

Uses the contamination-based threshold computed during fit. Returns all 1 (normal) if the model has not been fitted.

Source

pub fn score_threshold(&self) -> f64

Returns the anomaly score threshold determined during fit.

Trait Implementations§

Source§

impl Clone for IsolationForest

Source§

fn clone(&self) -> IsolationForest

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for IsolationForest

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for IsolationForest

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Tunable for IsolationForest

Source§

fn set_param(&mut self, name: &str, value: ParamValue) -> Result<()>

Apply a named hyperparameter. Read more
Source§

fn clone_box(&self) -> Box<dyn Tunable>

Clone this model into a boxed trait object.
Source§

fn fit(&mut self, data: &Dataset) -> Result<()>

Train on a dataset.
Source§

fn predict(&self, features: &[Vec<f64>]) -> Result<Vec<f64>>

Predict on row-major features.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.