miniboosts 0.4.0

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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! This file defines some options of MLPBoost.

use crate::{
    Sample,
    Classifier,
    common::{utils, checker},
};

use std::fmt;


const SUB_TOLERANCE: f64 = 1e-9;


/// FWType updates.
/// These options correspond to the Frank-Wolfe strategies.
#[derive(Clone, Copy)]
pub enum FWType {
    /// Classic step size, `2 / (t + 2)`.
    Classic,

    /// Short-step size,
    /// Adopt the step size that minimizes the strongly-smooth bound.
    ShortStep,

    /// Line-search step size,
    /// Adopt the best step size on the descent direction.
    LineSearch,

    /// The Blended-Pairwise strategy, 
    /// See [this paper](https://proceedings.mlr.press/v162/tsuji22a). 
    BlendedPairwise,
}


impl fmt::Display for FWType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let fw = match self {
            Self::Classic => "Classic FW",
            Self::ShortStep => "Short-step FW",
            Self::LineSearch => "Line-search FW",
            Self::BlendedPairwise => "Blended Pairwise (BP) FW",
        };
        write!(f, "{fw}")
    }
}


pub(crate) struct FrankWolfe {
    eta: f64, // Strongly-smooth parameter
    nu: f64,
    fw_type: FWType,
}


impl FrankWolfe {
    /// Create a new FrankWolfe instance
    pub(crate) fn new(eta: f64, nu: f64, fw_type: FWType) -> Self {
        Self { eta, nu, fw_type, }
    }


    /// Set `self.eta`.
    pub(crate) fn eta(&mut self, eta: f64) {
        self.eta = eta;
    }


    /// Set `nu`.
    pub(crate) fn nu(&mut self, nu: f64) {
        self.nu = nu;
    }


    /// Get the current Frank-Wolfe strategy.
    pub(crate) fn current_type(&self) -> FWType {
        self.fw_type
    }


    /// Update the Frank-Wolfe type.
    /// Currently, you can choose types from below:
    /// - Classic. `1.0 / t + 1.0` for `t >= 1`.
    /// - ShortStep. The step size that minimizes the strongly-smooth bound.
    /// - LineSearch. Optimal step size that minimizes the objective.
    /// - Pairwise. Pairwise update.
    pub(crate) fn fw_type(&mut self, fw_type: FWType) {
        self.fw_type = fw_type;
    }


    /// Returns the next weights on hypotheses
    pub(crate) fn next_iterate<H>(
        &self,
        iteration: usize,
        sample: &Sample,
        dist: &[f64],
        hypotheses: &[H],
        position_of_new_one: usize,
        weights: Vec<f64>,
    ) -> Vec<f64>
        where H: Classifier,
    {
        let n_hypotheses = hypotheses.len();
        assert!((0..n_hypotheses).contains(&position_of_new_one));
        match self.fw_type {
            FWType::Classic
                => self.classic(iteration, position_of_new_one, weights),
            FWType::ShortStep
                => self.short_step(
                    sample, dist, hypotheses, position_of_new_one, weights,
                ),
            FWType::LineSearch
                => self.line_search(
                    sample, hypotheses, position_of_new_one, weights,
                ),
            FWType::BlendedPairwise
                => self.blended_pairwise(
                    sample, dist, hypotheses, position_of_new_one, weights,
                ),
        }
    }


    fn classic(
        &self,
        iteration: usize,
        position_of_new_one: usize,
        weights: Vec<f64>,
    ) -> Vec<f64>
    {
        // Compute the step-size
        let step_size = 2.0_f64 / ((iteration + 1) as f64);

        // Update the weights
        interior_point(step_size, position_of_new_one, weights)
    }


