aprender-core 0.30.0

Next-generation machine learning library in pure Rust
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
pub(crate) use super::*;
pub(super) fn simple_linear_model(x: &Vector<f32>) -> f32 {
    // Simple linear model: y = 2*x0 + 3*x1 - 1*x2 + 1.5
    2.0 * x[0] + 3.0 * x[1] - 1.0 * x[2] + 1.5
}

#[test]
fn test_shap_explainer_creation() {
    let background = vec![
        Vector::from_slice(&[1.0, 2.0, 3.0]),
        Vector::from_slice(&[2.0, 3.0, 4.0]),
    ];

    let explainer = ShapExplainer::new(&background, simple_linear_model);

    assert_eq!(explainer.n_features(), 3);
    assert!(explainer.expected_value() > 0.0); // Should be positive for our model
}

#[test]
fn test_shap_explain() {
    let background = vec![
        Vector::from_slice(&[0.0, 0.0, 0.0]),
        Vector::from_slice(&[1.0, 1.0, 1.0]),
        Vector::from_slice(&[2.0, 2.0, 2.0]),
    ];

    let explainer = ShapExplainer::new(&background, simple_linear_model);
    let sample = Vector::from_slice(&[1.0, 1.0, 1.0]);

    let shap_values = explainer.explain_with_model(&sample, simple_linear_model);

    // SHAP values should be finite
    for i in 0..shap_values.len() {
        assert!(shap_values[i].is_finite());
    }

    // Local accuracy: sum(shap) + expected ≈ prediction
    let prediction = simple_linear_model(&sample);
    let reconstructed: f32 = shap_values.sum() + explainer.expected_value();
    assert!(
        (prediction - reconstructed).abs() < 0.5,
        "Local accuracy: {} vs {} (diff: {})",
        prediction,
        reconstructed,
        (prediction - reconstructed).abs()
    );
}

#[test]
fn test_permutation_importance() {
    let x = vec![
        Vector::from_slice(&[1.0, 0.0, 0.0]),
        Vector::from_slice(&[2.0, 0.0, 0.0]),
        Vector::from_slice(&[3.0, 0.0, 0.0]),
        Vector::from_slice(&[4.0, 0.0, 0.0]),
    ];
    let y: Vec<f32> = x.iter().map(simple_linear_model).collect();

    // MSE scoring (higher = worse)
    let importance =
        PermutationImportance::compute(simple_linear_model, &x, &y, |pred, true_val| {
            (pred - true_val).powi(2)
        });

    // Feature 0 should have highest importance (coefficient 2.0)
    // Features 1 and 2 have zero importance (they're constant)
    let ranking = importance.ranking();
    assert_eq!(ranking[0], 0, "Feature 0 should be most important");
}

#[test]
fn test_permutation_importance_ranking() {
    let importance = PermutationImportance {
        importance: Vector::from_slice(&[0.1, 0.5, 0.3, 0.2]),
        baseline_score: 1.0,
    };

    let ranking = importance.ranking();
    assert_eq!(ranking, vec![1, 2, 3, 0]); // Sorted by abs importance
}

#[test]
fn test_feature_contributions_linear() {
    let weights = Vector::from_slice(&[2.0, 3.0, -1.0]);
    let features = Vector::from_slice(&[1.0, 2.0, 3.0]);
    let bias = 1.5;

    let contributions = FeatureContributions::from_linear(&weights, &features, bias);

    // Check individual contributions
    assert!((contributions.contributions[0] - 2.0).abs() < 1e-6); // 2.0 * 1.0
    assert!((contributions.contributions[1] - 6.0).abs() < 1e-6); // 3.0 * 2.0
    assert!((contributions.contributions[2] - (-3.0)).abs() < 1e-6); // -1.0 * 3.0

    // Check prediction
    let expected = 2.0 + 6.0 - 3.0 + 1.5; // = 6.5
    assert!((contributions.prediction - expected).abs() < 1e-6);

    // Verify sum
    assert!(contributions.verify_sum(1e-6));
}

