miniboosts 0.3.6

MiniBoosts: A collection of boosting algorithms written in Rust 🦀
Documentation
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
//! Defines the inner representation 
//! of the Decision Tree class.

use rayon::prelude::*;

use serde::{Serialize, Deserialize};

use std::fmt;
use std::cmp::Ordering;
use std::ops::{Mul, Add};
use std::collections::{HashSet, HashMap};

use crate::Sample;
use super::bin::*;
use crate::weak_learner::common::{
    type_and_struct::*,
};



/// Score for a splitting.
/// This is just a wrapper for `f64`.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub(self) struct Score(f64);


impl From<f64> for Score {
    #[inline(always)]
    fn from(score: f64) -> Self {
        Self(score)
    }
}


impl PartialEq for Score {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.0.eq(&other.0)
    }
}


impl PartialOrd for Score {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.0.partial_cmp(&other.0)
    }
}


impl Mul for Score {
    type Output = Self;
    #[inline]
    fn mul(self, other: Self) -> Self::Output {
        Self(self.0 * other.0)
    }
}


impl Add for Score {
    type Output = Self;
    #[inline]
    fn add(self, other: Self) -> Self::Output {
        Self(self.0 + other.0)
    }
}


/// Splitting criteria for growing decision tree.
/// * `Criterion::Edge` maximizes the edge (weighted training accuracy)
///     for given distribution.
/// * `Criterion::Entropy` minimizes entropic impurity for given distribution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Criterion {
    /// Binary entropy function.
    Entropy,
    /// Weighted accuracy.
    /// This criterion is designed for binary classification problems.
    Edge,
    /// Gini index.
    Gini,
    /// Twoing rule.
    Twoing,
}


impl fmt::Display for Criterion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::Entropy => "Entropy",
            Self::Edge => "Edge (Weighted accuracy)",
            Self::Gini => "Gini index",
            Self::Twoing => "Twoing Rule",
        };

        write!(f, "{name}")
    }
}


impl Criterion {
    /// Returns the best splitting rule based on the criterion.
    pub(super) fn best_split<'a>(
        &self,
        bins_map: &HashMap<&'a str, Bins>,
        sample: &'a Sample,
        dist: &[f64],
        idx: &[usize],
    ) -> (&'a str, f64)
    {
        let target = sample.target();
        let target = &target[..];
        match self {
            Criterion::Entropy => {
                sample.features()
                    .par_iter()
                    .map(|feature| {
                        let name = feature.name();
                        let bin = bins_map.get(name).unwrap();
                        let pack = bin.pack(idx, feature, target, dist);
                        let (threshold, score) = split_by_entropy(pack);

                        (score, name, threshold)
                    })
                    .min_by(|x, y| x.0.partial_cmp(&y.0).unwrap())
                    .map(|(_, name, threshold)| (name, threshold))
                    .expect("No feature minimizes entropic impurity")
            },
            Criterion::Edge => {
                sample.features()
                    .par_iter()
                    .map(|feature| {
                        let name = feature.name();
                        let bin = bins_map.get(name).unwrap();
                        let pack = bin.pack(idx, feature, target, dist);
                        let (threshold, score) = split_by_edge(pack);

                        (score, name, threshold)
                    })
                    .max_by(|x, y| x.0.partial_cmp(&y.0).unwrap())
                    .map(|(_, name, threshold)| (name, threshold))
                    .expect("No feature maximizes edge")
            },
            Criterion::Gini => {
                sample.features()
                    .par_iter()
                    .map(|feature| {
                        let name = feature.name();
                        let bin = bins_map.get(name).unwrap();
                        let pack = bin.pack(idx, feature, target, dist);
                        let (threshold, score) = split_by_gini(pack);

                        (score, name, threshold)
                    })
                    .min_by(|x, y| x.0.partial_cmp(&y.0).unwrap())
                    .map(|(_, name, threshold)| (name, threshold))
                    .expect("No feature minimizes Gini impurity")
            },
            Criterion::Twoing => {
                sample.features()
                    .par_iter()
                    .map(|feature| {
                        let name = feature.name();
                        let bin = bins_map.get(name).unwrap();
                        let pack = bin.pack(idx, feature, target, dist);
                        let (threshold, score) = split_by_twoing(pack);

                        (score, name, threshold)
                    })
                    .max_by(|x, y| x.0.partial_cmp(&y.0).unwrap())
                    .map(|(_, name, threshold)| (name, threshold))
                    .expect("No feature maximizes Twoing rule")
            },
        }
    }
}


fn split_by_entropy(pack: Vec<(Bin, LabelToWeight)>)
    -> (f64, Score)
{
    let weight_sum = pack.iter()
        .map(|(_, mp)| mp.values().sum::<f64>())
        .sum::<f64>();


    let mut left_weight = LabelToWeight::new();
    let mut left_weight_sum = 0.0;
    let mut right_weight = LabelToWeight::new();
    let mut right_weight_sum = 0.0;

    for (_, mp) in pack.iter() {
        for (y, w) in mp.iter() {
            let entry = right_weight.entry(*y).or_insert(0.0);
            *entry += w;
            right_weight_sum += w;
        }
    }

    let mut best_score = entropic_impurity(&right_weight);
    let mut best_threshold = f64::MIN;

    for (bin, map) in pack {
        for (y, w) in map {
            let entry = left_weight.entry(y).or_insert(0.0);
            *entry += w;
            left_weight_sum += w;
            let entry = right_weight.get_mut(&y).unwrap();
            *entry -= w;
            right_weight_sum -= w;
        }
        let lp = left_weight_sum / weight_sum;
        let rp = (1.0 - lp).max(0.0);

        let left_impurity = entropic_impurity(&left_weight);
        let right_impurity = entropic_impurity(&right_weight);
        let score = lp * left_impurity + rp * right_impurity;


        if score < best_score {
            best_score = score;
            best_threshold = bin.0.end;
        }
    }
    let best_score = Score::from(best_score);
    (best_threshold, best_score)
}


