use super::core_tree_structures::StreamingTreeModel;
use super::hoeffding_tree::{HoeffdingTree, HoeffdingTreeConfig};
use super::simd_operations as simd_tree;
use super::streaming_infrastructure::{ConceptDriftDetector, StreamingBuffer};
use crate::MaxFeatures;
use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::random::Random;
use sklears_core::error::{Result, SklearsError};
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug)]
pub struct OnlineGradientBoosting {
estimators: Vec<HoeffdingTree>,
learning_rate: f64,
tree_config: HoeffdingTreeConfig,
n_estimators: usize,
current_estimators: usize,
loss_function: OnlineLossFunction,
feature_importances: HashMap<usize, f64>,
}
#[derive(Debug, Clone, Copy)]
pub enum OnlineLossFunction {
SquaredLoss,
LogisticLoss,
ExponentialLoss,
}
#[derive(Debug, Clone)]
pub struct OnlineGradientBoostingConfig {
pub n_estimators: usize,
pub learning_rate: f64,
pub tree_config: HoeffdingTreeConfig,
pub loss_function: OnlineLossFunction,
pub min_samples_per_estimator: usize,
pub max_memory_usage: Option<usize>,
}
impl Default for OnlineGradientBoostingConfig {
fn default() -> Self {
Self {
n_estimators: 10,
learning_rate: 0.1,
tree_config: HoeffdingTreeConfig::default(),
loss_function: OnlineLossFunction::SquaredLoss,
min_samples_per_estimator: 100,
max_memory_usage: Some(100_000_000), }
}
}
impl OnlineGradientBoosting {
pub fn new(config: OnlineGradientBoostingConfig, _n_features: usize) -> Self {
Self {
estimators: Vec::with_capacity(config.n_estimators),
learning_rate: config.learning_rate,
tree_config: config.tree_config,
n_estimators: config.n_estimators,
current_estimators: 0,
loss_function: config.loss_function,
feature_importances: HashMap::new(),
}
}
pub fn update_single(&mut self, x: &[f64], y: f64) -> Result<()> {
let current_prediction = self.predict_single(x)?;
let gradient = self.compute_gradient(y, current_prediction);
for estimator in &mut self.estimators {
estimator.update(x, gradient, None)?;
}
if self.current_estimators < self.n_estimators {
let mut new_estimator = HoeffdingTree::new(self.tree_config.clone(), x.len());
new_estimator.update(x, gradient, None)?;
self.estimators.push(new_estimator);
self.current_estimators += 1;
}
Ok(())
}
pub fn compute_gradient(&self, y_true: f64, y_pred: f64) -> f64 {
match self.loss_function {
OnlineLossFunction::SquaredLoss => 2.0 * (y_pred - y_true),
OnlineLossFunction::LogisticLoss => {
let prob = 1.0 / (1.0 + (-y_pred).exp());
prob - y_true
}
OnlineLossFunction::ExponentialLoss => {
if y_true * y_pred < 0.0 {
y_true * (-y_true * y_pred).exp()
} else {
0.0
}
}
}
}
pub fn predict_single(&self, x: &[f64]) -> Result<f64> {
let mut prediction = 0.0;
for estimator in &self.estimators {
prediction += self.learning_rate * estimator.predict_single(x)?;
}
Ok(prediction)
}
pub fn get_feature_importances(&self) -> &HashMap<usize, f64> {
&self.feature_importances
}
pub fn get_ensemble_stats(&self) -> OnlineGradientBoostingStats {
let total_nodes: usize = self
.estimators
.iter()
.map(|est| est.get_stats().n_nodes)
.sum();
let total_samples: usize = self
.estimators
.iter()
.map(|est| est.get_stats().total_samples)
.sum();
let memory_usage: usize = self
.estimators
.iter()
.map(|est| est.get_stats().memory_usage)
.sum();
OnlineGradientBoostingStats {
n_estimators: self.current_estimators,
total_nodes,
total_samples,
memory_usage,
avg_tree_depth: if self.current_estimators > 0 {
self.estimators
.iter()
.map(|est| est.get_stats().max_depth)
.sum::<usize>() as f64
/ self.current_estimators as f64
} else {
0.0
},
}
}
}
#[derive(Debug, Clone)]
pub struct OnlineGradientBoostingStats {
pub n_estimators: usize,
pub total_nodes: usize,
pub total_samples: usize,
pub memory_usage: usize,
pub avg_tree_depth: f64,
}
impl StreamingTreeModel for OnlineGradientBoosting {
fn predict(&self, x: &Array2<f64>) -> Result<Array1<f64>> {
let mut predictions = Array1::zeros(x.nrows());
for (i, sample) in x.rows().into_iter().enumerate() {
let sample_vec: Vec<f64> = sample.to_vec();
predictions[i] = self.predict_single(&sample_vec)?;
}
Ok(predictions)
}
fn update(&mut self, x: &Array2<f64>, y: &Array1<f64>, _weights: &Array1<f64>) -> Result<()> {
for (i, sample) in x.rows().into_iter().enumerate() {
let sample_vec: Vec<f64> = sample.to_vec();
self.update_single(&sample_vec, y[i])?;
}
Ok(())
}
fn get_accuracy(&self, x: &Array2<f64>, y: &Array1<f64>) -> Result<f64> {
let predictions = self.predict(x)?;
match self.loss_function {
OnlineLossFunction::LogisticLoss => {
let correct = predictions
.iter()
.zip(y.iter())
.map(|(&pred, &actual)| {
let predicted_class = if pred > 0.0 { 1.0 } else { 0.0 };
if (predicted_class - actual).abs() < 1e-6 {
1.0
} else {
0.0
}
})
.sum::<f64>();
Ok(correct / predictions.len() as f64)
}
_ => {
let y_mean = y.mean().unwrap_or(0.0);
let ss_res = predictions
.iter()
.zip(y.iter())
.map(|(&pred, &actual)| (actual - pred).powi(2))
.sum::<f64>();
let ss_tot = y
.iter()
.map(|&actual| (actual - y_mean).powi(2))
.sum::<f64>();
if ss_tot == 0.0 {
Ok(1.0)
} else {
Ok((1.0 - ss_res / ss_tot).max(0.0))
}
}
}
}
fn rebuild(&mut self, x: &Array2<f64>, y: &Array1<f64>, weights: &Array1<f64>) -> Result<()> {
self.estimators.clear();
self.current_estimators = 0;
self.update(x, y, weights)
}
}
#[derive(Debug, Clone)]
pub struct IncrementalRandomForestConfig {
pub n_estimators: usize,
pub base_tree_config: HoeffdingTreeConfig,
pub max_features: MaxFeatures,
pub bootstrap: bool,
pub oob_score: bool,
pub random_state: Option<u64>,
pub window_size: usize,
pub drift_threshold: f64,
pub adaptive_ensemble_size: bool,
pub max_ensemble_size: Option<usize>,
pub min_tree_accuracy: f64,
}
impl Default for IncrementalRandomForestConfig {
fn default() -> Self {
Self {
n_estimators: 10,
base_tree_config: HoeffdingTreeConfig::default(),
max_features: MaxFeatures::Sqrt,
bootstrap: true,
oob_score: true,
random_state: None,
window_size: 1000,
drift_threshold: 0.05,
adaptive_ensemble_size: false,
max_ensemble_size: Some(100),
min_tree_accuracy: 0.5,
}
}
}
#[derive(Debug, Clone)]
pub struct RandomForestTreeStats {
pub tree_id: usize,
pub n_samples: usize,
pub accuracy: f64,
pub age: usize,
pub feature_importances: HashMap<usize, f64>,
pub oob_accuracy: Option<f64>,
pub bootstrap_indices: Vec<usize>,
}
impl RandomForestTreeStats {
pub fn new(tree_id: usize) -> Self {
Self {
tree_id,
n_samples: 0,
accuracy: 0.0,
age: 0,
feature_importances: HashMap::new(),
oob_accuracy: None,
bootstrap_indices: Vec::new(),
}
}
}
#[derive(Debug)]
pub struct IncrementalRandomForest {
trees: Vec<HoeffdingTree>,
tree_stats: Vec<RandomForestTreeStats>,
config: IncrementalRandomForestConfig,
feature_importances: HashMap<usize, f64>,
oob_buffer: StreamingBuffer,
drift_detector: ConceptDriftDetector,
rng: Random<scirs2_core::random::rngs::StdRng>,
n_features: Option<usize>,
sample_counter: usize,
}
impl IncrementalRandomForest {
pub fn new(config: IncrementalRandomForestConfig) -> Self {
let seed = config.random_state.unwrap_or_else(|| {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.subsec_nanos() as u64)
.unwrap_or(42)
});
let rng = Random::seed(seed);
let drift_detector = ConceptDriftDetector::new(config.window_size, config.drift_threshold);
let oob_buffer = StreamingBuffer::new(config.window_size);
Self {
trees: Vec::new(),
tree_stats: Vec::new(),
config,
feature_importances: HashMap::new(),
oob_buffer,
drift_detector,
rng,
n_features: None,
sample_counter: 0,
}
}
fn initialize_trees(&mut self, n_features: usize) -> Result<()> {
self.n_features = Some(n_features);
for i in 0..self.config.n_estimators {
let mut tree_config = self.config.base_tree_config.clone();
tree_config.confidence = self.rng.random_range(0.9..0.99);
tree_config.grace_period = self.rng.gen_range(150..250);
let tree = HoeffdingTree::new(tree_config, n_features);
let stats = RandomForestTreeStats::new(i);
self.trees.push(tree);
self.tree_stats.push(stats);
}
Ok(())
}
fn get_feature_subset(&mut self, n_features: usize) -> Vec<usize> {
let max_features_count = match self.config.max_features {
MaxFeatures::All => n_features,
MaxFeatures::Sqrt => (n_features as f64).sqrt().ceil() as usize,
MaxFeatures::Log2 => ((n_features as f64).log2().ceil() as usize).max(1),
MaxFeatures::Number(count) => count.min(n_features),
MaxFeatures::Fraction(frac) => ((n_features as f64 * frac).ceil() as usize).max(1),
};
let mut features: Vec<usize> = (0..n_features).collect();
self.rng.shuffle(&mut features);
features.truncate(max_features_count);
features.sort();
features
}
fn create_bootstrap_sample(&mut self, n_samples: usize) -> Vec<usize> {
if !self.config.bootstrap {
return (0..n_samples).collect();
}
let mut bootstrap_indices = Vec::with_capacity(n_samples);
for _ in 0..n_samples {
bootstrap_indices.push(self.rng.gen_range(0..n_samples));
}
bootstrap_indices
}
fn update_tree(
&mut self,
tree_idx: usize,
x: &Array2<f64>,
y: &Array1<f64>,
weights: &Array1<f64>,
bootstrap_indices: &[usize],
feature_subset: &[usize],
) -> Result<()> {
if tree_idx >= self.trees.len() {
return Err(SklearsError::InvalidInput(
"Tree index out of bounds".to_string(),
));
}
let n_samples = bootstrap_indices.len();
let n_features = feature_subset.len();
let mut x_sub = Array2::zeros((n_samples, n_features));
let mut y_sub = Array1::zeros(n_samples);
let mut w_sub = Array1::zeros(n_samples);
for (new_idx, &orig_idx) in bootstrap_indices.iter().enumerate() {
y_sub[new_idx] = y[orig_idx];
w_sub[new_idx] = weights[orig_idx];
for (new_feat_idx, &orig_feat_idx) in feature_subset.iter().enumerate() {
x_sub[[new_idx, new_feat_idx]] = x[[orig_idx, orig_feat_idx]];
}
}
for i in 0..n_samples {
let x_sample: Vec<f64> = x_sub.row(i).to_vec();
let y_sample = y_sub[i];
let class_label = if y_sample.fract() == 0.0 {
Some(y_sample as i32)
} else {
None
};
self.trees[tree_idx].update(&x_sample, y_sample, class_label)?;
}
self.tree_stats[tree_idx].n_samples += n_samples;
self.tree_stats[tree_idx].age += 1;
self.tree_stats[tree_idx].bootstrap_indices = bootstrap_indices.to_vec();
Ok(())
}
fn update_feature_importances(&mut self) {
self.feature_importances.clear();
for tree in &self.trees {
for (&feature_idx, &importance) in tree.get_feature_importances() {
*self.feature_importances.entry(feature_idx).or_insert(0.0) += importance;
}
}
let n_trees = self.trees.len() as f64;
for importance in self.feature_importances.values_mut() {
*importance /= n_trees;
}
}
fn prune_poor_trees(&mut self) -> Result<()> {
if !self.config.adaptive_ensemble_size {
return Ok(());
}
let mut trees_to_remove = Vec::new();
for (idx, stats) in self.tree_stats.iter().enumerate() {
if stats.accuracy < self.config.min_tree_accuracy && stats.age > 10 {
trees_to_remove.push(idx);
}
}
trees_to_remove.reverse();
for idx in trees_to_remove {
self.trees.remove(idx);
self.tree_stats.remove(idx);
}
Ok(())
}
fn add_new_trees(&mut self) -> Result<()> {
if !self.config.adaptive_ensemble_size {
return Ok(());
}
let current_size = self.trees.len();
let target_size = self.config.n_estimators;
if current_size < target_size {
let n_features = self.n_features.ok_or_else(|| {
SklearsError::InvalidInput("Features not initialized".to_string())
})?;
for i in current_size..target_size {
let mut tree_config = self.config.base_tree_config.clone();
tree_config.confidence = self.rng.random_range(0.9..0.99);
let tree = HoeffdingTree::new(tree_config, n_features);
let stats = RandomForestTreeStats::new(i);
self.trees.push(tree);
self.tree_stats.push(stats);
}
}
Ok(())
}
pub fn get_ensemble_size(&self) -> usize {
self.trees.len()
}
pub fn get_feature_importances(&self) -> &HashMap<usize, f64> {
&self.feature_importances
}
pub fn get_tree_stats(&self) -> &[RandomForestTreeStats] {
&self.tree_stats
}
}
impl StreamingTreeModel for IncrementalRandomForest {
fn predict(&self, x: &Array2<f64>) -> Result<Array1<f64>> {
if self.trees.is_empty() {
return Err(SklearsError::NotFitted {
operation: "predict".to_string(),
});
}
let n_samples = x.nrows();
let mut ensemble_predictions = Array1::zeros(n_samples);
for tree in &self.trees {
let tree_predictions = tree.predict(x)?;
ensemble_predictions += &tree_predictions;
}
ensemble_predictions /= self.trees.len() as f64;
Ok(ensemble_predictions)
}
fn update(&mut self, x: &Array2<f64>, y: &Array1<f64>, weights: &Array1<f64>) -> Result<()> {
let n_samples = x.nrows();
let n_features = x.ncols();
if self.trees.is_empty() {
self.initialize_trees(n_features)?;
}
for tree_idx in 0..self.trees.len() {
let bootstrap_indices = self.create_bootstrap_sample(n_samples);
let feature_subset = self.get_feature_subset(n_features);
self.update_tree(tree_idx, x, y, weights, &bootstrap_indices, &feature_subset)?;
}
if self.config.oob_score {
for i in 0..n_samples {
let x_sample: Vec<f64> = x.row(i).to_vec();
self.oob_buffer
.add_sample(x_sample, y[i], weights[i], self.sample_counter as u64);
self.sample_counter += 1;
}
}
self.update_feature_importances();
let current_accuracy = self.get_accuracy(x, y)?;
let drift_detected = self.drift_detector.update(current_accuracy);
if drift_detected {
let n_trees_to_refresh = (self.trees.len() / 4).max(1);
for _ in 0..n_trees_to_refresh {
let tree_idx = self.rng.gen_range(0..self.trees.len());
self.trees[tree_idx] = HoeffdingTree::new(
self.config.base_tree_config.clone(),
self.n_features.unwrap_or(1),
);
self.tree_stats[tree_idx] = RandomForestTreeStats::new(tree_idx);
}
}
self.prune_poor_trees()?;
self.add_new_trees()?;
Ok(())
}
fn get_accuracy(&self, x: &Array2<f64>, y: &Array1<f64>) -> Result<f64> {
let predictions = self.predict(x)?;
let mean_y = y.mean().unwrap_or(0.0);
let pred_slice: Vec<f64> = predictions.iter().cloned().collect();
let target_slice: Vec<f64> = y.iter().cloned().collect();
let ss_res =
simd_tree::simd_mse_evaluation(&pred_slice, &target_slice) * predictions.len() as f64;
let y_slice: Vec<f64> = y.iter().cloned().collect();
let mean_vec: Vec<f64> = vec![mean_y; y_slice.len()];
let ss_tot = simd_tree::simd_mse_evaluation(&y_slice, &mean_vec) * y_slice.len() as f64;
if ss_tot == 0.0 {
Ok(1.0)
} else {
Ok((1.0 - ss_res / ss_tot).max(0.0))
}
}
fn rebuild(&mut self, x: &Array2<f64>, y: &Array1<f64>, weights: &Array1<f64>) -> Result<()> {
self.trees.clear();
self.tree_stats.clear();
self.feature_importances.clear();
let n_features = x.ncols();
self.initialize_trees(n_features)?;
self.update(x, y, weights)
}
}