    fn short_step<H>(
        &self,
        sample: &Sample,
        dist: &[f64],
        hypotheses: &[H],
        position_of_new_one: usize,
        weights: Vec<f64>,
    ) -> Vec<f64>
        where H: Classifier,
    {
        if hypotheses.len() == 1 { return vec![1.0]; }


        let h = &hypotheses[position_of_new_one];


        let old_margins = utils::margins_of_weighted_hypothesis(
            sample, &weights[..], hypotheses,
        );
        let new_margins = utils::margins_of_hypothesis(sample, h);


        // Compute the step size `= numer / denom`, where
        // `numer = d^T A (e_h - w)` and
        // `denom = ‖ A (e_h - w) ‖_∞`.
        // See the paper by Shalev-Shwartz, [COLT '08].
        let mut numer: f64 = 0.0;
        let mut denom: f64 = f64::MIN;
        new_margins.into_iter()
            .zip(old_margins)
            .zip(dist)
            .for_each(|((ae, aw), &d)| {
                let diff = ae - aw;
                numer += d * diff;
                denom = denom.max(diff.abs());
            });
        let step = numer / (self.eta * denom.powi(2));

        // Clip the step size to `[0, 1]`.
        let step_size = step.clamp(0f64, 1f64);


        // Update the weights
        interior_point(step_size, position_of_new_one, weights)
    }


    fn line_search<H>(
        &self,
        sample: &Sample,
        hypotheses: &[H],
        position_of_new_one: usize,
        mut weights: Vec<f64>,
    ) -> Vec<f64>
        where H: Classifier,
    {
        // base: w
        // dir:  e_h - w
        let base = weights.clone();
        let dir  = weights.iter()
            .copied()
            .enumerate()
            .map(|(j, w)|
                if j == position_of_new_one { 1.0 - w } else { -w }
            )
            .collect::<Vec<_>>();

        // A(e_h - w)
        let dir_margins = utils::margins_of_weighted_hypothesis(
            sample, &dir[..], hypotheses,
        );
        // Aw
        let base_margins = utils::margins_of_weighted_hypothesis(
            sample, &base[..], hypotheses,
        );


        // Check the case where the step size is `1`.
        let dist = utils::exp_distribution(
            self.eta, self.nu, sample, &dir[..], hypotheses,
        );


        // `dot` is `d * A (e_h - w)`
        let dot = utils::inner_product(&dist[..], &dir_margins[..]);


        if dot <= 0.0 {
            let n_weights = weights.len();
            weights = vec![0.0; n_weights];
            weights[position_of_new_one] = 1.0;
            return weights;
        }



        let mut ub = 1.0;
        let mut lb = 0.0;
        while ub - lb > SUB_TOLERANCE {
            let step_size = (lb + ub) / 2.0;

            let margins = base_margins.iter()
                .zip(&dir_margins[..])
                .map(|(&b, &d)| b + step_size * d);
            let dist = utils::exp_distribution_from_margins(
                self.eta, self.nu, margins,
            );


            // Compute the gradient for the direction `dir`.
            let dot = utils::inner_product(&dist[..], &dir_margins[..]);

            if dot < 0.0 {
                lb = step_size;
            } else if dot > 0.0 {
                ub = step_size;
            } else {
                break;
            }
        }

        // Update the weights
        let step_size = (lb + ub) / 2.0;


        interior_point(step_size, position_of_new_one, base)
    }


