sklears-ensemble 0.1.2

Ensemble methods for sklears: Random Forest, Gradient Boosting, AdaBoost
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! SIMD-accelerated operations for high-performance ensemble voting computations
//!
//! This module provides a thin wrapper around scirs2-core::simd_ops::SimdUnifiedOps,
//! ensuring SciRS2 Policy compliance. All SIMD operations are delegated to SciRS2-Core.
//!
//! ## SciRS2 Policy Compliance
//! ✅ Uses `scirs2-core::simd_ops::SimdUnifiedOps` for all SIMD operations
//! ✅ No direct implementation of SIMD code (policy requirement)
//! ✅ Works on stable Rust (no nightly features required)

use scirs2_core::ndarray::{Array1, Array2, ArrayView1};
use scirs2_core::simd_ops::SimdUnifiedOps;
use sklears_core::{error::Result, types::Float};

/// Mean calculation for f32 arrays using SciRS2 SIMD
#[inline]
pub fn simd_mean_f32(data: &[f32]) -> f32 {
    if data.is_empty() {
        return 0.0;
    }
    let arr = ArrayView1::from(data);
    f32::simd_mean(&arr)
}

/// Sum calculation for f32 arrays using SciRS2 SIMD
#[inline]
pub fn simd_sum_f32(data: &[f32]) -> f32 {
    if data.is_empty() {
        return 0.0;
    }
    let arr = ArrayView1::from(data);
    f32::simd_sum(&arr)
}

/// Variance calculation for f32 arrays using SciRS2 SIMD
pub fn simd_variance_f32(data: &[f32], mean: f32) -> f32 {
    if data.len() <= 1 {
        return 0.0;
    }
    let arr = ArrayView1::from(data);
    let mean_vec = Array1::from_elem(data.len(), mean);
    let diff = f32::simd_sub(&arr, &mean_vec.view());
    let sum_sq = f32::simd_sum_squares(&diff.view());
    sum_sq / (data.len() - 1) as f32
}

/// Entropy calculation for probability distributions
pub fn simd_entropy_f32(probabilities: &[f32]) -> f32 {
    if probabilities.is_empty() {
        return 0.0;
    }
    let mut entropy = 0.0;
    for &prob in probabilities {
        if prob > 1e-8 {
            entropy -= prob * prob.ln();
        }
    }
    entropy
}

/// Weighted sum for probability aggregation using SciRS2 SIMD
pub fn simd_weighted_sum_f32(values: &[f32], weights: &[f32], output: &mut [f32]) {
    let len = values.len().min(weights.len()).min(output.len());
    let val_arr = ArrayView1::from(&values[..len]);
    let weight_arr = ArrayView1::from(&weights[..len]);
    let result = f32::simd_mul(&val_arr, &weight_arr);
    output[..len].copy_from_slice(result.as_slice().expect("slice operation should succeed"));
}

/// Vector addition for probability combination using SciRS2 SIMD
pub fn simd_add_f32(a: &[f32], b: &[f32], output: &mut [f32]) {
    let len = a.len().min(b.len()).min(output.len());
    let a_arr = ArrayView1::from(&a[..len]);
    let b_arr = ArrayView1::from(&b[..len]);
    let result = f32::simd_add(&a_arr, &b_arr);
    output[..len].copy_from_slice(result.as_slice().expect("slice operation should succeed"));
}

/// Scalar multiplication for weight application using SciRS2 SIMD
pub fn simd_scale_f32(input: &[f32], scalar: f32, output: &mut [f32]) {
    let len = input.len().min(output.len());
    let input_arr = ArrayView1::from(&input[..len]);
    let result = f32::simd_scalar_mul(&input_arr, scalar);
    output[..len].copy_from_slice(result.as_slice().expect("slice operation should succeed"));
}

/// Argmax operation for finding maximum index
pub fn simd_argmax_f32(values: &[f32]) -> usize {
    if values.is_empty() {
        return 0;
    }
    let arr = ArrayView1::from(values);
    let max_val = f32::simd_max_element(&arr);

    // Find first occurrence of max value
    values.iter().position(|&v| v == max_val).unwrap_or(0)
}

