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
//! Merge models with binary to multi-class classification
//!
use crate::dataset::{Pr, Records};
use crate::traits::PredictInplace;
use ndarray::{Array1, ArrayBase, Data, Ix2};
use std::iter::FromIterator;

type MultiClassVec<R, L> = Vec<(L, Box<dyn PredictInplace<R, Array1<Pr>>>)>;

/// Merge models with binary to multi-class classification
pub struct MultiClassModel<R: Records, L> {
    models: MultiClassVec<R, L>,
}

impl<R: Records, L> MultiClassModel<R, L> {
    pub fn new(models: MultiClassVec<R, L>) -> Self {
        MultiClassModel { models }
    }
}

impl<L: Clone + Default, F, D: Data<Elem = F>> PredictInplace<ArrayBase<D, Ix2>, Array1<L>>
    for MultiClassModel<ArrayBase<D, Ix2>, L>
{
    fn predict_inplace(&self, arr: &ArrayBase<D, Ix2>, y: &mut Array1<L>) {
        assert_eq!(
            arr.nrows(),
            y.len(),
            "The number of data points must match the number of output targets."
        );

        let mut res = Vec::new();

        for pairs in self.models.iter().map(|(elm, model)| {
            let mut targets = Array1::default(arr.nrows());
            model.predict_inplace(arr, &mut targets);

            targets.into_iter().map(|x| (elm.clone(), *x)).collect()
        }) {
            // initialize result with guess of first model
            if res.is_empty() {
                res = pairs;
                continue;
            }

            // compare probability to each subsequent model and replace label
            // if probability is higher
            res = res
                .into_iter()
                .zip(pairs.into_iter())
                .map(|(c, d)| if d.1 > c.1 { d } else { c })
                .collect();
        }

        // remove probabilities from array and convert to `Array1`
        for (r, target) in res.into_iter().zip(y.iter_mut()) {
            *target = r.0;
        }
    }

    fn default_target(&self, x: &ArrayBase<D, Ix2>) -> Array1<L> {
        Array1::default(x.nrows())
    }
}

impl<F, D: Data<Elem = F>, L, P: PredictInplace<ArrayBase<D, Ix2>, Array1<Pr>> + 'static>
    FromIterator<(L, P)> for MultiClassModel<ArrayBase<D, Ix2>, L>
{
    fn from_iter<I: IntoIterator<Item = (L, P)>>(iter: I) -> Self {
        let models = iter
            .into_iter()
            .map(|(l, x)| {
                (
                    l,
                    Box::new(x) as Box<dyn PredictInplace<ArrayBase<D, Ix2>, Array1<Pr>>>,
                )
            })
            .collect();

        MultiClassModel { models }
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        dataset::Pr,
        traits::{Predict, PredictInplace},
        MultiClassModel,
    };
    use ndarray::{array, Array1, Array2};

    /// First dummy model, returns probability 1 for odd items
    struct DummyModel {
        on_even: bool,
    }

    impl PredictInplace<Array2<f32>, Array1<Pr>> for DummyModel {
        fn predict_inplace(&self, arr: &Array2<f32>, targets: &mut Array1<Pr>) {
            assert_eq!(
                arr.nrows(),
                targets.len(),
                "The number of data points must match the number of output targets."
            );

            if !self.on_even {
                *targets = Array1::from_shape_fn(arr.nrows(), |x| {
                    if x % 2 == 1 {
                        Pr::new(1.0)
                    } else {
                        Pr::new(0.0)
                    }
                });
            } else {
                *targets = Array1::from_shape_fn(arr.nrows(), |x| {
                    if x % 2 == 1 {
                        Pr::new(0.0)
                    } else {
                        Pr::new(1.0)
                    }
                });
            }
        }

        fn default_target(&self, x: &Array2<f32>) -> Array1<Pr> {
            Array1::default(x.nrows())
        }
    }

    #[test]
    fn correct_dummies() {
        let model1 = DummyModel { on_even: false };
        let model2 = DummyModel { on_even: true };

        let data = Array2::zeros((4, 2));
        assert_eq!(
            model1.predict(&data),
            array![0.0, 1.0, 0.0, 1.0].mapv(Pr::new)
        );
        assert_eq!(
            model2.predict(&data),
            array![1.0, 0.0, 1.0, 0.0].mapv(Pr::new)
        );
    }

    #[test]
    fn choose_correct() {
        let model = vec![
            (0, DummyModel { on_even: false }),
            (1, DummyModel { on_even: true }),
        ]
        .into_iter()
        .collect::<MultiClassModel<_, usize>>();

        let data = Array2::zeros((4, 2));
        assert_eq!(model.predict(&data), array![1, 0, 1, 0]);
    }
}