#[test]
fn test_feature_contributions_top_features() {
    let contributions =
        FeatureContributions::new(Vector::from_slice(&[0.1, -0.5, 0.3, -0.2, 0.4]), 1.0);

    let top3 = contributions.top_features(3);

    assert_eq!(top3.len(), 3);
    assert_eq!(top3[0].0, 1); // -0.5 has highest abs value
    assert_eq!(top3[1].0, 4); // 0.4
    assert_eq!(top3[2].0, 2); // 0.3
}

#[test]
fn test_integrated_gradients_basic() {
    let ig = IntegratedGradients::new(20);

    let sample = Vector::from_slice(&[1.0, 2.0, 3.0]);
    let baseline = Vector::from_slice(&[0.0, 0.0, 0.0]);

    let attributions = ig.attribute(simple_linear_model, &sample, &baseline);

    // Attributions should be finite
    for i in 0..attributions.len() {
        assert!(attributions[i].is_finite());
    }

    // For linear model, attributions should match weight * (x - baseline)
    // Approximately: [2*1, 3*2, -1*3] = [2, 6, -3]
    assert!(
        (attributions[0] - 2.0).abs() < 0.5,
        "Feature 0 attribution: {}",
        attributions[0]
    );
    assert!(
        (attributions[1] - 6.0).abs() < 0.5,
        "Feature 1 attribution: {}",
        attributions[1]
    );
    assert!(
        (attributions[2] - (-3.0)).abs() < 0.5,
        "Feature 2 attribution: {}",
        attributions[2]
    );
}

#[test]
fn test_integrated_gradients_completeness() {
    // Completeness axiom: sum(attributions) = f(x) - f(baseline)
    let ig = IntegratedGradients::new(50);

    let sample = Vector::from_slice(&[2.0, 1.0, 0.5]);
    let baseline = Vector::from_slice(&[0.0, 0.0, 0.0]);

    let attributions = ig.attribute(simple_linear_model, &sample, &baseline);

    let sum_attr: f32 = attributions.sum();
    let delta = simple_linear_model(&sample) - simple_linear_model(&baseline);

    assert!(
        (sum_attr - delta).abs() < 0.5,
        "Completeness: sum={sum_attr}, delta={delta}"
    );
}

#[test]
fn test_integrated_gradients_default() {
    let ig = IntegratedGradients::default();
    assert_eq!(ig.n_steps, 50);
}

#[test]
fn test_shap_with_samples() {
    let background = vec![
        Vector::from_slice(&[0.0, 0.0, 0.0]),
        Vector::from_slice(&[1.0, 1.0, 1.0]),
    ];

    let explainer = ShapExplainer::new(&background, simple_linear_model).with_n_samples(50);

    assert_eq!(explainer.n_samples, 50);
}

// LIME Tests
#[test]
fn test_lime_creation() {
    let lime = LIME::new(100, 0.5);
    assert_eq!(lime.n_samples(), 100);
    assert_eq!(lime.kernel_width(), 0.5);
}

#[test]
fn test_lime_default() {
    let lime = LIME::default();
    assert_eq!(lime.n_samples(), 500);
    assert_eq!(lime.kernel_width(), 0.75);
}

#[test]
fn test_lime_explain_linear() {
    let lime = LIME::new(200, 1.0);
    let sample = Vector::from_slice(&[1.0, 2.0, 3.0]);

    let explanation = lime.explain(simple_linear_model, &sample, 42);

    // Coefficients should be finite
    for i in 0..explanation.coefficients.len() {
        assert!(explanation.coefficients[i].is_finite());
    }

    // Original prediction should match
    assert!((explanation.original_prediction - simple_linear_model(&sample)).abs() < 1e-6);
}