/// L2 normalization using SciRS2 SIMD
pub fn simd_normalize_f32(input: &[f32], output: &mut [f32]) {
    let len = input.len().min(output.len());
    if len == 0 {
        return;
    }

    let input_arr = ArrayView1::from(&input[..len]);
    let norm = f32::simd_norm(&input_arr);

    if norm > 1e-8 {
        let result = f32::simd_scalar_mul(&input_arr, 1.0 / norm);
        output[..len].copy_from_slice(result.as_slice().expect("slice operation should succeed"));
    } else {
        output[..len].fill(0.0);
    }
}

/// Confidence calculation for predictions
pub fn simd_confidence_f32(predictions: &[f32]) -> f32 {
    if predictions.is_empty() {
        return 0.0;
    }
    let max_idx = simd_argmax_f32(predictions);
    let max_val = predictions[max_idx];
    let sum = simd_sum_f32(predictions);
    if sum > 1e-8 {
        max_val / sum
    } else {
        0.0
    }
}

/// Matrix-vector multiplication for ensemble voting using SciRS2 SIMD
pub fn simd_matrix_vector_multiply(
    matrix: &Array2<Float>,
    vector: &Array1<Float>,
    result: &mut Array1<Float>,
) -> Result<()> {
    if matrix.ncols() != vector.len() || matrix.nrows() != result.len() {
        return Err(sklears_core::error::SklearsError::ShapeMismatch {
            expected: format!(
                "matrix: {}x{}, vector: {}",
                matrix.nrows(),
                matrix.ncols(),
                vector.len()
            ),
            actual: format!("result: {}", result.len()),
        });
    }

    // Use SciRS2's GEMV (matrix-vector multiplication)
    Float::simd_gemv(&matrix.view(), &vector.view(), 0.0, result);
    Ok(())
}

/// Probability aggregation for ensemble voting using SciRS2 SIMD
pub fn simd_aggregate_probabilities(
    all_probabilities: &[Array2<Float>],
    weights: &[Float],
    result: &mut Array2<Float>,
) -> Result<()> {
    if all_probabilities.is_empty() || weights.is_empty() {
        return Err(sklears_core::error::SklearsError::InvalidParameter {
            name: "input_data".to_string(),
            reason: "Empty probabilities or weights".to_string(),
        });
    }

    let n_estimators = all_probabilities.len().min(weights.len());
    let n_samples = all_probabilities[0].nrows();
    let n_classes = all_probabilities[0].ncols();

    result.fill(0.0);

    let weight_sum: Float = weights[..n_estimators].iter().sum();
    if weight_sum <= 1e-8 {
        return Err(sklears_core::error::SklearsError::InvalidParameter {
            name: "weights".to_string(),
            reason: "Zero weight sum".to_string(),
        });
    }

    for sample_idx in 0..n_samples {
        for class_idx in 0..n_classes {
            let mut weighted_sum = 0.0;
            for (est_idx, prob_matrix) in all_probabilities[..n_estimators].iter().enumerate() {
                weighted_sum += prob_matrix[[sample_idx, class_idx]] * weights[est_idx];
            }
            result[[sample_idx, class_idx]] = weighted_sum / weight_sum;
        }
    }

    Ok(())
}

/// Rank calculation for rank-based voting
pub fn simd_calculate_ranks(values: &[f32], ranks: &mut [f32]) -> Result<()> {
    if values.len() != ranks.len() {
        return Err(sklears_core::error::SklearsError::ShapeMismatch {
            expected: format!("{}", values.len()),
            actual: format!("{}", ranks.len()),
        });
    }

    let n = values.len();
    let mut indices: Vec<usize> = (0..n).collect();
    indices.sort_by(|&a, &b| {
        values[b]
            .partial_cmp(&values[a])
            .expect("operation should succeed")
    });

    for (rank, &idx) in indices.iter().enumerate() {
        ranks[idx] = (rank + 1) as f32;
    }

    Ok(())
}

/// Ensemble disagreement calculation
pub fn simd_ensemble_disagreement(
    predictions: &[Array1<Float>],
    disagreement: &mut Array1<Float>,
) -> Result<()> {
    if predictions.is_empty() {
        return Err(sklears_core::error::SklearsError::InvalidParameter {
            name: "predictions".to_string(),
            reason: "Empty predictions".to_string(),
        });
    }

    let n_samples = predictions[0].len();

    for sample_idx in 0..n_samples {
        let sample_preds: Vec<f32> = predictions
            .iter()
            .map(|pred| pred[sample_idx] as f32)
            .collect();

        let mean = simd_mean_f32(&sample_preds);
        let variance = simd_variance_f32(&sample_preds, mean);
        disagreement[sample_idx] = variance as Float;
    }

    Ok(())
}