    fn blended_pairwise<H>(
        &self,
        sample: &Sample,
        dist: &[f64],
        hypotheses: &[H],
        position_of_new_one: usize,
        mut weights: Vec<f64>,
    ) -> Vec<f64>
        where H: Classifier,
    {
        // Find a hypothesis that has a smallest edge.
        let mut worst_edge = 2.0;
        let mut local_best_edge = -2.0;
        let mut global_best_edge = -2.0;
        let mut position_of_worst_one = hypotheses.len();
        let mut position_of_local_best_one = hypotheses.len();
        let mut position_of_global_best_one = position_of_new_one;
        weights.iter()
            .zip(hypotheses)
            .enumerate()
            .filter_map(|(j, (w, h))| {
                if *w <= 0.0 {
                    None
                } else {
                    let edge = utils::edge_of_hypothesis(sample, dist, h);
                    Some((j, edge))
                }
            })
            .for_each(|(j, edge)| {
                if j != position_of_new_one && edge > local_best_edge {
                    local_best_edge = edge;
                    position_of_local_best_one = j;
                }

                if edge > global_best_edge {
                    global_best_edge = edge;
                    position_of_global_best_one = j;
                }


                if edge < worst_edge {
                    worst_edge = edge;
                    position_of_worst_one = j;
                }
            });

        // If the following condition holds,
        // the global FW atom is not the newly attained one
        // so that the local one is the same as the global one.
        if position_of_global_best_one + 1 != hypotheses.len() {
            local_best_edge = global_best_edge;
            position_of_local_best_one = position_of_global_best_one;
        }

        let current_edge = utils::edge_of_weighted_hypothesis(
            sample, dist, &weights[..], hypotheses
        );

        let lhs = local_best_edge - worst_edge;
        let rhs = global_best_edge - current_edge;
        if lhs >= rhs {
            // Pairwise update!
            let max_stepsize = weights[position_of_worst_one];

            // Find the best stepsize by line-search
            let local_best_margins = utils::margins_of_hypothesis(
                sample, &hypotheses[position_of_local_best_one]
            );
            let worst_margins = utils::margins_of_hypothesis(
                sample, &hypotheses[position_of_worst_one]
            );

            let dir_margins = local_best_margins.into_iter()
                .zip(worst_margins)
                .map(|(a, b)| a - b)
                .collect::<Vec<_>>();


            // You don't need to remove the newly attaind hypothesis
            // since the weight of new one is assigned as 0 at this point.
            let base_margins = utils::margins_of_weighted_hypothesis(
                sample, &weights[..], hypotheses,
            );


            let margins = dir_margins.iter()
                .zip(base_margins.iter())
                .map(|(dir, cur)| cur + max_stepsize * dir)
                .collect::<Vec<_>>();


            let dist = utils::exp_distribution(
                self.eta, self.nu, sample, &margins[..], hypotheses,
            );


            // If the max step size is the best one,
            // 1. Set 0 weight on `position_of_worst_one`,
            // 2. Set `max_stepsize` on `position_of_local_best_one`.
            if utils::inner_product(&dist[..], &dir_margins[..]) <= 0.0 {
                weights[position_of_new_one] = max_stepsize;
                weights[position_of_worst_one] = 0.0;
                return weights;
            }

            let mut ub = max_stepsize;
            let mut lb = 0.0;
            while ub - lb > SUB_TOLERANCE {
                let step_size = (lb + ub) / 2.0;

                let margins = base_margins.iter()
                    .zip(&dir_margins[..])
                    .map(|(&b, &d)| b + step_size * d);
                let dist = utils::exp_distribution_from_margins(
                    self.eta, self.nu, margins,
                );


                // Compute the gradient for the direction `dir`.
                let dot = utils::inner_product(&dist[..], &dir_margins[..]);

                if dot < 0.0 {
                    lb = step_size;
                } else if dot > 0.0 {
                    ub = step_size;
                } else {
                    break;
                }
            }

            // Update the weights
            let step_size = (lb + ub) / 2.0;


            weights[position_of_local_best_one] += step_size;
            weights[position_of_worst_one] -= step_size;

            weights
        } else {
            // Ordinal FW update!
            // Find the best step size over [0, 1].
            self.line_search(
                sample, hypotheses, position_of_new_one, weights,
            )
        }
    }
}


/// Take the interior point of the given two arrays.
pub(crate) fn interior_point(
    step_size: f64,
    new_basis: usize,
    base: Vec<f64>,
) -> Vec<f64>
{
    checker::check_stepsize(step_size);
    base.into_iter()
        .enumerate()
        .map(|(j, b)| {
            let dir = if j == new_basis { 1.0 - b } else { -b };

            b + step_size * dir
        })
        .collect()
}