rcf3
A Rust implementation of the Random Cut Forest (RCF) algorithm for anomaly detection in streaming data.
Overview
Random Cut Forest is an ensemble-based anomaly detection algorithm that uses randomized decision trees to identify anomalies in both univariate and multivariate time series data. It's particularly effective for:
- Anomaly Detection: Identifying unusual patterns in streaming data
- Time Series Analysis: Detecting changes in temporal patterns and seasonality
- Interpretability: Provides feature attribution scores to understand which dimensions contribute to anomalies
This implementation provides both Rust and Python APIs with support for advanced features like missing value imputation, neighborhood search, and time series forecasting.
Features
The crate supports several compile-time features:
std (enabled by default)
Enables use of the Rust standard library. Disable this for no_std environments:
[]
= { = "0.1", = false }
serde (enabled by default)
Provides JSON serialization and deserialization support for Forest objects. Allows saving and loading trained models:
[]
= { = "0.1", = ["serde", "std"] }
python (optional)
Builds Python bindings using PyO3, enabling use from Python. Automatically enables serde and std:
[]
= { = "0.1", = ["python"] }
To use just the core algorithm without serialization:
[]
= { = "0.1", = false, = ["std"] }
Configuration Options
All forests are configured via RcfConfig with the following parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
input_dim |
usize |
Required | Number of base feature dimensions per observation (before shingling) |
shingle_size |
usize |
1 |
Temporal window size. When internal_shingling is true, the effective model dimension becomes input_dim * shingle_size |
capacity |
usize |
256 |
Maximum number of points stored per tree |
num_trees |
usize |
50 |
Number of trees in the ensemble |
time_decay |
f64 |
0.0 |
Exponential time-decay rate applied to sampling weights. 0.0 uses the default: 0.1 / capacity |
output_after |
usize |
0 |
Minimum number of updates before score/attribution/etc. return non-trivial results. 0 uses the default: 1 + capacity / 4 |
internal_shingling |
bool |
true |
When true, the forest automatically manages the shingle buffer so callers pass one base observation at a time |
initial_accept_fraction |
f64 |
0.125 |
Controls how quickly the sampler fills to capacity during warm-up |
Rust API
Creating a Forest
Use the builder pattern to create a configured forest:
use Forest;
let forest = builder // 2D input, shingle size 1 (default)
.num_trees
.capacity
.build?;
With time series (shingling):
let forest = builder // 4D input, window size 8
.num_trees
.capacity
.time_decay
.build?;
internal_shingling is true by default, so you only need to set it explicitly when turning it off.
From a config object:
use ;
let config = new
.with_num_trees
.with_capacity
.with_shingle_size;
let forest = from_config?;
Basic Operations
For online anomaly detection, the recommended order is to score first and then update. The snippets below are minimal API examples showing each operation separately.
Update the forest with a new observation:
let point = vec!;
forest.update?;
Check if the forest has warmed up:
if forest.is_ready
Get the number of observations processed:
println!;
Scoring Methods
Anomaly Score (RCF Score):
The primary anomaly metric. Lower scores indicate normal behavior; higher scores indicate anomalies.
let point = vec!;
let score = forest.score?;
if score > threshold
Displacement Score:
A displacement-based anomaly metric that measures how far a point is from the expected region:
let displacement = forest.displacement_score?;
Density Estimate:
Returns an estimate of the probability density at the given point. Higher density = normal behavior:
let density = forest.density?;
Feature Attribution
Understand which dimensions contribute to the anomaly score:
let point = vec!; // Third dimension is anomalous
let attribution = forest.attribution?;
for in attribution.iter.enumerate
Each dimension returns below and above scores indicating how much that dimension contributes to the overall anomaly.
Neighborhood Search
Find approximate near-neighbors of a query point:
let point = vec!;
let neighbors = forest.near_neighbors?;
for neighbor in neighbors
Parameters:
top_k: Maximum number of neighbors to return (default 10)percentile: Percentile threshold for filtering candidates (default 50)
Missing Value Imputation
Impute missing dimensions using learned data distribution:
let point = vec!; // Missing value at index 1
let missing = vec!; // Indices of missing dimensions
let imputed = forest.impute?;
println!;
Parameters:
point: Full-dimensional query (missing values will be ignored)missing: Indices of dimensions to imputecentrality: Controls how deterministic the imputation is (1.0 = always pick nearest)
Time Series Forecasting
Predict future observations (requires internal_shingling = true and shingle_size > 1):
let forest = builder
.build?;
// Feed observations one at a time
for point in stream
// Predict the next 5 observations
let predictions = forest.extrapolate?;
// Returns a flat list of length 5 * input_dim
Serialization
Save and load trained models using JSON:
// Save to string
let json_str = forest.to_json?;
// Save to file
forest.save_json?;
// Load from string
let loaded = from_json?;
// Load from file
let loaded = load_json?;
Python API
The Python API mirrors the Rust interface. Create forests, update them, and compute scores exactly like in Rust:
Creating a Forest
=
With time series:
=
Basic Operations
# Update the forest
=
# Check if ready
=
# Get the number of observations processed
Scoring Methods
=
# Anomaly score
=
# Displacement score
=
# Density estimate
=
Feature Attribution
=
=
Neighborhood Search
=
=
Missing Value Imputation
=
= # Index to impute
=
Time Series Forecasting
=
# Feed observations one at a time
# Predict next 5 observations
=
# Returns a list of length 5 * input_dim
Serialization
# Save to string
=
# Save to file
# Load from string
=
# Load from file
=
You can also use pickle for Python serialization:
# Save
# Load
=
Example: Detecting Anomalies in a Data Stream
Rust
use Forest;
Python
=
# Warm up the forest with many normal data points
= * 0.01
=
= 0
# Online inference order: score first, then update.
=
=
# Lower threshold since we're detecting a very extreme anomaly
+= 1
License
Licensed under the Apache License 2.0.