fn split_by_edge(pack: Vec<(Bin, LabelToWeight)>) -> (f64, Score) {
    // Compute the edge of the hypothesis that predicts `+1`
    // for all instances.
    let mut edge = pack.iter()
        .map(|(_, map)| {
            map.iter()
                .map(|(y, d)| *y as f64 * d)
                .sum::<f64>()
        })
        .sum::<f64>();

    let mut best_edge = edge.abs();
    let mut best_threshold = f64::MIN;


    for (bin, map) in pack {
        edge -= 2.0 * map.into_iter()
            .map(|(y, d)| y as f64 * d)
            .sum::<f64>();


        if best_edge < edge.abs() {
            best_edge = edge.abs();
            best_threshold = bin.0.end;
        }
    }
    let best_edge = Score::from(best_edge);
    (best_threshold, best_edge)
}


fn split_by_gini(pack: Vec<(Bin, LabelToWeight)>) -> (f64, Score) {
    let weight_sum = pack.iter()
        .map(|(_, mp)| mp.values().sum::<f64>())
        .sum::<f64>();


    let mut left_weight = LabelToWeight::new();
    let mut left_weight_sum = 0.0;
    let mut right_weight = LabelToWeight::new();
    let mut right_weight_sum = 0.0;

    for (_, mp) in pack.iter() {
        for (y, w) in mp.iter() {
            let entry = right_weight.entry(*y).or_insert(0.0);
            *entry += w;
            right_weight_sum += w;
        }
    }

    let mut best_score = gini_impurity(&right_weight);
    let mut best_threshold = f64::MIN;

    for (bin, map) in pack {
        for (y, w) in map {
            let entry = left_weight.entry(y).or_insert(0.0);
            *entry += w;
            left_weight_sum += w;
            let entry = right_weight.get_mut(&y).unwrap();
            *entry -= w;
            right_weight_sum -= w;


            if *entry <= 0.0 { right_weight.remove(&y); }
        }
        let lp = left_weight_sum / weight_sum;
        let rp = (1.0 - lp).max(0.0);

        let left_impurity = gini_impurity(&left_weight);
        let right_impurity = gini_impurity(&right_weight);
        let score = lp * left_impurity + rp * right_impurity;


        if score < best_score {
            best_score = score;
            best_threshold = bin.0.end;
        }
    }
    let best_score = Score::from(best_score);
    (best_threshold, best_score)
}


fn split_by_twoing(pack: Vec<(Bin, LabelToWeight)>) -> (f64, Score) {
    let mut left_weight = LabelToWeight::new();
    let mut right_weight = LabelToWeight::new();

    let mut labels = HashSet::new();
    for (_, mp) in pack.iter() {
        for (y, w) in mp.iter() {
            let entry = right_weight.entry(*y).or_insert(0.0);
            *entry += w;

            labels.insert(*y);
        }
    }

    let mut best_score = 0.0;
    let mut best_threshold = f64::MIN;

    for (bin, map) in pack {
        // Move the weights in a `pack` from right to left.
        for (y, w) in map {
            let entry = left_weight.entry(y).or_insert(0.0);
            *entry += w;
            if let Some(entry) = right_weight.get_mut(&y) {
                *entry -= w;
            }

            if *entry <= 0.0 { right_weight.remove(&y); }
        }


        let score = twoing_score(&labels, &left_weight, &right_weight);


        if score > best_score {
            best_score = score;
            best_threshold = bin.0.end;
        }
    }
    let best_score = Score::from(best_score);
    (best_threshold, best_score)
}


/// Returns the entropic-impurity of the given map.
#[inline(always)]
pub(self) fn entropic_impurity(map: &HashMap<i32, f64>) -> f64 {
    let total = map.values().sum::<f64>();
    if total <= 0.0 || map.is_empty() { return 0.0.into(); }

    map.par_iter()
        .map(|(_, &p)| {
            let r = p / total;
            if r <= 0.0 { 0.0 } else { -r * r.ln() }
        })
        .sum::<f64>()
}


/// Returns the gini-impurity of the given map.
#[inline(always)]
pub(self) fn gini_impurity(map: &HashMap<i32, f64>) -> f64 {
    let total = map.values().sum::<f64>();
    if total <= 0.0 || map.is_empty() { return 0.0.into(); }

    let correct = map.par_iter()
        .map(|(_, &w)| (w / total).powi(2))
        .sum::<f64>();

    (1.0 - correct).max(0.0)
}


/// Returns the gini-impurity of the given map.
#[inline(always)]
pub(self) fn twoing_score(
    labels: &HashSet<i32>,
    left: &HashMap<i32, f64>,
    right: &HashMap<i32, f64>,
) -> f64
{
    let pl = left.values().sum::<f64>();
    let pr = right.values().sum::<f64>();
    let pt = pl + pr;

    if pl == 0.0 || pr == 0.0 { return 0.0; }
    assert!(pt > 0.0);

    let mut score = 0.0;
    for y in labels {
        let l = left.get(y).unwrap_or(&0.0);
        let r = right.get(y).unwrap_or(&0.0);

        score += ((l / pl) - (r / pr)).abs();
    }
    score = score.powi(2) * pl * pr / (2.0 * pt).powi(2);

    score
}