@@ -79,11 +79,12 @@ use serde::{Deserialize, Serialize};
7979
8080use crate :: api:: { Predictor , SupervisedEstimator } ;
8181use crate :: ensemble:: base_forest:: {
82- BaseForest , BaseForestParameters , predict_mode, predict_mode_oob,
82+ BaseForest , BaseForestParameters , predict_mode, predict_mode_oob, predict_proba ,
8383} ;
8484use crate :: ensemble:: max_features:: MaxFeatures ;
8585use crate :: error:: Failed ;
8686use crate :: linalg:: basic:: arrays:: { Array1 , Array2 } ;
87+ use crate :: linalg:: basic:: matrix:: DenseMatrix ;
8788use crate :: numbers:: basenum:: Number ;
8889use crate :: numbers:: floatnum:: FloatNumber ;
8990
@@ -396,6 +397,72 @@ impl<TX: FloatNumber + PartialOrd, TY: Number + Ord, X: Array2<TX>, Y: Array1<TY
396397 }
397398 }
398399
400+ /// Predict the class probabilities for each row of `x`.
401+ ///
402+ /// The probability of a class is the mean, over all trees, of the class
403+ /// distribution in the leaf that the row reaches. The class distribution
404+ /// of a leaf is the weighted fraction of training samples of each class
405+ /// in that leaf.
406+ ///
407+ /// # Arguments
408+ ///
409+ /// * `x` - The input samples as a matrix where each row is a sample and each column is a feature.
410+ ///
411+ /// # Returns
412+ ///
413+ /// A `Result` containing a `DenseMatrix<f64>` where each row corresponds to a sample and each
414+ /// column corresponds to a class. The columns are in the order of the sorted classes. The values
415+ /// of each row add up to 1 within f32 precision.
416+ ///
417+ /// # Errors
418+ ///
419+ /// Returns an error if `fit` was not called before this method.
420+ ///
421+ /// ```
422+ /// use smartcore::ensemble::extra_trees_classifier::*;
423+ /// use smartcore::linalg::basic::arrays::Array;
424+ /// use smartcore::linalg::basic::matrix::DenseMatrix;
425+ ///
426+ /// // Column 0 sets the class: rows 0-9 are class 1, rows 10-19 are class 3
427+ /// // and rows 20-29 are class 7. Column 1 is noise.
428+ /// let rows: Vec<Vec<f64>> = (0..30)
429+ /// .map(|i| vec![i as f64, ((i * 7) % 30) as f64])
430+ /// .collect();
431+ /// let x = DenseMatrix::from_2d_vec(&rows).unwrap();
432+ /// let y: Vec<u32> = (0..30)
433+ /// .map(|i| match i / 10 {
434+ /// 0 => 1,
435+ /// 1 => 3,
436+ /// _ => 7,
437+ /// })
438+ /// .collect();
439+ /// let parameters = ExtraTreesClassifierParameters::default()
440+ /// .with_n_trees(20)
441+ /// .with_seed(42);
442+ /// let forest = ExtraTreesClassifier::fit(&x, &y, parameters).unwrap();
443+ ///
444+ /// let x_new = DenseMatrix::from_2d_array(&[&[2.0, 5.0], &[25.0, 5.0]]).unwrap();
445+ /// let proba = forest.predict_proba(&x_new).unwrap();
446+ ///
447+ /// // One row for each sample and one column for each class, in the order 1, 3, 7.
448+ /// assert_eq!(proba.shape(), (2, 3));
449+ /// for i in 0..2 {
450+ /// let sum: f64 = (0..3).map(|j| *proba.get((i, j))).sum();
451+ /// assert!((sum - 1.0).abs() < 1e-6);
452+ /// }
453+ /// // The first sample is most probably class 1, the second sample class 7.
454+ /// assert!(*proba.get((0, 0)) > 0.5);
455+ /// assert!(*proba.get((1, 2)) > 0.5);
456+ /// ```
457+ pub fn predict_proba ( & self , x : & X ) -> Result < DenseMatrix < f64 > , Failed > {
458+ match ( & self . forest_classifier , & self . classes ) {
459+ ( Some ( forest) , Some ( classes) ) => predict_proba ( forest, x, classes. len ( ) ) ,
460+ _ => Err ( Failed :: predict (
461+ "'fit' should be called before calling 'predict_proba'" ,
462+ ) ) ,
463+ }
464+ }
465+
399466 /// Compute the impurity-based feature importances for this forest.
400467 /// * returns: a vector where index `j` gives the importance of feature `j`.
401468 /// The importances are normalized: they add up to 1 when the trees contain at least one split.
@@ -893,4 +960,147 @@ mod tests {
893960 assert ! ( !params. bootstrap) ;
894961 assert ! ( !params. keep_samples) ;
895962 }
963+
964+ #[ cfg_attr(
965+ all( target_arch = "wasm32" , not( target_os = "wasi" ) ) ,
966+ wasm_bindgen_test:: wasm_bindgen_test
967+ ) ]
968+ #[ test]
969+ fn predict_proba_recovers_known_probability ( ) {
970+ use crate :: rand_custom:: get_rng_impl;
971+ use rand:: RngExt ;
972+
973+ // True model: P(y = 1 | x) = sigmoid(x0 + x1^2 - 2), x ~ U[-3, 3]^2.
974+ fn true_p ( x0 : f64 , x1 : f64 ) -> f64 {
975+ 1.0 / ( 1.0 + ( -( x0 + x1 * x1 - 2.0 ) ) . exp ( ) )
976+ }
977+
978+ // Draws n rows. Returns the features, the labels and the true probabilities.
979+ fn sample ( n : usize , seed : u64 ) -> ( DenseMatrix < f64 > , Vec < u32 > , Vec < f64 > ) {
980+ let mut rng = get_rng_impl ( Some ( seed) ) ;
981+ let mut values = Vec :: with_capacity ( 2 * n) ;
982+ let mut y = Vec :: with_capacity ( n) ;
983+ let mut p = Vec :: with_capacity ( n) ;
984+ for _ in 0 ..n {
985+ let x0: f64 = rng. random_range ( -3.0 ..3.0 ) ;
986+ let x1: f64 = rng. random_range ( -3.0 ..3.0 ) ;
987+ let pi = true_p ( x0, x1) ;
988+ values. push ( x0) ;
989+ values. push ( x1) ;
990+ y. push ( u32:: from ( rng. random :: < f64 > ( ) < pi) ) ;
991+ p. push ( pi) ;
992+ }
993+ ( DenseMatrix :: new ( n, 2 , values, false ) . unwrap ( ) , y, p)
994+ }
995+
996+ let ( x_train, y_train, _) = sample ( 2000 , 1 ) ;
997+ let ( x_test, _, p_test) = sample ( 500 , 2 ) ;
998+
999+ let params = ExtraTreesClassifierParameters :: default ( )
1000+ . with_n_trees ( 100 )
1001+ . with_min_samples_leaf ( 5 )
1002+ . with_seed ( 42 ) ;
1003+ let forest = ExtraTreesClassifier :: fit ( & x_train, & y_train, params) . unwrap ( ) ;
1004+ let proba = forest. predict_proba ( & x_test) . unwrap ( ) ;
1005+
1006+ // Each row is a probability distribution.
1007+ let tol = 2.0 * f32:: EPSILON as f64 ; // ≈ 2.4e-7, two classes
1008+ for i in 0 ..p_test. len ( ) {
1009+ assert ! ( * proba. get( ( i, 0 ) ) >= 0.0 ) ;
1010+ assert ! ( * proba. get( ( i, 1 ) ) >= 0.0 ) ;
1011+ let s = * proba. get ( ( i, 0 ) ) + * proba. get ( ( i, 1 ) ) ;
1012+ assert ! ( ( s - 1.0 ) . abs( ) < tol, "s should be close to one but is {s}" ) ;
1013+ }
1014+
1015+ // Labels are {0, 1} and sorted, so column 1 is P(y = 1).
1016+ let mae: f64 = p_test
1017+ . iter ( )
1018+ . enumerate ( )
1019+ . map ( |( i, p) | ( proba. get ( ( i, 1 ) ) - p) . abs ( ) )
1020+ . sum :: < f64 > ( )
1021+ / p_test. len ( ) as f64 ;
1022+
1023+ // Baseline: always predict the base rate of the training labels.
1024+ let base_rate = y_train. iter ( ) . sum :: < u32 > ( ) as f64 / y_train. len ( ) as f64 ;
1025+ let baseline_mae: f64 =
1026+ p_test. iter ( ) . map ( |p| ( base_rate - p) . abs ( ) ) . sum :: < f64 > ( ) / p_test. len ( ) as f64 ;
1027+
1028+ assert ! (
1029+ mae < 0.5 * baseline_mae,
1030+ "forest MAE {mae:.3} vs base-rate MAE {baseline_mae:.3}"
1031+ ) ;
1032+ }
1033+
1034+ #[ cfg_attr(
1035+ all( target_arch = "wasm32" , not( target_os = "wasi" ) ) ,
1036+ wasm_bindgen_test:: wasm_bindgen_test
1037+ ) ]
1038+ #[ test]
1039+ fn predict_proba_without_fit_should_not_panic ( ) {
1040+ let tree: ExtraTreesClassifier < f64 , u32 , DenseMatrix < f64 > , Vec < u32 > > =
1041+ ExtraTreesClassifier :: new ( ) ;
1042+ let x = DenseMatrix :: from_2d_array ( & [ & [ 1.0f64 ] ] ) . expect ( "Construction of x should work" ) ;
1043+ let predicted_probas = tree. predict_proba ( & x) ;
1044+ assert ! ( predicted_probas. is_err( ) ) ;
1045+ let msg = "'fit' should be called before calling 'predict_proba'" ;
1046+ assert_eq ! ( predicted_probas. err( ) , Some ( Failed :: predict( msg) ) ) ;
1047+ }
1048+
1049+ fn iris_with_unsorted_labels ( ) -> ( DenseMatrix < f64 > , Vec < i32 > ) {
1050+ let ( x, y) = iris ( ) ;
1051+ let y = y. iter ( ) . map ( |c| if * c == 0 { 12 } else { -7 } ) . collect ( ) ;
1052+ ( x, y)
1053+ }
1054+
1055+ #[ cfg_attr(
1056+ all( target_arch = "wasm32" , not( target_os = "wasi" ) ) ,
1057+ wasm_bindgen_test:: wasm_bindgen_test
1058+ ) ]
1059+ #[ test]
1060+ fn predict_proba_with_one_tree_equals_leaf_distributions ( ) {
1061+ let ( x, y) = iris_with_unsorted_labels ( ) ;
1062+ let parameters = ExtraTreesClassifierParameters :: default ( )
1063+ . with_n_trees ( 1 )
1064+ . with_min_samples_leaf ( 3 )
1065+ . with_seed ( 42 ) ;
1066+ let classifier = ExtraTreesClassifier :: fit ( & x, & y, parameters) . unwrap ( ) ;
1067+ let proba = classifier. predict_proba ( & x) . unwrap ( ) ;
1068+ assert_eq ! ( proba. shape( ) , ( 20 , 2 ) ) ;
1069+
1070+ let tree = & classifier. forest_classifier . as_ref ( ) . unwrap ( ) . trees ( ) [ 0 ] ;
1071+ for i in 0 ..20 {
1072+ let leaf = tree. leaf_distribution_for_row ( & x, i, 2 ) ;
1073+ for ( j, p) in leaf. iter ( ) . enumerate ( ) {
1074+ assert_eq ! ( * proba. get( ( i, j) ) , * p as f64 , "row {i}, column {j}" ) ;
1075+ }
1076+ }
1077+ }
1078+
1079+ #[ cfg_attr(
1080+ all( target_arch = "wasm32" , not( target_os = "wasi" ) ) ,
1081+ wasm_bindgen_test:: wasm_bindgen_test
1082+ ) ]
1083+ #[ test]
1084+ fn predict_proba_with_stumps_gives_weighted_class_fractions ( ) {
1085+ let ( x, y) = iris_with_unsorted_labels ( ) ;
1086+ let weights: Vec < f64 > = y. iter ( ) . map ( |c| if * c == 12 { 3.0 } else { 1.0 } ) . collect ( ) ;
1087+ let parameters = ExtraTreesClassifierParameters :: default ( )
1088+ . with_max_depth ( 1 )
1089+ . with_n_trees ( 3 )
1090+ . with_seed ( 42 ) ;
1091+ let classifier =
1092+ ExtraTreesClassifier :: fit_with_weights ( & x, & y, & weights, parameters) . unwrap ( ) ;
1093+ let proba = classifier. predict_proba ( & x) . unwrap ( ) ;
1094+ assert_eq ! ( proba. shape( ) , ( 20 , 2 ) ) ;
1095+
1096+ for i in 0 ..20 {
1097+ for ( j, expected) in [ 0.25 , 0.75 ] . iter ( ) . enumerate ( ) {
1098+ let p = * proba. get ( ( i, j) ) ;
1099+ assert ! (
1100+ ( p - expected) . abs( ) < 1e-6 ,
1101+ "row {i}, column {j}: {p} is not {expected}"
1102+ ) ;
1103+ }
1104+ }
1105+ }
8961106}
0 commit comments