#[test]
fn test_lime_explanation_top_features() {
    let exp = LIMEExplanation {
        coefficients: Vector::from_slice(&[0.1, 0.5, -0.3, 0.2]),
        intercept: 1.0,
        original_prediction: 2.0,
    };

    let top2 = exp.top_features(2);
    assert_eq!(top2.len(), 2);
    assert_eq!(top2[0].0, 1); // 0.5 has highest abs
    assert_eq!(top2[1].0, 2); // -0.3 is second
}

#[test]
fn test_lime_local_prediction() {
    let exp = LIMEExplanation {
        coefficients: Vector::from_slice(&[2.0, 3.0]),
        intercept: 1.0,
        original_prediction: 8.0,
    };

    let sample = Vector::from_slice(&[1.0, 1.0]);
    let local = exp.local_prediction(&sample);
    // intercept + 2*1 + 3*1 = 1 + 2 + 3 = 6
    assert!((local - 6.0).abs() < 1e-6);
}

// Saliency Maps Tests
#[test]
fn test_saliency_map_creation() {
    let sm = SaliencyMap::new();
    assert!((sm.epsilon() - 1e-4).abs() < 1e-10);
}

#[test]
fn test_saliency_map_custom_epsilon() {
    let sm = SaliencyMap::with_epsilon(1e-3);
    assert!((sm.epsilon() - 1e-3).abs() < 1e-10);
}

#[test]
fn test_saliency_map_compute() {
    let sm = SaliencyMap::new();
    let sample = Vector::from_slice(&[1.0, 2.0, 3.0]);

    let saliency = sm.compute(simple_linear_model, &sample);

    // Gradients should be approximately [2, 3, -1] (model coefficients)
    assert!(saliency.len() == 3);
    assert!((saliency[0] - 2.0).abs() < 0.1, "Got {}", saliency[0]);
    assert!((saliency[1] - 3.0).abs() < 0.1, "Got {}", saliency[1]);
    assert!((saliency[2] - (-1.0)).abs() < 0.1, "Got {}", saliency[2]);
}

#[test]
fn test_saliency_map_absolute() {
    let sm = SaliencyMap::new();
    let sample = Vector::from_slice(&[1.0, 2.0, 3.0]);

    let saliency = sm.compute_absolute(simple_linear_model, &sample);

    // All values should be positive
    for i in 0..saliency.len() {
        assert!(saliency[i] >= 0.0);
    }
}

// Counterfactual Tests
#[test]
fn test_counterfactual_creation() {
    let cf = CounterfactualExplainer::new(100, 0.01);
    assert_eq!(cf.max_iter(), 100);
    assert!((cf.step_size() - 0.01).abs() < 1e-10);
}

#[test]
fn test_counterfactual_find() {
    // Model: classify as 1 if x[0] + x[1] > 2
    let model = |x: &Vector<f32>| -> usize { usize::from(x[0] + x[1] > 2.0) };

    let cf = CounterfactualExplainer::new(500, 0.1);
    let original = Vector::from_slice(&[0.5, 0.5]); // Class 0

    if let Some(result) = cf.find(&original, 1, model) {
        // Counterfactual should be class 1
        let cf_class = model(&result.counterfactual);
        assert_eq!(cf_class, 1, "Counterfactual should achieve target class");

        // Distance should be finite
        assert!(result.distance.is_finite());
    }
}

#[test]
fn test_counterfactual_changes() {
    let result = CounterfactualResult {
        counterfactual: Vector::from_slice(&[1.5, 1.5, 0.5]),
        original: Vector::from_slice(&[1.0, 1.0, 1.0]),
        target_class: 1,
        distance: 0.5,
    };

    let changes = result.feature_changes();

    assert_eq!(changes.len(), 3);
    assert!((changes[0] - 0.5).abs() < 1e-6);
    assert!((changes[1] - 0.5).abs() < 1e-6);
    assert!((changes[2] - (-0.5)).abs() < 1e-6);
}

