Skip to main content

dtrees_rs/algorithms/common/
errors.rs

1//! Error functions: the cost of a leaf and what it predicts.
2
3/// The error of a leaf.
4pub trait ErrorWrapper: Send + Sync {
5    /// `(error, prediction)` of a leaf, given its class counts or its instance
6    /// ids, depending on the search's configuration.
7    fn compute(&self, data: &[usize]) -> (f64, f64);
8}
9
10/// An error function backed by a plain Rust function.
11#[derive(Debug, Clone)]
12pub struct NativeError {
13    function: fn(&[usize]) -> (f64, f64),
14}
15
16impl NativeError {
17    /// Wraps `function`.
18    pub fn new(function: fn(&[usize]) -> (f64, f64)) -> Self {
19        NativeError { function }
20    }
21}
22
23impl Default for NativeError {
24    fn default() -> Self {
25        Self::new(classification_error)
26    }
27}
28
29impl ErrorWrapper for NativeError {
30    fn compute(&self, data: &[usize]) -> (f64, f64) {
31        (self.function)(data)
32    }
33}
34
35/// Misclassification error of a leaf predicting its majority class, and that
36/// class. Ties go to the highest class index. The default error function.
37pub fn classification_error(classes_support: &[usize]) -> (f64, f64) {
38    let mut max_idx = 0;
39    let mut max_value = 0;
40    let mut total = 0;
41    for (idx, value) in classes_support.iter().enumerate() {
42        total += value;
43        if *value >= max_value {
44            max_value = *value;
45            max_idx = idx;
46        }
47    }
48    let error = total - max_value;
49    (error as f64, max_idx as f64)
50}