1use scirs2_core::ndarray::{Array1, Array2, ArrayBase, Axis, Dim, OwnedRepr};
6use scirs2_core::random::prelude::*;
7use sklears_core::{
8 error::{Result, SklearsError},
9 traits::{Fit, Predict, Untrained},
10 types::Float,
11};
12use std::collections::HashMap;
13
14type Mat2f = ArrayBase<OwnedRepr<f64>, Dim<[usize; 2]>, f64>;
16type Vec1f = ArrayBase<OwnedRepr<f64>, Dim<[usize; 1]>, f64>;
18
19#[derive(Debug, Clone)]
21pub struct BiasVarianceDecomposition {
22 pub bias_squared: Float,
24 pub variance: Float,
26 pub noise: Float,
28 pub total_loss: Float,
30 pub n_bootstrap_samples: usize,
32 pub sample_decompositions: Option<Vec<SampleBiasVariance>>,
34}
35pub struct EnsembleCrossValidator {
37 config: EnsembleConstructionConfig,
38}
39impl EnsembleCrossValidator {
40 pub fn new(config: EnsembleConstructionConfig) -> Self {
42 Self { config }
43 }
44 pub fn validate_ensemble<E>(
46 &self,
47 base_estimator: E,
48 x: &Array2<Float>,
49 y: &Array1<Float>,
50 param_grid: &HashMap<String, Vec<Float>>,
51 ) -> Result<EnsembleCVResults>
52 where
53 E: Clone + Fit<Mat2f, Vec1f, Untrained> + 'static,
54 <E as Fit<Mat2f, Vec1f, Untrained>>::Fitted: Predict<Mat2f, Vec1f>,
55 {
56 let start_time = std::time::Instant::now();
57 let folds = self.create_folds(x, y)?;
58 let mut fold_scores = Vec::new();
59 let mut best_score = Float::NEG_INFINITY;
60 let mut best_config = HashMap::new();
61 for config in self.generate_parameter_combinations(param_grid) {
62 let mut config_scores = Vec::new();
63 for (train_indices, val_indices) in &folds {
64 let (x_train, y_train) = self.subset_data(x, y, train_indices);
65 let (x_val, y_val) = self.subset_data(x, y, val_indices);
66 let estimator = base_estimator.clone();
67 let trained_ensemble = self.build_ensemble_fold(estimator, &x_train, &y_train)?;
68 let predictions = trained_ensemble.predict(&x_val)?;
69 let score = self.compute_score(&predictions, &y_val);
70 config_scores.push(score);
71 }
72 let mean_score = config_scores.iter().sum::<Float>() / config_scores.len() as Float;
73 if mean_score > best_score {
74 best_score = mean_score;
75 best_config = config.clone();
76 fold_scores = config_scores;
77 }
78 }
79 let std_score = self.compute_std(&fold_scores, best_score);
80 let diversity_metrics = self.compute_diversity_metrics(x, y)?;
81 let training_time = start_time.elapsed().as_secs_f64() as Float;
82 Ok(EnsembleCVResults {
83 mean_score: best_score,
84 std_score,
85 fold_scores,
86 best_config,
87 diversity_metrics,
88 training_time,
89 })
90 }
91 pub(crate) fn create_folds(
93 &self,
94 x: &Array2<Float>,
95 y: &Array1<Float>,
96 ) -> Result<Vec<(Vec<usize>, Vec<usize>)>> {
97 let n_samples = x.nrows();
98 let mut indices: Vec<usize> = (0..n_samples).collect();
99 match &self.config.cv_strategy {
100 EnsembleCVStrategy::KFold { n_splits, shuffle } => {
101 if *shuffle {
102 if let Some(_seed) = self.config.random_state {
103 let mut rng = thread_rng();
104 for i in (1..indices.len()).rev() {
105 let j = rng.gen_range(0..i + 1);
106 indices.swap(i, j);
107 }
108 }
109 }
110 let fold_size = n_samples / n_splits;
111 let mut folds = Vec::new();
112 for i in 0..*n_splits {
113 let start = i * fold_size;
114 let end = if i == n_splits - 1 {
115 n_samples
116 } else {
117 (i + 1) * fold_size
118 };
119 let val_indices: Vec<usize> = indices[start..end].to_vec();
120 let train_indices: Vec<usize> = indices[..start]
121 .iter()
122 .chain(indices[end..].iter())
123 .copied()
124 .collect();
125 folds.push((train_indices, val_indices));
126 }
127 Ok(folds)
128 }
129 EnsembleCVStrategy::StratifiedKFold {
130 n_splits,
131 shuffle: _,
132 } => {
133 let mut class_indices: HashMap<i32, Vec<usize>> = HashMap::new();
134 for (idx, &label) in y.iter().enumerate() {
135 let class = label as i32;
136 class_indices.entry(class).or_default().push(idx);
137 }
138 let mut folds = vec![Vec::new(); *n_splits];
139 for class_idx_vec in class_indices.values() {
140 let class_fold_size = class_idx_vec.len() / n_splits;
141 for (i, &idx) in class_idx_vec.iter().enumerate() {
142 let fold_idx = i.checked_div(class_fold_size).unwrap_or(i % n_splits);
143 let fold_idx = fold_idx.min(n_splits - 1);
144 folds[fold_idx].push(idx);
145 }
146 }
147 let mut cv_folds = Vec::new();
148 for i in 0..*n_splits {
149 let val_indices = folds[i].clone();
150 let train_indices: Vec<usize> = folds
151 .iter()
152 .enumerate()
153 .filter(|(j, _)| *j != i)
154 .flat_map(|(_, fold)| fold.iter())
155 .copied()
156 .collect();
157 cv_folds.push((train_indices, val_indices));
158 }
159 Ok(cv_folds)
160 }
161 EnsembleCVStrategy::LeaveOneOut => {
162 let mut folds = Vec::new();
163 for i in 0..n_samples {
164 let val_indices = vec![i];
165 let train_indices: Vec<usize> = (0..n_samples).filter(|&j| j != i).collect();
166 folds.push((train_indices, val_indices));
167 }
168 Ok(folds)
169 }
170 EnsembleCVStrategy::TimeSeriesSplit {
171 n_splits,
172 max_train_size,
173 } => {
174 let mut folds = Vec::new();
175 let min_train_size = n_samples / (n_splits + 1);
176 for i in 1..=*n_splits {
177 let train_end = min_train_size * i;
178 let val_start = train_end;
179 let val_end = if i == *n_splits {
180 n_samples
181 } else {
182 min_train_size * (i + 1)
183 };
184 let mut train_start = 0;
185 if let Some(max_size) = max_train_size {
186 train_start = train_end.saturating_sub(*max_size);
187 }
188 let train_indices: Vec<usize> = (train_start..train_end).collect();
189 let val_indices: Vec<usize> = (val_start..val_end).collect();
190 if !train_indices.is_empty() && !val_indices.is_empty() {
191 folds.push((train_indices, val_indices));
192 }
193 }
194 Ok(folds)
195 }
196 EnsembleCVStrategy::GroupKFold {
197 n_splits: _,
198 groups: _,
199 } => self.create_kfold_simple(n_samples, 5),
200 EnsembleCVStrategy::NestedCV {
201 outer_splits,
202 inner_splits: _,
203 } => self.create_kfold_simple(n_samples, *outer_splits),
204 }
205 }
206 fn create_kfold_simple(
207 &self,
208 n_samples: usize,
209 n_splits: usize,
210 ) -> Result<Vec<(Vec<usize>, Vec<usize>)>> {
211 let fold_size = n_samples / n_splits;
212 let mut folds = Vec::new();
213 for i in 0..n_splits {
214 let start = i * fold_size;
215 let end = if i == n_splits - 1 {
216 n_samples
217 } else {
218 (i + 1) * fold_size
219 };
220 let val_indices: Vec<usize> = (start..end).collect();
221 let train_indices: Vec<usize> = (0..start).chain(end..n_samples).collect();
222 folds.push((train_indices, val_indices));
223 }
224 Ok(folds)
225 }
226 pub(crate) fn generate_parameter_combinations(
228 &self,
229 param_grid: &HashMap<String, Vec<Float>>,
230 ) -> Vec<HashMap<String, Float>> {
231 if param_grid.is_empty() {
232 return vec![HashMap::new()];
233 }
234 let mut combinations = vec![HashMap::new()];
235 for (param_name, param_values) in param_grid {
236 let mut new_combinations = Vec::new();
237 for combination in &combinations {
238 for &value in param_values {
239 let mut new_combination = combination.clone();
240 new_combination.insert(param_name.clone(), value);
241 new_combinations.push(new_combination);
242 }
243 }
244 combinations = new_combinations;
245 }
246 combinations
247 }
248 fn subset_data(
250 &self,
251 x: &Array2<Float>,
252 y: &Array1<Float>,
253 indices: &[usize],
254 ) -> (Array2<Float>, Array1<Float>) {
255 let x_subset = x.select(Axis(0), indices);
256 let y_subset = y.select(Axis(0), indices);
257 (x_subset, y_subset)
258 }
259 fn build_ensemble_fold<E>(
261 &self,
262 _estimator: E,
263 _x_train: &Array2<Float>,
264 _y_train: &Array1<Float>,
265 ) -> Result<MockEnsemble>
266 where
267 E: Fit<Mat2f, Vec1f, Untrained>,
268 {
269 Ok(MockEnsemble {
270 mean_prediction: 0.5,
271 })
272 }
273 pub(crate) fn compute_score(
275 &self,
276 predictions: &Array1<Float>,
277 y_true: &Array1<Float>,
278 ) -> Float {
279 match &self.config.scoring {
280 ScoringMetric::Accuracy => {
281 let correct = predictions
282 .iter()
283 .zip(y_true.iter())
284 .map(|(&pred, &true_val)| {
285 if (pred - true_val).abs() < 0.5 {
286 1.0
287 } else {
288 0.0
289 }
290 })
291 .sum::<Float>();
292 correct / predictions.len() as Float
293 }
294 ScoringMetric::MeanSquaredError => {
295 let mse = predictions
296 .iter()
297 .zip(y_true.iter())
298 .map(|(&pred, &true_val)| (pred - true_val).powi(2))
299 .sum::<Float>()
300 / predictions.len() as Float;
301 -mse
302 }
303 ScoringMetric::MeanAbsoluteError => {
304 let mae = predictions
305 .iter()
306 .zip(y_true.iter())
307 .map(|(&pred, &true_val)| (pred - true_val).abs())
308 .sum::<Float>()
309 / predictions.len() as Float;
310 -mae
311 }
312 ScoringMetric::R2Score => {
313 let y_mean = y_true.sum() / y_true.len() as Float;
314 let ss_tot = y_true.iter().map(|&y| (y - y_mean).powi(2)).sum::<Float>();
315 let ss_res = predictions
316 .iter()
317 .zip(y_true.iter())
318 .map(|(&pred, &true_val)| (true_val - pred).powi(2))
319 .sum::<Float>();
320 if ss_tot == 0.0 {
321 1.0
322 } else {
323 1.0 - (ss_res / ss_tot)
324 }
325 }
326 ScoringMetric::F1Score => {
327 let mut tp = 0.0;
328 let mut fp = 0.0;
329 let mut fn_count = 0.0;
330 for (&pred, &true_val) in predictions.iter().zip(y_true.iter()) {
331 let pred_class = if pred > 0.5 { 1.0 } else { 0.0 };
332 let true_class = if true_val > 0.5 { 1.0 } else { 0.0 };
333 if pred_class == 1.0 && true_class == 1.0 {
334 tp += 1.0;
335 } else if pred_class == 1.0 && true_class == 0.0 {
336 fp += 1.0;
337 } else if pred_class == 0.0 && true_class == 1.0 {
338 fn_count += 1.0;
339 }
340 }
341 let precision = if tp + fp > 0.0 { tp / (tp + fp) } else { 0.0 };
342 let recall = if tp + fn_count > 0.0 {
343 tp / (tp + fn_count)
344 } else {
345 0.0
346 };
347 if precision + recall > 0.0 {
348 2.0 * precision * recall / (precision + recall)
349 } else {
350 0.0
351 }
352 }
353 ScoringMetric::AUC => {
354 let mut pairs: Vec<(Float, Float)> = predictions
355 .iter()
356 .zip(y_true.iter())
357 .map(|(&pred, &true_val)| (pred, true_val))
358 .collect();
359 pairs.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("operation should succeed"));
360 let mut auc = 0.0;
361 let mut tp = 0.0;
362 let total_pos = y_true.iter().filter(|&&y| y > 0.5).count() as Float;
363 let total_neg = y_true.len() as Float - total_pos;
364 if total_pos == 0.0 || total_neg == 0.0 {
365 return 0.5;
366 }
367 for (_, true_val) in pairs {
368 if true_val > 0.5 {
369 tp += 1.0;
370 } else {
371 auc += tp / total_pos;
372 }
373 }
374 auc / total_neg
375 }
376 ScoringMetric::Custom(scorer) => scorer(predictions, y_true),
377 ScoringMetric::MultiObjective {
378 accuracy_weight,
379 diversity_weight,
380 } => {
381 let accuracy =
382 self.compute_score_with_metric(predictions, y_true, &ScoringMetric::Accuracy);
383 let diversity = 0.5;
384 accuracy_weight * accuracy + diversity_weight * diversity
385 }
386 }
387 }
388 fn compute_score_with_metric(
389 &self,
390 predictions: &Array1<Float>,
391 y_true: &Array1<Float>,
392 metric: &ScoringMetric,
393 ) -> Float {
394 let temp_config = EnsembleConstructionConfig {
395 cv_strategy: self.config.cv_strategy.clone(),
396 scoring: metric.clone(),
397 random_state: self.config.random_state,
398 early_stopping: self.config.early_stopping,
399 patience: self.config.patience,
400 min_improvement: self.config.min_improvement,
401 max_ensemble_size: self.config.max_ensemble_size,
402 diversity_weight: self.config.diversity_weight,
403 };
404 let temp_validator = EnsembleCrossValidator::new(temp_config);
405 temp_validator.compute_score(predictions, y_true)
406 }
407 fn compute_std(&self, scores: &[Float], mean: Float) -> Float {
409 if scores.len() <= 1 {
410 return 0.0;
411 }
412 let variance = scores
413 .iter()
414 .map(|&score| (score - mean).powi(2))
415 .sum::<Float>()
416 / (scores.len() - 1) as Float;
417 variance.sqrt()
418 }
419 fn compute_diversity_metrics(
421 &self,
422 _x: &Array2<Float>,
423 _y: &Array1<Float>,
424 ) -> Result<DiversityMetrics> {
425 Ok(DiversityMetrics {
426 disagreement: 0.3,
427 double_fault: 0.1,
428 q_statistic: 0.2,
429 entropy_diversity: 0.4,
430 kw_variance: 0.25,
431 kappa: 0.6,
432 fleiss_kappa: 0.65,
433 interrater_reliability: InterraterReliability {
434 overall_agreement: 0.7,
435 chance_agreement: 0.4,
436 krippendorff_alpha: 0.55,
437 pearson_correlation: 0.8,
438 weighted_kappa: 0.6,
439 kappa_std_error: 0.05,
440 },
441 })
442 }
443}
444impl EnsembleCrossValidator {
446 pub fn for_classification(n_splits: usize) -> Self {
448 let config = EnsembleConstructionConfig {
449 cv_strategy: EnsembleCVStrategy::StratifiedKFold {
450 n_splits,
451 shuffle: true,
452 },
453 scoring: ScoringMetric::Accuracy,
454 ..Default::default()
455 };
456 Self::new(config)
457 }
458 pub fn for_regression(n_splits: usize) -> Self {
460 let config = EnsembleConstructionConfig {
461 cv_strategy: EnsembleCVStrategy::KFold {
462 n_splits,
463 shuffle: true,
464 },
465 scoring: ScoringMetric::R2Score,
466 ..Default::default()
467 };
468 Self::new(config)
469 }
470 pub fn for_time_series(n_splits: usize, max_train_size: Option<usize>) -> Self {
472 let config = EnsembleConstructionConfig {
473 cv_strategy: EnsembleCVStrategy::TimeSeriesSplit {
474 n_splits,
475 max_train_size,
476 },
477 scoring: ScoringMetric::MeanSquaredError,
478 ..Default::default()
479 };
480 Self::new(config)
481 }
482 pub fn multi_objective(
484 n_splits: usize,
485 accuracy_weight: Float,
486 diversity_weight: Float,
487 ) -> Self {
488 let config = EnsembleConstructionConfig {
489 cv_strategy: EnsembleCVStrategy::StratifiedKFold {
490 n_splits,
491 shuffle: true,
492 },
493 scoring: ScoringMetric::MultiObjective {
494 accuracy_weight,
495 diversity_weight,
496 },
497 diversity_weight,
498 ..Default::default()
499 };
500 Self::new(config)
501 }
502}
503#[derive(Debug, Clone)]
505pub struct DiversityMetrics {
506 pub disagreement: Float,
508 pub double_fault: Float,
510 pub q_statistic: Float,
512 pub entropy_diversity: Float,
514 pub kw_variance: Float,
516 pub kappa: Float,
518 pub fleiss_kappa: Float,
520 pub interrater_reliability: InterraterReliability,
522}
523pub(super) struct MockEnsemble {
525 pub(super) mean_prediction: Float,
526}
527#[derive(Debug)]
529pub struct BiasVarianceEnsembleSizeAnalysis {
530 pub ensemble_sizes: Vec<usize>,
532 pub bias_curve: Vec<Float>,
534 pub variance_curve: Vec<Float>,
536 pub total_error_curve: Vec<Float>,
538 pub optimal_ensemble_size: usize,
540 pub bias_reduction: Float,
542 pub variance_reduction: Float,
544}
545#[derive(Debug, Clone)]
547pub enum ModelSelectionLossFunction {
548 SquaredLoss,
550 ZeroOneLoss,
552 Custom(fn(Float, Float) -> Float),
554}
555#[derive(Debug, Clone)]
557pub struct BiasVarianceConfig {
558 pub n_bootstrap_samples: usize,
560 pub random_state: Option<u64>,
562 pub bootstrap_size: Float,
564 pub compute_sample_level: bool,
566 pub loss_function: ModelSelectionLossFunction,
568}
569#[derive(Debug, Clone)]
571pub enum EnsembleCVStrategy {
572 KFold { n_splits: usize, shuffle: bool },
574 StratifiedKFold { n_splits: usize, shuffle: bool },
576 LeaveOneOut,
578 TimeSeriesSplit {
580 n_splits: usize,
581 max_train_size: Option<usize>,
582 },
583 GroupKFold { n_splits: usize, groups: Vec<usize> },
585 NestedCV {
587 outer_splits: usize,
588 inner_splits: usize,
589 },
590}
591#[derive(Debug, Clone)]
593pub enum ScoringMetric {
594 Accuracy,
595 F1Score,
596 AUC,
597 MeanSquaredError,
598 MeanAbsoluteError,
599 R2Score,
600 Custom(fn(&Array1<Float>, &Array1<Float>) -> Float),
601 MultiObjective {
602 accuracy_weight: Float,
603 diversity_weight: Float,
604 },
605}
606#[derive(Debug, Clone)]
608pub struct InterraterReliability {
609 pub overall_agreement: Float,
611 pub chance_agreement: Float,
613 pub krippendorff_alpha: Float,
615 pub pearson_correlation: Float,
617 pub weighted_kappa: Float,
619 pub kappa_std_error: Float,
621}
622pub struct BiasVarianceAnalyzer {
624 config: BiasVarianceConfig,
625}
626impl BiasVarianceAnalyzer {
627 pub fn new(config: BiasVarianceConfig) -> Self {
629 Self { config }
630 }
631 pub fn decompose<E>(
633 &self,
634 estimator: E,
635 x: &Array2<Float>,
636 y: &Array1<Float>,
637 ) -> Result<BiasVarianceDecomposition>
638 where
639 E: Clone + Fit<Mat2f, Vec1f, Untrained>,
640 <E as Fit<Mat2f, Vec1f, Untrained>>::Fitted: Predict<Mat2f, Vec1f>,
641 {
642 let _n_samples = x.nrows();
643 let n_bootstrap = self.config.n_bootstrap_samples;
644 let mut all_predictions = Vec::with_capacity(n_bootstrap);
645 for bootstrap_idx in 0..n_bootstrap {
646 let (x_bootstrap, y_bootstrap) = self.generate_bootstrap_sample(x, y, bootstrap_idx)?;
647 let trained_estimator = estimator.clone().fit(&x_bootstrap, &y_bootstrap)?;
648 let predictions = trained_estimator.predict(x)?;
649 all_predictions.push(predictions);
650 }
651 let decomposition = self.compute_decomposition(&all_predictions, y)?;
652 Ok(decomposition)
653 }
654 pub fn decompose_ensemble<E>(
656 &self,
657 base_estimator: E,
658 ensemble_sizes: &[usize],
659 x: &Array2<Float>,
660 y: &Array1<Float>,
661 ) -> Result<Vec<(usize, BiasVarianceDecomposition)>>
662 where
663 E: Clone + Fit<Mat2f, Vec1f, Untrained>,
664 <E as Fit<Mat2f, Vec1f, Untrained>>::Fitted: Predict<Mat2f, Vec1f>,
665 {
666 let mut results = Vec::new();
667 for &ensemble_size in ensemble_sizes {
668 let ensemble_config = BiasVarianceConfig {
669 n_bootstrap_samples: self.config.n_bootstrap_samples,
670 random_state: self.config.random_state,
671 bootstrap_size: self.config.bootstrap_size,
672 compute_sample_level: self.config.compute_sample_level,
673 loss_function: self.config.loss_function.clone(),
674 };
675 let ensemble_analyzer = BiasVarianceAnalyzer::new(ensemble_config);
676 let ensemble_decomposition = ensemble_analyzer.decompose_bagged_ensemble(
677 base_estimator.clone(),
678 ensemble_size,
679 x,
680 y,
681 )?;
682 results.push((ensemble_size, ensemble_decomposition));
683 }
684 Ok(results)
685 }
686 fn decompose_bagged_ensemble<E>(
688 &self,
689 base_estimator: E,
690 ensemble_size: usize,
691 x: &Array2<Float>,
692 y: &Array1<Float>,
693 ) -> Result<BiasVarianceDecomposition>
694 where
695 E: Clone + Fit<Mat2f, Vec1f, Untrained>,
696 <E as Fit<Mat2f, Vec1f, Untrained>>::Fitted: Predict<Mat2f, Vec1f>,
697 {
698 let n_samples = x.nrows();
699 let n_bootstrap = self.config.n_bootstrap_samples;
700 let mut ensemble_predictions = Vec::with_capacity(n_bootstrap);
701 for bootstrap_idx in 0..n_bootstrap {
702 let (_x_bootstrap, _y_bootstrap) =
703 self.generate_bootstrap_sample(x, y, bootstrap_idx)?;
704 let mut member_predictions = Vec::with_capacity(ensemble_size);
705 for member_idx in 0..ensemble_size {
706 let seed_offset = bootstrap_idx * ensemble_size + member_idx;
707 let (x_member, y_member) =
708 self.generate_bootstrap_sample_with_offset(x, y, seed_offset)?;
709 let trained_member = base_estimator.clone().fit(&x_member, &y_member)?;
710 let member_pred = trained_member.predict(x)?;
711 member_predictions.push(member_pred);
712 }
713 let mut ensemble_pred = Array1::zeros(n_samples);
714 for pred in &member_predictions {
715 ensemble_pred += pred;
716 }
717 ensemble_pred /= ensemble_size as Float;
718 ensemble_predictions.push(ensemble_pred);
719 }
720 let decomposition = self.compute_decomposition(&ensemble_predictions, y)?;
721 Ok(decomposition)
722 }
723 fn generate_bootstrap_sample_with_offset(
725 &self,
726 x: &Array2<Float>,
727 y: &Array1<Float>,
728 _seed_offset: usize,
729 ) -> Result<(Array2<Float>, Array1<Float>)> {
730 let n_samples = x.nrows();
731 let bootstrap_size = (n_samples as Float * self.config.bootstrap_size) as usize;
732 let mut rng = thread_rng();
733 let mut indices = Vec::with_capacity(bootstrap_size);
734 for _ in 0..bootstrap_size {
735 let idx = rng.gen_range(0..n_samples);
736 indices.push(idx);
737 }
738 let x_bootstrap = x.select(Axis(0), &indices);
739 let y_bootstrap = y.select(Axis(0), &indices);
740 Ok((x_bootstrap, y_bootstrap))
741 }
742 pub(crate) fn generate_bootstrap_sample(
744 &self,
745 x: &Array2<Float>,
746 y: &Array1<Float>,
747 _bootstrap_idx: usize,
748 ) -> Result<(Array2<Float>, Array1<Float>)> {
749 self.generate_bootstrap_sample_with_offset(x, y, 0)
750 }
751 fn compute_decomposition(
753 &self,
754 all_predictions: &[Array1<Float>],
755 y_true: &Array1<Float>,
756 ) -> Result<BiasVarianceDecomposition> {
757 let n_samples = y_true.len();
758 let n_bootstrap = all_predictions.len();
759 if n_bootstrap == 0 {
760 return Err(SklearsError::InvalidInput(
761 "No predictions provided".to_string(),
762 ));
763 }
764 let mut mean_predictions = Array1::zeros(n_samples);
765 for predictions in all_predictions {
766 mean_predictions += predictions;
767 }
768 mean_predictions /= n_bootstrap as Float;
769 let sample_decompositions = if self.config.compute_sample_level {
770 let mut decomps = Vec::with_capacity(n_samples);
771 for sample_idx in 0..n_samples {
772 let true_value = y_true[sample_idx];
773 let mean_pred = mean_predictions[sample_idx];
774 let bootstrap_preds: Vec<Float> = all_predictions
775 .iter()
776 .map(|pred| pred[sample_idx])
777 .collect();
778 let bias_squared = self.compute_loss(mean_pred, true_value);
779 let variance = bootstrap_preds
780 .iter()
781 .map(|&pred| self.compute_loss(pred, mean_pred))
782 .sum::<Float>()
783 / n_bootstrap as Float;
784 decomps.push(SampleBiasVariance {
785 sample_idx,
786 true_value,
787 mean_prediction: mean_pred,
788 bias_squared,
789 variance,
790 bootstrap_predictions: bootstrap_preds,
791 });
792 }
793 Some(decomps)
794 } else {
795 None
796 };
797 let mut total_bias_squared = 0.0;
798 let mut total_variance = 0.0;
799 let mut total_loss = 0.0;
800 for sample_idx in 0..n_samples {
801 let true_value = y_true[sample_idx];
802 let mean_pred = mean_predictions[sample_idx];
803 let bias_squared = self.compute_loss(mean_pred, true_value);
804 total_bias_squared += bias_squared;
805 let sample_variance = all_predictions
806 .iter()
807 .map(|pred| self.compute_loss(pred[sample_idx], mean_pred))
808 .sum::<Float>()
809 / n_bootstrap as Float;
810 total_variance += sample_variance;
811 let sample_loss = all_predictions
812 .iter()
813 .map(|pred| self.compute_loss(pred[sample_idx], true_value))
814 .sum::<Float>()
815 / n_bootstrap as Float;
816 total_loss += sample_loss;
817 }
818 total_bias_squared /= n_samples as Float;
819 total_variance /= n_samples as Float;
820 total_loss /= n_samples as Float;
821 let noise = match self.config.loss_function {
822 ModelSelectionLossFunction::SquaredLoss => {
823 (total_loss - total_bias_squared - total_variance).max(0.0)
824 }
825 _ => 0.0,
826 };
827 Ok(BiasVarianceDecomposition {
828 bias_squared: total_bias_squared,
829 variance: total_variance,
830 noise,
831 total_loss,
832 n_bootstrap_samples: n_bootstrap,
833 sample_decompositions,
834 })
835 }
836 pub(crate) fn compute_loss(&self, prediction: Float, true_value: Float) -> Float {
838 match &self.config.loss_function {
839 ModelSelectionLossFunction::SquaredLoss => (prediction - true_value).powi(2),
840 ModelSelectionLossFunction::ZeroOneLoss => {
841 if (prediction - true_value).abs() < 0.5 {
842 0.0
843 } else {
844 1.0
845 }
846 }
847 ModelSelectionLossFunction::Custom(loss_fn) => loss_fn(prediction, true_value),
848 }
849 }
850 pub fn analyze_ensemble_size_effect<E>(
852 &self,
853 base_estimator: E,
854 max_ensemble_size: usize,
855 x: &Array2<Float>,
856 y: &Array1<Float>,
857 ) -> Result<BiasVarianceEnsembleSizeAnalysis>
858 where
859 E: Clone + Fit<Mat2f, Vec1f, Untrained>,
860 <E as Fit<Mat2f, Vec1f, Untrained>>::Fitted: Predict<Mat2f, Vec1f>,
861 {
862 let ensemble_sizes: Vec<usize> = (1..=max_ensemble_size)
863 .step_by(if max_ensemble_size > 20 {
864 max_ensemble_size / 20
865 } else {
866 1
867 })
868 .collect();
869 let decompositions = self.decompose_ensemble(base_estimator, &ensemble_sizes, x, y)?;
870 let bias_curve: Vec<Float> = decompositions
871 .iter()
872 .map(|(_, decomp)| decomp.bias_squared)
873 .collect();
874 let variance_curve: Vec<Float> = decompositions
875 .iter()
876 .map(|(_, decomp)| decomp.variance)
877 .collect();
878 let total_error_curve: Vec<Float> = decompositions
879 .iter()
880 .map(|(_, decomp)| decomp.total_loss)
881 .collect();
882 let optimal_idx = total_error_curve
883 .iter()
884 .enumerate()
885 .min_by(|(_, a), (_, b)| a.partial_cmp(b).expect("operation should succeed"))
886 .map(|(idx, _)| idx)
887 .unwrap_or(0);
888 let optimal_size = ensemble_sizes[optimal_idx];
889 let bias_reduction = bias_curve[0] - bias_curve.last().unwrap_or(&bias_curve[0]);
890 let variance_reduction =
891 variance_curve[0] - variance_curve.last().unwrap_or(&variance_curve[0]);
892 Ok(BiasVarianceEnsembleSizeAnalysis {
893 ensemble_sizes,
894 bias_curve,
895 variance_curve,
896 total_error_curve,
897 optimal_ensemble_size: optimal_size,
898 bias_reduction,
899 variance_reduction,
900 })
901 }
902}
903impl BiasVarianceAnalyzer {
905 pub fn for_regression(n_bootstrap_samples: usize) -> Self {
907 let config = BiasVarianceConfig {
908 n_bootstrap_samples,
909 loss_function: ModelSelectionLossFunction::SquaredLoss,
910 ..Default::default()
911 };
912 Self::new(config)
913 }
914 pub fn for_classification(n_bootstrap_samples: usize) -> Self {
916 let config = BiasVarianceConfig {
917 n_bootstrap_samples,
918 loss_function: ModelSelectionLossFunction::ZeroOneLoss,
919 ..Default::default()
920 };
921 Self::new(config)
922 }
923 pub fn with_sample_analysis(n_bootstrap_samples: usize) -> Self {
925 let config = BiasVarianceConfig {
926 n_bootstrap_samples,
927 compute_sample_level: true,
928 ..Default::default()
929 };
930 Self::new(config)
931 }
932}
933#[derive(Debug)]
935pub struct EnsembleCVResults {
936 pub mean_score: Float,
938 pub std_score: Float,
940 pub fold_scores: Vec<Float>,
942 pub best_config: HashMap<String, Float>,
944 pub diversity_metrics: DiversityMetrics,
946 pub training_time: Float,
948}
949pub struct DiversityAnalyzer;
951impl DiversityAnalyzer {
952 pub fn compute_diversity_metrics(
954 predictions: &[Array1<Float>],
955 ground_truth: &Array1<Float>,
956 ) -> Result<DiversityMetrics> {
957 if predictions.is_empty() {
958 return Err(SklearsError::InvalidInput(
959 "No predictions provided".to_string(),
960 ));
961 }
962 let _n_classifiers = predictions.len();
963 let n_samples = predictions[0].len();
964 for pred in predictions {
965 if pred.len() != n_samples {
966 return Err(SklearsError::InvalidInput(
967 "Inconsistent prediction lengths".to_string(),
968 ));
969 }
970 }
971 let class_predictions: Vec<Vec<i32>> = predictions
972 .iter()
973 .map(|pred| pred.iter().map(|&p| p.round() as i32).collect())
974 .collect();
975 let disagreement = Self::compute_disagreement(&class_predictions);
976 let double_fault = Self::compute_double_fault(&class_predictions, ground_truth);
977 let q_statistic = Self::compute_q_statistic(&class_predictions);
978 let entropy_diversity = Self::compute_entropy_diversity(&class_predictions);
979 let kw_variance = Self::compute_kw_variance(&class_predictions);
980 let kappa = Self::compute_cohens_kappa(&class_predictions)?;
981 let fleiss_kappa = Self::compute_fleiss_kappa(&class_predictions)?;
982 let interrater_reliability = Self::compute_interrater_reliability(&class_predictions)?;
983 Ok(DiversityMetrics {
984 disagreement,
985 double_fault,
986 q_statistic,
987 entropy_diversity,
988 kw_variance,
989 kappa,
990 fleiss_kappa,
991 interrater_reliability,
992 })
993 }
994 pub(crate) fn compute_disagreement(predictions: &[Vec<i32>]) -> Float {
996 let n_classifiers = predictions.len();
997 if n_classifiers < 2 {
998 return 0.0;
999 }
1000 let mut total_disagreement = 0.0;
1001 let mut pair_count = 0;
1002 for i in 0..n_classifiers {
1003 for j in (i + 1)..n_classifiers {
1004 let disagreement_ij = predictions[i]
1005 .iter()
1006 .zip(&predictions[j])
1007 .map(|(&pred_i, &pred_j)| if pred_i != pred_j { 1.0 } else { 0.0 })
1008 .sum::<Float>()
1009 / predictions[i].len() as Float;
1010 total_disagreement += disagreement_ij;
1011 pair_count += 1;
1012 }
1013 }
1014 total_disagreement / pair_count as Float
1015 }
1016 fn compute_double_fault(predictions: &[Vec<i32>], ground_truth: &Array1<Float>) -> Float {
1018 let n_classifiers = predictions.len();
1019 if n_classifiers < 2 {
1020 return 0.0;
1021 }
1022 let ground_truth_int: Vec<i32> = ground_truth.iter().map(|&y| y.round() as i32).collect();
1023 let mut total_double_fault = 0.0;
1024 let mut pair_count = 0;
1025 for i in 0..n_classifiers {
1026 for j in (i + 1)..n_classifiers {
1027 let double_fault_ij = predictions[i]
1028 .iter()
1029 .zip(&predictions[j])
1030 .zip(&ground_truth_int)
1031 .map(|((&pred_i, &pred_j), &true_label)| {
1032 if pred_i != true_label && pred_j != true_label {
1033 1.0
1034 } else {
1035 0.0
1036 }
1037 })
1038 .sum::<Float>()
1039 / predictions[i].len() as Float;
1040 total_double_fault += double_fault_ij;
1041 pair_count += 1;
1042 }
1043 }
1044 total_double_fault / pair_count as Float
1045 }
1046 fn compute_q_statistic(predictions: &[Vec<i32>]) -> Float {
1048 let n_classifiers = predictions.len();
1049 if n_classifiers < 2 {
1050 return 0.0;
1051 }
1052 let mut total_q = 0.0;
1053 let mut pair_count = 0;
1054 for i in 0..n_classifiers {
1055 for j in (i + 1)..n_classifiers {
1056 let mut n11 = 0.0;
1057 let mut n10 = 0.0;
1058 let mut n01 = 0.0;
1059 let mut n00 = 0.0;
1060 for (&pi, &pj) in predictions[i].iter().zip(predictions[j].iter()) {
1061 let i_correct = pi == 1;
1062 let j_correct = pj == 1;
1063 match (i_correct, j_correct) {
1064 (true, true) => n11 += 1.0,
1065 (true, false) => n10 += 1.0,
1066 (false, true) => n01 += 1.0,
1067 (false, false) => n00 += 1.0,
1068 }
1069 }
1070 let denominator = (n11 * n00) + (n01 * n10);
1071 let q_ij = if denominator != 0.0 {
1072 ((n11 * n00) - (n01 * n10)) / denominator
1073 } else {
1074 0.0
1075 };
1076 total_q += q_ij;
1077 pair_count += 1;
1078 }
1079 }
1080 total_q / pair_count as Float
1081 }
1082 fn compute_entropy_diversity(predictions: &[Vec<i32>]) -> Float {
1084 let n_samples = predictions[0].len();
1085 let n_classifiers = predictions.len();
1086 let mut total_entropy = 0.0;
1087 for sample_idx in 0..n_samples {
1088 let mut class_counts = std::collections::HashMap::new();
1089 for pred_vec in predictions.iter() {
1090 let prediction = pred_vec[sample_idx];
1091 *class_counts.entry(prediction).or_insert(0) += 1;
1092 }
1093 let mut sample_entropy = 0.0;
1094 for &count in class_counts.values() {
1095 let probability = count as Float / n_classifiers as Float;
1096 if probability > 0.0 {
1097 sample_entropy -= probability * probability.ln();
1098 }
1099 }
1100 total_entropy += sample_entropy;
1101 }
1102 total_entropy / n_samples as Float
1103 }
1104 fn compute_kw_variance(predictions: &[Vec<i32>]) -> Float {
1106 let n_samples = predictions[0].len();
1107 let n_classifiers = predictions.len();
1108 let mut total_variance = 0.0;
1109 for sample_idx in 0..n_samples {
1110 let sample_predictions: Vec<Float> = predictions
1111 .iter()
1112 .map(|pred_vec| pred_vec[sample_idx] as Float)
1113 .collect();
1114 let mean = sample_predictions.iter().sum::<Float>() / n_classifiers as Float;
1115 let variance = sample_predictions
1116 .iter()
1117 .map(|&pred| (pred - mean).powi(2))
1118 .sum::<Float>()
1119 / n_classifiers as Float;
1120 total_variance += variance;
1121 }
1122 total_variance / n_samples as Float
1123 }
1124 pub(crate) fn compute_cohens_kappa(predictions: &[Vec<i32>]) -> Result<Float> {
1126 let n_classifiers = predictions.len();
1127 if n_classifiers < 2 {
1128 return Ok(0.0);
1129 }
1130 let mut total_kappa = 0.0;
1131 let mut pair_count = 0;
1132 for i in 0..n_classifiers {
1133 for j in (i + 1)..n_classifiers {
1134 let kappa_ij = Self::compute_pairwise_kappa(&predictions[i], &predictions[j])?;
1135 total_kappa += kappa_ij;
1136 pair_count += 1;
1137 }
1138 }
1139 Ok(total_kappa / pair_count as Float)
1140 }
1141 pub(crate) fn compute_pairwise_kappa(pred1: &[i32], pred2: &[i32]) -> Result<Float> {
1143 if pred1.len() != pred2.len() {
1144 return Err(SklearsError::InvalidInput(
1145 "Predictions must have same length".to_string(),
1146 ));
1147 }
1148 let n = pred1.len();
1149 if n == 0 {
1150 return Ok(0.0);
1151 }
1152 let mut classes = std::collections::HashSet::new();
1153 for &pred in pred1.iter().chain(pred2.iter()) {
1154 classes.insert(pred);
1155 }
1156 let classes: Vec<i32> = classes.into_iter().collect();
1157 let n_classes = classes.len();
1158 let mut confusion_matrix = vec![vec![0; n_classes]; n_classes];
1159 for (&p1, &p2) in pred1.iter().zip(pred2.iter()) {
1160 let ci = classes
1161 .iter()
1162 .position(|&c| c == p1)
1163 .expect("operation should succeed");
1164 let cj = classes
1165 .iter()
1166 .position(|&c| c == p2)
1167 .expect("operation should succeed");
1168 confusion_matrix[ci][cj] += 1;
1169 }
1170 let observed_agreement = (0..n_classes)
1171 .map(|i| confusion_matrix[i][i])
1172 .sum::<usize>() as Float
1173 / n as Float;
1174 let mut expected_agreement = 0.0;
1175 for (row_idx, row) in confusion_matrix.iter().enumerate() {
1176 let row_sum: usize = row.iter().sum();
1177 let col_sum: usize = confusion_matrix.iter().map(|r| r[row_idx]).sum();
1178 expected_agreement += (row_sum as Float * col_sum as Float) / (n * n) as Float;
1179 }
1180 let kappa = if expected_agreement == 1.0 {
1181 1.0
1182 } else {
1183 (observed_agreement - expected_agreement) / (1.0 - expected_agreement)
1184 };
1185 Ok(kappa)
1186 }
1187 pub(crate) fn compute_fleiss_kappa(predictions: &[Vec<i32>]) -> Result<Float> {
1189 let n_classifiers = predictions.len();
1190 let n_samples = predictions[0].len();
1191 if n_classifiers < 2 || n_samples == 0 {
1192 return Ok(0.0);
1193 }
1194 let mut classes = std::collections::HashSet::new();
1195 for pred_vec in predictions {
1196 for &pred in pred_vec {
1197 classes.insert(pred);
1198 }
1199 }
1200 let classes: Vec<i32> = classes.into_iter().collect();
1201 let n_classes = classes.len();
1202 let mut agreement_matrix = vec![vec![0; n_classes]; n_samples];
1203 for (sample_idx, row) in agreement_matrix.iter_mut().enumerate() {
1204 for pred_vec in predictions.iter() {
1205 let prediction = pred_vec[sample_idx];
1206 let class_idx = classes
1207 .iter()
1208 .position(|&c| c == prediction)
1209 .expect("operation should succeed");
1210 row[class_idx] += 1;
1211 }
1212 }
1213 let mut total_agreement = 0.0;
1214 for row in &agreement_matrix {
1215 let sample_agreement: Float = row
1216 .iter()
1217 .map(|&n_ij| {
1218 let n = n_ij as Float;
1219 n * (n - 1.0)
1220 })
1221 .sum();
1222 total_agreement += sample_agreement;
1223 }
1224 let observed_agreement =
1225 total_agreement / (n_samples * n_classifiers * (n_classifiers - 1)) as Float;
1226 let mut expected_agreement = 0.0;
1227 for class_idx in 0..n_classes {
1228 let class_proportion = agreement_matrix
1229 .iter()
1230 .map(|row| row[class_idx])
1231 .sum::<usize>() as Float
1232 / (n_samples * n_classifiers) as Float;
1233 expected_agreement += class_proportion * class_proportion;
1234 }
1235 let fleiss_kappa = if expected_agreement == 1.0 {
1236 1.0
1237 } else {
1238 (observed_agreement - expected_agreement) / (1.0 - expected_agreement)
1239 };
1240 Ok(fleiss_kappa)
1241 }
1242 fn compute_interrater_reliability(predictions: &[Vec<i32>]) -> Result<InterraterReliability> {
1244 let n_classifiers = predictions.len();
1245 let n_samples = predictions[0].len();
1246 if n_classifiers < 2 || n_samples == 0 {
1247 return Ok(InterraterReliability {
1248 overall_agreement: 0.0,
1249 chance_agreement: 0.0,
1250 krippendorff_alpha: 0.0,
1251 pearson_correlation: 0.0,
1252 weighted_kappa: 0.0,
1253 kappa_std_error: 0.0,
1254 });
1255 }
1256 let mut exact_agreements = 0;
1257 for sample_idx in 0..n_samples {
1258 let first_pred = predictions[0][sample_idx];
1259 let all_agree = predictions
1260 .iter()
1261 .all(|pred| pred[sample_idx] == first_pred);
1262 if all_agree {
1263 exact_agreements += 1;
1264 }
1265 }
1266 let overall_agreement = exact_agreements as Float / n_samples as Float;
1267 let mut class_counts = std::collections::HashMap::new();
1268 for pred_vec in predictions {
1269 for &pred in pred_vec {
1270 *class_counts.entry(pred).or_insert(0) += 1;
1271 }
1272 }
1273 let total_predictions = n_classifiers * n_samples;
1274 let chance_agreement = class_counts
1275 .values()
1276 .map(|&count| {
1277 let prob = count as Float / total_predictions as Float;
1278 prob.powi(n_classifiers as i32)
1279 })
1280 .sum::<Float>();
1281 let krippendorff_alpha = Self::compute_krippendorff_alpha(predictions)?;
1282 let pearson_correlation = Self::compute_average_correlation(predictions)?;
1283 let weighted_kappa = Self::compute_cohens_kappa(predictions)?;
1284 let kappa_std_error =
1285 (overall_agreement * (1.0 - overall_agreement) / n_samples as Float).sqrt();
1286 Ok(InterraterReliability {
1287 overall_agreement,
1288 chance_agreement,
1289 krippendorff_alpha,
1290 pearson_correlation,
1291 weighted_kappa,
1292 kappa_std_error,
1293 })
1294 }
1295 fn compute_krippendorff_alpha(predictions: &[Vec<i32>]) -> Result<Float> {
1297 let n_classifiers = predictions.len();
1298 let _n_samples = predictions[0].len();
1299 if n_classifiers < 2 {
1300 return Ok(0.0);
1301 }
1302 let mut observed_disagreements = 0.0;
1303 let mut expected_disagreements = 0.0;
1304 for i in 0..n_classifiers {
1305 for j in (i + 1)..n_classifiers {
1306 for (&vi, &vj) in predictions[i].iter().zip(predictions[j].iter()) {
1307 if vi != vj {
1308 observed_disagreements += 1.0;
1309 }
1310 expected_disagreements += 0.5;
1311 }
1312 }
1313 }
1314 let alpha = if expected_disagreements > 0.0 {
1315 1.0 - (observed_disagreements / expected_disagreements)
1316 } else {
1317 1.0
1318 };
1319 Ok(alpha)
1320 }
1321 fn compute_average_correlation(predictions: &[Vec<i32>]) -> Result<Float> {
1323 let n_classifiers = predictions.len();
1324 if n_classifiers < 2 {
1325 return Ok(0.0);
1326 }
1327 let mut total_correlation = 0.0;
1328 let mut pair_count = 0;
1329 for i in 0..n_classifiers {
1330 for j in (i + 1)..n_classifiers {
1331 let corr = Self::compute_pearson_correlation(&predictions[i], &predictions[j])?;
1332 total_correlation += corr;
1333 pair_count += 1;
1334 }
1335 }
1336 Ok(total_correlation / pair_count as Float)
1337 }
1338 pub(crate) fn compute_pearson_correlation(pred1: &[i32], pred2: &[i32]) -> Result<Float> {
1340 if pred1.len() != pred2.len() || pred1.is_empty() {
1341 return Ok(0.0);
1342 }
1343 let n = pred1.len() as Float;
1344 let mean1 = pred1.iter().sum::<i32>() as Float / n;
1345 let mean2 = pred2.iter().sum::<i32>() as Float / n;
1346 let mut numerator = 0.0;
1347 let mut sum_sq1 = 0.0;
1348 let mut sum_sq2 = 0.0;
1349 for i in 0..pred1.len() {
1350 let diff1 = pred1[i] as Float - mean1;
1351 let diff2 = pred2[i] as Float - mean2;
1352 numerator += diff1 * diff2;
1353 sum_sq1 += diff1 * diff1;
1354 sum_sq2 += diff2 * diff2;
1355 }
1356 let denominator = (sum_sq1 * sum_sq2).sqrt();
1357 let correlation = if denominator > 0.0 {
1358 numerator / denominator
1359 } else {
1360 0.0
1361 };
1362 Ok(correlation)
1363 }
1364}
1365#[derive(Debug, Clone)]
1367pub struct SampleBiasVariance {
1368 pub sample_idx: usize,
1370 pub true_value: Float,
1372 pub mean_prediction: Float,
1374 pub bias_squared: Float,
1376 pub variance: Float,
1378 pub bootstrap_predictions: Vec<Float>,
1380}
1381#[derive(Debug, Clone)]
1383pub struct EnsembleConstructionConfig {
1384 pub cv_strategy: EnsembleCVStrategy,
1386 pub scoring: ScoringMetric,
1388 pub random_state: Option<u64>,
1390 pub early_stopping: bool,
1392 pub patience: usize,
1394 pub min_improvement: Float,
1396 pub max_ensemble_size: Option<usize>,
1398 pub diversity_weight: Float,
1400}