use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::random::{Random, rng};
use sklears_core::{
error::Result,
prelude::{Predict, SklearsError},
traits::{Fit, Trained, Untrained},
types::Float,
};
use smartcore::ensemble::random_forest_classifier::RandomForestClassifier as SmartCoreRandomForestClassifier;
use smartcore::ensemble::random_forest_regressor::RandomForestRegressor as SmartCoreRandomForestRegressor;
use smartcore::linalg::basic::matrix::DenseMatrix;
use std::marker::PhantomData;
#[derive(Debug, Clone, Copy)]
pub enum NoiseInjectionStrategy {
None,
Gaussian { std_dev: f64 },
Uniform { range: f64 },
TargetNoise { std_dev: f64 },
FeatureDropout { dropout_rate: f64 },
SampleDropout { dropout_rate: f64 },
}
#[derive(Debug, Clone)]
pub struct ExtraTreesConfig {
pub n_estimators: usize,
pub max_depth: Option<u16>,
pub min_samples_split: usize,
pub min_samples_leaf: usize,
pub random_state: Option<u64>,
pub bootstrap: bool,
pub max_features: Option<usize>,
pub n_random_thresholds: usize,
pub noise_injection: NoiseInjectionStrategy,
}
impl Default for ExtraTreesConfig {
fn default() -> Self {
Self {
n_estimators: 10,
max_depth: None,
min_samples_split: 2,
min_samples_leaf: 1,
random_state: None,
bootstrap: false, max_features: None, n_random_thresholds: 1, noise_injection: NoiseInjectionStrategy::None,
}
}
}
pub fn ndarray_to_dense_matrix(arr: &Array2<f64>) -> DenseMatrix<f64> {
let _rows = arr.nrows();
let _cols = arr.ncols();
let mut data = Vec::new();
for row in arr.outer_iter() {
data.push(row.to_vec());
}
DenseMatrix::from_2d_vec(&data)
}
pub fn apply_noise_injection<R: scirs2_core::random::Random + ?Sized>(
x: &Array2<f64>,
y: &Array1<f64>,
strategy: NoiseInjectionStrategy,
rng: &mut R,
) -> Result<(Array2<f64>, Array1<f64>)> {
match strategy {
NoiseInjectionStrategy::None => Ok((x.clone(), y.clone())),
NoiseInjectionStrategy::Gaussian { std_dev } => {
let mut noisy_x = x.clone();
add_gaussian_noise(&mut noisy_x, std_dev, rng);
Ok((noisy_x, y.clone()))
}
NoiseInjectionStrategy::Uniform { range } => {
let mut noisy_x = x.clone();
add_uniform_noise(&mut noisy_x, range, rng);
Ok((noisy_x, y.clone()))
}
NoiseInjectionStrategy::TargetNoise { std_dev } => {
let mut noisy_y = y.clone();
add_gaussian_noise_1d(&mut noisy_y, std_dev, rng);
Ok((x.clone(), noisy_y))
}
NoiseInjectionStrategy::FeatureDropout { dropout_rate } => {
let mut dropped_x = x.clone();
apply_feature_dropout(&mut dropped_x, dropout_rate, rng);
Ok((dropped_x, y.clone()))
}
NoiseInjectionStrategy::SampleDropout { dropout_rate } => {
apply_sample_dropout(x, y, dropout_rate, rng)
}
}
}
fn add_gaussian_noise<R: scirs2_core::random::Random + ?Sized>(arr: &mut Array2<f64>, std_dev: f64, rng: &mut R) {
use scirs2_core::random::{Random, rng};
if std_dev <= 0.0 {
return;
}
let normal = Normal::new(0.0, std_dev).expect("operation should succeed");
for element in arr.iter_mut() {
*element += normal.sample(rng);
}
}
fn add_uniform_noise<R: scirs2_core::random::Random + ?Sized>(arr: &mut Array2<f64>, range: f64, rng: &mut R) {
use scirs2_core::random::{Random, rng};
if range <= 0.0 {
return;
}
let uniform = Uniform::new(-range, range).expect("Failed to create uniform distribution");
for element in arr.iter_mut() {
*element += uniform.sample(rng);
}
}
fn add_gaussian_noise_1d<R: scirs2_core::random::Random + ?Sized>(arr: &mut Array1<f64>, std_dev: f64, rng: &mut R) {
use scirs2_core::random::{Random, rng};
if std_dev <= 0.0 {
return;
}
let normal = Normal::new(0.0, std_dev).expect("operation should succeed");
for element in arr.iter_mut() {
*element += normal.sample(rng);
}
}
fn apply_feature_dropout<R: scirs2_core::random::Random + ?Sized>(
arr: &mut Array2<f64>,
dropout_rate: f64,
rng: &mut R,
) {
if dropout_rate <= 0.0 || dropout_rate >= 1.0 {
return;
}
let (n_samples, n_features) = arr.dim();
for sample_idx in 0..n_samples {
for feature_idx in 0..n_features {
if rng.gen() < dropout_rate {
arr[[sample_idx, feature_idx]] = 0.0;
}
}
}
}
fn apply_sample_dropout<R: scirs2_core::random::Random + ?Sized>(
x: &Array2<f64>,
y: &Array1<f64>,
dropout_rate: f64,
rng: &mut R,
) -> Result<(Array2<f64>, Array1<f64>)> {
if dropout_rate <= 0.0 || dropout_rate >= 1.0 {
return Ok((x.clone(), y.clone()));
}
let n_samples = x.nrows();
let mut selected_indices = Vec::new();
for i in 0..n_samples {
if rng.gen() >= dropout_rate {
selected_indices.push(i);
}
}
if selected_indices.is_empty() && n_samples > 0 {
selected_indices.push(0);
}
if selected_indices.len() == n_samples {
return Ok((x.clone(), y.clone()));
}
let new_x = x.select(scirs2_core::ndarray::Axis(0), &selected_indices);
let new_y = y.select(scirs2_core::ndarray::Axis(0), &selected_indices);
Ok((new_x, new_y))
}
#[derive(Debug)]
pub struct ExtraTreesClassifier<State = Untrained> {
config: ExtraTreesConfig,
state: PhantomData<State>,
model_: Option<SmartCoreRandomForestClassifier<f64, i32, DenseMatrix<f64>, Vec<i32>>>,
classes_: Option<Vec<i32>>,
n_features_in_: Option<usize>,
n_classes_: Option<usize>,
}
impl ExtraTreesClassifier<Untrained> {
pub fn new() -> Self {
Self {
config: ExtraTreesConfig::default(),
state: PhantomData,
model_: None,
classes_: None,
n_features_in_: None,
n_classes_: None,
}
}
pub fn n_estimators(mut self, n_estimators: usize) -> Self {
self.config.n_estimators = n_estimators;
self
}
pub fn max_depth(mut self, max_depth: Option<u16>) -> Self {
self.config.max_depth = max_depth;
self
}
pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
self.config.min_samples_split = min_samples_split;
self
}
pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
self.config.min_samples_leaf = min_samples_leaf;
self
}
pub fn random_state(mut self, random_state: Option<u64>) -> Self {
self.config.random_state = random_state;
self
}
pub fn bootstrap(mut self, bootstrap: bool) -> Self {
self.config.bootstrap = bootstrap;
self
}
pub fn max_features(mut self, max_features: Option<usize>) -> Self {
self.config.max_features = max_features;
self
}
pub fn n_random_thresholds(mut self, n_random_thresholds: usize) -> Self {
self.config.n_random_thresholds = n_random_thresholds;
self
}
}
impl ExtraTreesClassifier<Trained> {
pub fn classes(&self) -> &Vec<i32> {
self.classes_.as_ref().expect("Classifier should be fitted")
}
pub fn n_classes(&self) -> usize {
self.n_classes_.expect("Classifier should be fitted")
}
pub fn n_features_in(&self) -> usize {
self.n_features_in_.expect("Classifier should be fitted")
}
}
impl Default for ExtraTreesClassifier<Untrained> {
fn default() -> Self {
Self::new()
}
}
impl Fit<Array2<Float>, Array1<i32>> for ExtraTreesClassifier<Untrained> {
type Fitted = ExtraTreesClassifier<Trained>;
fn fit(self, x: &Array2<Float>, y: &Array1<i32>) -> Result<Self::Fitted> {
let (n_samples, n_features) = x.dim();
if n_samples == 0 {
return Err(SklearsError::InvalidInput(
"Cannot fit classifier on empty dataset".to_string(),
));
}
let y_len = y.len();
if n_samples != y_len {
return Err(SklearsError::ShapeMismatch {
expected: format!("X.shape[0] = {n_samples}"),
actual: format!("y.shape[0] = {y_len}"),
});
}
let x_matrix = ndarray_to_dense_matrix(x);
let y_vec = y.to_vec();
let mut classes: Vec<i32> = y_vec.to_vec();
classes.sort_unstable();
classes.dedup();
let n_classes = classes.len();
let params = {
let mut p = smartcore::ensemble::random_forest_classifier::RandomForestClassifierParameters::default()
.with_n_trees(self.config.n_estimators as u16)
.with_min_samples_split(self.config.min_samples_split)
.with_min_samples_leaf(self.config.min_samples_leaf);
if let Some(max_depth) = self.config.max_depth {
p = p.with_max_depth(max_depth);
}
p
};
let model = if self.config.bootstrap {
SmartCoreRandomForestClassifier::fit(&x_matrix, &y_vec, params)
.map_err(|e| SklearsError::FitError(format!("SmartCore fit error: {e}")))?
} else {
log::warn!("SmartCore always uses bootstrap for Random Forest. Extra Trees behavior approximated.");
SmartCoreRandomForestClassifier::fit(&x_matrix, &y_vec, params)
.map_err(|e| SklearsError::FitError(format!("SmartCore fit error: {e}")))?
};
Ok(ExtraTreesClassifier {
config: self.config,
state: PhantomData,
model_: Some(model),
classes_: Some(classes),
n_features_in_: Some(n_features),
n_classes_: Some(n_classes),
})
}
}
impl Predict<Array2<Float>, Array1<i32>> for ExtraTreesClassifier<Trained> {
fn predict(&self, x: &Array2<Float>) -> Result<Array1<i32>> {
let (_n_samples, n_features) = x.dim();
if n_features != self.n_features_in() {
return Err(SklearsError::FeatureMismatch {
expected: self.n_features_in(),
actual: n_features,
});
}
let x_matrix = ndarray_to_dense_matrix(x);
let model = self.model_.as_ref().expect("Classifier should be fitted");
let predictions = model
.predict(&x_matrix)
.map_err(|e| SklearsError::PredictError(format!("SmartCore predict error: {e}")))?;
Ok(Array1::from_vec(predictions))
}
}
#[derive(Debug)]
pub struct ExtraTreesRegressor<State = Untrained> {
config: ExtraTreesConfig,
state: PhantomData<State>,
model_: Option<SmartCoreRandomForestRegressor<f64, f64, DenseMatrix<f64>, Vec<f64>>>,
n_features_in_: Option<usize>,
}
impl ExtraTreesRegressor<Untrained> {
pub fn new() -> Self {
Self {
config: ExtraTreesConfig::default(),
state: PhantomData,
model_: None,
n_features_in_: None,
}
}
pub fn n_estimators(mut self, n_estimators: usize) -> Self {
self.config.n_estimators = n_estimators;
self
}
pub fn max_depth(mut self, max_depth: Option<u16>) -> Self {
self.config.max_depth = max_depth;
self
}
pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
self.config.min_samples_split = min_samples_split;
self
}
pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
self.config.min_samples_leaf = min_samples_leaf;
self
}
pub fn random_state(mut self, random_state: Option<u64>) -> Self {
self.config.random_state = random_state;
self
}
pub fn bootstrap(mut self, bootstrap: bool) -> Self {
self.config.bootstrap = bootstrap;
self
}
pub fn max_features(mut self, max_features: Option<usize>) -> Self {
self.config.max_features = max_features;
self
}
pub fn n_random_thresholds(mut self, n_random_thresholds: usize) -> Self {
self.config.n_random_thresholds = n_random_thresholds;
self
}
}
impl ExtraTreesRegressor<Trained> {
pub fn n_features_in(&self) -> usize {
self.n_features_in_.expect("Regressor should be fitted")
}
}
impl Default for ExtraTreesRegressor<Untrained> {
fn default() -> Self {
Self::new()
}
}
impl Fit<Array2<Float>, Array1<Float>> for ExtraTreesRegressor<Untrained> {
type Fitted = ExtraTreesRegressor<Trained>;
fn fit(self, x: &Array2<Float>, y: &Array1<Float>) -> Result<Self::Fitted> {
let (n_samples, n_features) = x.dim();
if n_samples == 0 {
return Err(SklearsError::InvalidInput(
"Cannot fit regressor on empty dataset".to_string(),
));
}
let y_len = y.len();
if n_samples != y_len {
return Err(SklearsError::ShapeMismatch {
expected: format!("X.shape[0] = {n_samples}"),
actual: format!("y.shape[0] = {y_len}"),
});
}
let x_matrix = ndarray_to_dense_matrix(x);
let y_vec = y.to_vec();
let params = {
let mut p = smartcore::ensemble::random_forest_regressor::RandomForestRegressorParameters::default()
.with_n_trees(self.config.n_estimators)
.with_min_samples_split(self.config.min_samples_split)
.with_min_samples_leaf(self.config.min_samples_leaf);
if let Some(max_depth) = self.config.max_depth {
p = p.with_max_depth(max_depth);
}
p
};
let model = if self.config.bootstrap {
SmartCoreRandomForestRegressor::fit(&x_matrix, &y_vec, params)
.map_err(|e| SklearsError::FitError(format!("SmartCore fit error: {e}")))?
} else {
log::warn!("SmartCore always uses bootstrap for Random Forest. Extra Trees behavior approximated.");
SmartCoreRandomForestRegressor::fit(&x_matrix, &y_vec, params)
.map_err(|e| SklearsError::FitError(format!("SmartCore fit error: {e}")))?
};
Ok(ExtraTreesRegressor {
config: self.config,
state: PhantomData,
model_: Some(model),
n_features_in_: Some(n_features),
})
}
}
impl Predict<Array2<Float>, Array1<Float>> for ExtraTreesRegressor<Trained> {
fn predict(&self, x: &Array2<Float>) -> Result<Array1<Float>> {
let (_n_samples, n_features) = x.dim();
if n_features != self.n_features_in() {
return Err(SklearsError::FeatureMismatch {
expected: self.n_features_in(),
actual: n_features,
});
}
let x_matrix = ndarray_to_dense_matrix(x);
let model = self.model_.as_ref().expect("Regressor should be fitted");
let predictions = model
.predict(&x_matrix)
.map_err(|e| SklearsError::PredictError(format!("SmartCore predict error: {e}")))?;
Ok(Array1::from_vec(predictions))
}
}
#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
use super::*;
use scirs2_core::ndarray::array;
#[test]
fn test_extra_trees_classifier() {
let x = array![
[0.0, 0.0],
[1.0, 1.0],
[0.0, 1.0],
[1.0, 0.0],
[0.0, 0.0],
[1.0, 1.0],
];
let y = array![0, 1, 0, 1, 0, 1];
let classifier = ExtraTreesClassifier::new()
.n_estimators(5)
.random_state(Some(42))
.fit(&x, &y)
.expect("operation should succeed");
assert_eq!(classifier.n_features_in(), 2);
assert_eq!(classifier.n_classes(), 2);
assert_eq!(classifier.classes(), &vec![0, 1]);
let predictions = classifier.predict(&x).expect("prediction should succeed");
assert_eq!(predictions.len(), x.nrows());
for &pred in predictions.iter() {
assert!(pred == 0 || pred == 1);
}
}
#[test]
fn test_extra_trees_regressor() {
let x = array![[0.0], [1.0], [2.0], [3.0], [4.0],];
let y = array![0.0, 1.0, 4.0, 9.0, 16.0];
let regressor = ExtraTreesRegressor::new()
.n_estimators(10)
.random_state(Some(42))
.fit(&x, &y)
.expect("operation should succeed");
assert_eq!(regressor.n_features_in(), 1);
let predictions = regressor.predict(&x).expect("prediction should succeed");
assert_eq!(predictions.len(), x.nrows());
for (i, &pred) in predictions.iter().enumerate() {
assert!(pred >= 0.0); assert!(pred <= 20.0); }
}
#[test]
fn test_extra_trees_classifier_empty_data() {
let x = Array2::<f64>::zeros((0, 2));
let y = Array1::<i32>::zeros(0);
let result = ExtraTreesClassifier::new().fit(&x, &y);
assert!(result.is_err());
}
#[test]
fn test_extra_trees_dimension_mismatch() {
let x = array![[1.0, 2.0], [3.0, 4.0]];
let y = array![1];
let result = ExtraTreesClassifier::new().fit(&x, &y);
assert!(result.is_err());
}
}