#[test]
fn test_counterfactual_top_changes() {
    let result = CounterfactualResult {
        counterfactual: Vector::from_slice(&[2.0, 1.1, 3.0]),
        original: Vector::from_slice(&[1.0, 1.0, 1.0]),
        target_class: 1,
        distance: 2.0,
    };

    let top = result.top_changed_features(2);

    assert_eq!(top.len(), 2);
    assert_eq!(top[0].0, 2); // Largest change: 3.0 - 1.0 = 2.0
    assert_eq!(top[1].0, 0); // Second: 2.0 - 1.0 = 1.0
}

// =========================================================================
// Additional coverage tests
// =========================================================================

#[test]
fn test_saliency_map_default() {
    let sm = SaliencyMap::default();
    assert!((sm.epsilon() - 1e-4).abs() < 1e-10);
}

#[test]
fn test_saliency_map_clone() {
    let sm = SaliencyMap::with_epsilon(1e-5);
    let cloned = sm.clone();
    assert_eq!(cloned.epsilon(), sm.epsilon());
}

#[test]
fn test_counterfactual_not_found() {
    // Impossible to change: model always returns 0
    let impossible_model = |_: &Vector<f32>| -> usize { 0 };

    let cf = CounterfactualExplainer::new(10, 0.1);
    let original = Vector::from_slice(&[1.0, 1.0]);

    let result = cf.find(&original, 1, impossible_model);
    assert!(result.is_none());
}

#[test]
fn test_permutation_importance_scores() {
    let importance = PermutationImportance {
        importance: Vector::from_slice(&[0.1, 0.2, 0.3]),
        baseline_score: 0.5,
    };

    // Test scores() getter
    assert_eq!(importance.scores().len(), 3);
    assert!((importance.baseline_score - 0.5).abs() < 1e-6);
}

#[test]
fn test_feature_contributions_bias() {
    let fc = FeatureContributions {
        contributions: Vector::from_slice(&[1.0, 2.0, 3.0]),
        bias: 1.0,
        prediction: 7.0,
    };
    assert_eq!(fc.contributions.len(), 3);
    assert_eq!(fc.prediction, 7.0);
    assert_eq!(fc.bias, 1.0);
}

#[test]
fn test_integrated_gradients_steps() {
    let ig = IntegratedGradients::new(100);
    assert_eq!(ig.n_steps, 100);
}

#[test]
fn test_shap_explainer_debug() {
    let background = vec![Vector::from_slice(&[1.0, 2.0, 3.0])];
    let explainer = ShapExplainer::new(&background, simple_linear_model);
    let debug_str = format!("{:?}", explainer);
    assert!(debug_str.contains("ShapExplainer"));
}

#[test]
fn test_integrated_gradients_debug() {
    let ig = IntegratedGradients::new(50);
    let debug_str = format!("{:?}", ig);
    assert!(debug_str.contains("IntegratedGradients"));
}

#[test]
fn test_lime_debug() {
    let lime = LIME::new(100, 0.5);
    let debug_str = format!("{:?}", lime);
    assert!(debug_str.contains("LIME"));
}

#[test]
fn test_saliency_map_debug() {
    let sm = SaliencyMap::new();
    let debug_str = format!("{:?}", sm);
    assert!(debug_str.contains("SaliencyMap"));
}

#[test]
fn test_counterfactual_explainer_debug() {
    let cf = CounterfactualExplainer::new(100, 0.01);
    let debug_str = format!("{:?}", cf);
    assert!(debug_str.contains("CounterfactualExplainer"));
}

#[test]
fn test_counterfactual_result_debug() {
    let result = CounterfactualResult {
        counterfactual: Vector::from_slice(&[1.0]),
        original: Vector::from_slice(&[0.0]),
        target_class: 1,
        distance: 1.0,
    };
    let debug_str = format!("{:?}", result);
    assert!(debug_str.contains("CounterfactualResult"));
}

#[path = "tests_explainers.rs"]
mod tests_explainers;