/// Bootstrap aggregation
pub fn simd_bootstrap_aggregate(
    predictions: &[Array1<Float>],
    _n_bootstrap: usize,
    result: &mut Array1<Float>,
) -> Result<()> {
    if predictions.is_empty() {
        return Err(sklears_core::error::SklearsError::InvalidParameter {
            name: "predictions".to_string(),
            reason: "Empty predictions".to_string(),
        });
    }

    let n_samples = predictions[0].len();
    result.fill(0.0);

    for sample_idx in 0..n_samples {
        let sample_preds: Vec<f32> = predictions
            .iter()
            .map(|pred| pred[sample_idx] as f32)
            .collect();

        result[sample_idx] = simd_mean_f32(&sample_preds) as Float;
    }

    Ok(())
}

/// Adaptive weight computation
pub fn simd_adaptive_weights(
    performances: &[f32],
    current_weights: &[f32],
    learning_rate: f32,
    output_weights: &mut [f32],
) {
    let len = performances
        .len()
        .min(current_weights.len())
        .min(output_weights.len());

    let perf_sum = simd_sum_f32(&performances[..len]);
    let mut normalized_perfs = vec![0.0f32; len];

    if perf_sum > 1e-8 {
        simd_scale_f32(&performances[..len], 1.0 / perf_sum, &mut normalized_perfs);
    }

    for i in 0..len {
        let diff = normalized_perfs[i] - current_weights[i];
        output_weights[i] = current_weights[i] + learning_rate * diff;
    }

    let weight_sum = simd_sum_f32(&output_weights[..len]);
    if weight_sum > 1e-8 {
        let temp_weights: Vec<f32> = output_weights[..len].to_vec();
        simd_scale_f32(&temp_weights, 1.0 / weight_sum, &mut output_weights[..len]);
    }
}

/// Hard voting with weighted vote counting
pub fn simd_hard_voting_weighted(
    all_predictions: &[Array1<Float>],
    weights: &[Float],
    classes: &[Float],
) -> Array1<Float> {
    if all_predictions.is_empty() || weights.is_empty() || classes.is_empty() {
        return Array1::zeros(0);
    }

    let n_samples = all_predictions[0].len();
    let n_classes = classes.len();
    let n_estimators = all_predictions.len().min(weights.len());

    let mut votes = Array2::<Float>::zeros((n_samples, n_classes));

    for sample_idx in 0..n_samples {
        for estimator_idx in 0..n_estimators {
            let prediction = all_predictions[estimator_idx][sample_idx];
            for (class_idx, &class_val) in classes.iter().enumerate() {
                if (prediction - class_val).abs() < 1e-6 {
                    votes[[sample_idx, class_idx]] += weights[estimator_idx];
                    break;
                }
            }
        }
    }

    let mut result = Array1::<Float>::zeros(n_samples);
    for sample_idx in 0..n_samples {
        let sample_votes: Vec<f32> = (0..n_classes)
            .map(|i| votes[[sample_idx, i]] as f32)
            .collect();
        let max_class_idx = simd_argmax_f32(&sample_votes);
        result[sample_idx] = classes[max_class_idx];
    }

    result
}

/// Soft voting with probability averaging
pub fn simd_soft_voting_weighted(
    all_probabilities: &[Array2<Float>],
    weights: &[Float],
) -> Array2<Float> {
    if all_probabilities.is_empty() || weights.is_empty() {
        return Array2::zeros((0, 0));
    }

    let n_samples = all_probabilities[0].nrows();
    let n_classes = all_probabilities[0].ncols();
    let mut result = Array2::<Float>::zeros((n_samples, n_classes));

    if simd_aggregate_probabilities(all_probabilities, weights, &mut result).is_err() {
        let n_estimators = all_probabilities.len();
        result.fill(0.0);

        for prob_matrix in all_probabilities.iter() {
            for i in 0..n_samples {
                for j in 0..n_classes {
                    result[[i, j]] += prob_matrix[[i, j]] / n_estimators as Float;
                }
            }
        }
    }

    result
}

