| 19 | //! feature, columns in the order of `feature_names`. Labels are `0.0`/`1.0`. |
| 20 | //! - `splits` are `(train_indices, test_indices)` pairs into the rows, typically from |
| 21 | //! [`crate::cross_validation::PurgedKFold`]. |
| 22 | //! - Results map feature name to [`ImportanceStats`], whose `std` is the **standard error of |
| 23 | //! the mean**, not a standard deviation: MDI and MDA divide the sample deviation (ddof 1) by |
| 24 | //! `sqrt(n)`, SFI the population deviation (ddof 0). A standard error from one fold or tree is |
| 25 | //! 0, not `NaN`. |
| 26 | //! - Each method is fooled differently: MDI gives noise features a share, MDA lets correlated |
| 27 | //! features hide each other (substitution), SFI misses features that matter only jointly. |
| 28 | //! |
| 29 | //! ``` |
| 30 | //! use openquant::feature_importance::{mean_decrease_impurity, FeatureImportanceError}; |
| 31 | //! |
| 32 | //! # fn main() -> Result<(), FeatureImportanceError> { |
| 33 | //! let per_tree = vec![vec![0.6, 0.3, 0.1], vec![0.5, 0.3, 0.2], vec![0.7, 0.2, 0.1]]; |
| 34 | //! let names: Vec<String> = ["f0", "f1", "f2"].map(String::from).to_vec(); |
| 35 | //! let mdi = mean_decrease_impurity(&per_tree, &names)?; |
| 36 | //! // Means 0.6, 0.267, 0.133 already sum to 1. |
| 37 | //! assert!((mdi["f0"].mean - 0.6).abs() < 1e-12); |
| 38 | //! // Sample deviation of (0.6, 0.5, 0.7) is 0.1; its standard error over 3 trees is 0.1 / sqrt(3). |
| 39 | //! assert!((mdi["f0"].std - 0.1 / 3f64.sqrt()).abs() < 1e-12); |
| 40 | //! # Ok(()) |
| 41 | //! # } |
| 42 | //! ``` |
| 43 | |
| 44 | use std::collections::BTreeMap; |
| 45 | |
| 46 | use crate::util::stats; |
| 47 | use nalgebra::{DMatrix, SymmetricEigen}; |
| 48 | use rand::rngs::StdRng; |
| 49 | use rand::seq::SliceRandom; |
| 50 | use rand::SeedableRng; |
| 51 | |
| 52 | use crate::cross_validation::{ |
| 53 | check_prediction_count, check_score_inputs, ml_cross_val_score, CrossValidationError, Scoring, |
| 54 | SimpleClassifier, |
| 55 | }; |
| 56 | |
| 57 | /// Errors returned by the feature-importance functions. |
| 58 | #[derive(Debug, Clone, PartialEq, thiserror::Error)] |
| 59 | pub enum FeatureImportanceError { |