/// Entropy-weighted voting
pub fn simd_entropy_weighted_voting(
    all_probabilities: &[Array2<Float>],
    entropy_weight_factor: f32,
) -> Array2<Float> {
    if all_probabilities.is_empty() {
        return Array2::zeros((0, 0));
    }

    let n_samples = all_probabilities[0].nrows();
    let n_classes = all_probabilities[0].ncols();
    let n_estimators = all_probabilities.len();

    let mut entropy_weights = Vec::with_capacity(n_estimators);

    for prob_matrix in all_probabilities.iter() {
        let mut total_entropy = 0.0f32;

        for sample_idx in 0..n_samples {
            let sample_probs: Vec<f32> = (0..n_classes)
                .map(|class_idx| prob_matrix[[sample_idx, class_idx]] as f32)
                .collect();

            let entropy = simd_entropy_f32(&sample_probs);
            total_entropy += entropy;
        }

        let avg_entropy = total_entropy / n_samples as f32;
        let weight = if avg_entropy > 1e-6 {
            entropy_weight_factor / avg_entropy
        } else {
            entropy_weight_factor
        };

        entropy_weights.push(weight as Float);
    }

    let weight_sum: Float = entropy_weights.iter().sum();
    if weight_sum > 1e-8 {
        for w in entropy_weights.iter_mut() {
            *w /= weight_sum;
        }
    }

    simd_soft_voting_weighted(all_probabilities, &entropy_weights)
}

/// Variance-weighted voting
pub fn simd_variance_weighted_voting(
    all_probabilities: &[Array2<Float>],
    variance_weight_factor: f32,
) -> Array2<Float> {
    if all_probabilities.is_empty() {
        return Array2::zeros((0, 0));
    }

    let n_samples = all_probabilities[0].nrows();
    let n_classes = all_probabilities[0].ncols();
    let n_estimators = all_probabilities.len();

    let mut variance_weights = Vec::with_capacity(n_estimators);

    for prob_matrix in all_probabilities.iter() {
        let mut total_variance = 0.0f32;

        for sample_idx in 0..n_samples {
            let sample_probs: Vec<f32> = (0..n_classes)
                .map(|class_idx| prob_matrix[[sample_idx, class_idx]] as f32)
                .collect();

            let mean = simd_mean_f32(&sample_probs);
            let variance = simd_variance_f32(&sample_probs, mean);
            total_variance += variance;
        }

        let avg_variance = total_variance / n_samples as f32;
        let weight = if avg_variance > 1e-6 {
            variance_weight_factor / avg_variance
        } else {
            variance_weight_factor
        };

        variance_weights.push(weight as Float);
    }

    let weight_sum: Float = variance_weights.iter().sum();
    if weight_sum > 1e-8 {
        for w in variance_weights.iter_mut() {
            *w /= weight_sum;
        }
    }

    simd_soft_voting_weighted(all_probabilities, &variance_weights)
}

/// Confidence-weighted voting
pub fn simd_confidence_weighted_voting(
    all_probabilities: &[Array2<Float>],
    confidence_threshold: f32,
) -> Array2<Float> {
    if all_probabilities.is_empty() {
        return Array2::zeros((0, 0));
    }

    let n_samples = all_probabilities[0].nrows();
    let n_classes = all_probabilities[0].ncols();
    let n_estimators = all_probabilities.len();

    let mut confidence_weights = Vec::with_capacity(n_estimators);

    for prob_matrix in all_probabilities.iter() {
        let mut total_confidence = 0.0f32;

        for sample_idx in 0..n_samples {
            let sample_probs: Vec<f32> = (0..n_classes)
                .map(|class_idx| prob_matrix[[sample_idx, class_idx]] as f32)
                .collect();

            let confidence = simd_confidence_f32(&sample_probs);
            total_confidence += confidence.max(confidence_threshold);
        }

        let avg_confidence = total_confidence / n_samples as f32;
        confidence_weights.push(avg_confidence as Float);
    }

    let weight_sum: Float = confidence_weights.iter().sum();
    if weight_sum > 1e-8 {
        for w in confidence_weights.iter_mut() {
            *w /= weight_sum;
        }
    }

    simd_soft_voting_weighted(all_probabilities, &confidence_weights)
}

/// Bayesian model averaging
pub fn simd_bayesian_averaging(
    all_probabilities: &[Array2<Float>],
    model_evidences: &[Float],
) -> Array2<Float> {
    if all_probabilities.is_empty() || model_evidences.is_empty() {
        return Array2::zeros((0, 0));
    }

    let n_estimators = all_probabilities.len().min(model_evidences.len());
    let weights: Vec<Float> = model_evidences[..n_estimators].to_vec();

    simd_soft_voting_weighted(&all_probabilities[..n_estimators], &weights)
}