ferricml 0.2.1

A lean, pure-Rust toolkit for classical machine learning
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//! The public shape of a bagged tree ensemble, generated once.
//!
//! Two ensembles that differ only in how their members are grown must not
//! differ in their public surface, in their validation order, or in which fits
//! they persist. Generating both facades from one macro makes that structural:
//! an entry point cannot exist on one and be forgotten on the other, and a doc
//! comment cannot describe one estimator's behaviour while the other quietly
//! does something else.
//!
//! What each expansion supplies is only what genuinely differs: the type name,
//! its parameter type, its artifact kind, and its own type-level documentation.

/// Generates one public ensemble classifier over the shared core.
macro_rules! forest_classifier {
    ($name:ident, $params:ident, $kind:expr, $($doc:expr),+ $(,)?) => {
        $(#[doc = $doc])+
        ///
        /// Class labels are sorted, and probability columns follow that order.
        /// Models fitted on a single class expose one probability column
        /// containing `1.0`.
        ///
        /// [`fit`](Self::fit) takes binary targets and keeps the asymmetric
        /// scalar-leaf representation FerricML froze first.
        /// [`fit_multiclass`](Self::fit_multiclass) takes any observed class
        /// set and fits natively multiclass trees whose ensemble probability is
        /// the **mean of the per-tree probability vectors** — soft averaging,
        /// not a majority vote of per-tree labels. The two are different models
        /// even on the same two-class data. Both persist, under one artifact
        /// kind that records which leaf arithmetic it holds.
        #[derive(Clone, Debug, PartialEq)]
        pub struct $name {
            pub(crate) params: $params,
            pub(crate) core: $crate::ensemble::forest::model::ClassifierCore,
        }

        impl $name {
            /// Returns the feature width required by this model.
            #[inline]
            pub fn n_features_in(&self) -> usize {
                self.core.n_features_in
            }

            /// Returns the exact parameters used to fit this model.
            #[inline]
            pub fn get_params(&self) -> &$params {
                &self.params
            }

            /// Returns sorted class labels observed during fitting.
            #[inline]
            pub fn classes(&self) -> &[u8] {
                &self.core.classes
            }

            /// Fits a binary classifier over `0`/`1` targets.
            ///
            /// This is the asymmetric scalar-leaf fit: each tree stores the
            /// probability of class `1` and the ensemble averages that scalar.
            pub fn fit(
                data: &$crate::data::MatrixView<'_>,
                targets: &$crate::data::BinaryTargets,
                params: $params,
            ) -> Result<Self, $crate::api::ModelError> {
                Self::fit_binary(data, targets, None, params)
            }

            /// Fits a binary classifier with per-row sample weights.
            ///
            /// A weight scales the row's contribution to every impurity and
            /// leaf statistic, and composes with the bootstrap replication
            /// count. Weights of exactly one reproduce [`Self::fit`] bit for
            /// bit, and an integer weight is the same fit as repeating that row
            /// that many times.
            pub fn fit_weighted(
                data: &$crate::data::MatrixView<'_>,
                targets: &$crate::data::BinaryTargets,
                sample_weights: &$crate::data::SampleWeights,
                params: $params,
            ) -> Result<Self, $crate::api::ModelError> {
                Self::fit_binary(data, targets, Some(sample_weights), params)
            }

            fn fit_binary(
                data: &$crate::data::MatrixView<'_>,
                targets: &$crate::data::BinaryTargets,
                sample_weights: Option<&$crate::data::SampleWeights>,
                params: $params,
            ) -> Result<Self, $crate::api::ModelError> {
                use $crate::ensemble::forest::{model, training};
                let config = training::ForestConfig::from(&params);
                model::validate_common(data, targets.as_slice().len(), sample_weights, &config)?;
                let saw_zero = targets.as_slice().contains(&0);
                let saw_one = targets.as_slice().contains(&1);
                let classes = match (saw_zero, saw_one) {
                    (true, true) => vec![0, 1],
                    (true, false) => vec![0],
                    (false, true) => vec![1],
                    (false, false) => unreachable!("non-empty validated binary targets"),
                };
                let trees = training::train_forest(
                    data,
                    targets.as_slice(),
                    sample_weights.map($crate::data::SampleWeights::as_slice),
                    &config,
                    $crate::tree::Classification,
                )?;
                Ok(Self {
                    params,
                    core: model::ClassifierCore {
                        n_features_in: data.columns(),
                        classes,
                        forest: model::Forest::Binary(trees),
                    },
                })
            }

            /// Fits a natively multiclass classifier over any observed class
            /// set.
            ///
            /// Each tree splits on multiclass Gini impurity and stores one
            /// probability per class at every leaf. The ensemble probability is
            /// the **mean of the per-tree probability vectors**, which is a
            /// strictly different rule from a majority vote over per-tree
            /// labels — soft averaging produces values a vote cannot, and the
            /// two disagree on real data.
            ///
            /// A single observed class is accepted: the fit succeeds with one
            /// probability column containing `1.0`, matching the single-class
            /// contract the binary entry point already has. Two observed
            /// classes are also accepted and produce a vector-leaf model, which
            /// is a different — and deliberately not interchangeable — model
            /// from [`Self::fit`] on the same data.
            pub fn fit_multiclass(
                data: &$crate::data::MatrixView<'_>,
                targets: &$crate::data::ClassTargets,
                params: $params,
            ) -> Result<Self, $crate::api::ModelError> {
                Self::fit_multiclass_internal(data, targets, None, params)
            }

            /// Fits a natively multiclass classifier with per-row sample
            /// weights.
            ///
            /// The weight scales the row's contribution to the multiclass Gini
            /// statistics and to every leaf distribution, exactly as it does for
            /// the binary fit.
            pub fn fit_multiclass_weighted(
                data: &$crate::data::MatrixView<'_>,
                targets: &$crate::data::ClassTargets,
                sample_weights: &$crate::data::SampleWeights,
                params: $params,
            ) -> Result<Self, $crate::api::ModelError> {
                Self::fit_multiclass_internal(data, targets, Some(sample_weights), params)
            }

            fn fit_multiclass_internal(
                data: &$crate::data::MatrixView<'_>,
                targets: &$crate::data::ClassTargets,
                sample_weights: Option<&$crate::data::SampleWeights>,
                params: $params,
            ) -> Result<Self, $crate::api::ModelError> {
                use $crate::ensemble::forest::{model, training};
                let config = training::ForestConfig::from(&params);
                model::validate_common(data, targets.len(), sample_weights, &config)?;
                let classes = targets.classes().to_vec();
                let class_of_row = targets
                    .as_slice()
                    .iter()
                    .map(|&label| {
                        targets
                            .class_index(label)
                            .expect("every target label is an observed class")
                    })
                    .collect::<Vec<_>>();
                let trees = training::train_class_forest(
                    data,
                    &class_of_row,
                    classes.len(),
                    sample_weights.map($crate::data::SampleWeights::as_slice),
                    &config,
                )?;
                Ok(Self {
                    params,
                    core: model::ClassifierCore {
                        n_features_in: data.columns(),
                        classes,
                        forest: model::Forest::Multiclass(trees),
                    },
                })
            }

            /// Predicts the class label for one sample.
            pub fn predict_one(&self, row: &[f32]) -> Result<u8, $crate::api::ModelError> {
                self.core.predict_one(row)
            }

            /// Predicts one label per row, allocating the output vector.
            pub fn predict(
                &self,
                data: &$crate::data::MatrixView<'_>,
            ) -> Result<Vec<u8>, $crate::api::ModelError> {
                self.core.predict(data)
            }

            /// Predicts one label per row without allocating.
            pub fn predict_into(
                &self,
                data: &$crate::data::MatrixView<'_>,
                output: &mut [u8],
            ) -> Result<(), $crate::api::ModelError> {
                self.core.predict_into(data, output)
            }

            /// Predicts probabilities for one sample in [`Self::classes`] order.
            pub fn predict_proba_one(
                &self,
                row: &[f32],
            ) -> Result<Vec<f32>, $crate::api::ModelError> {
                self.core.predict_proba_one(row)
            }

            /// Predicts probabilities for one sample into caller-owned storage.
            pub fn predict_proba_one_into(
                &self,
                row: &[f32],
                output: &mut [f32],
            ) -> Result<(), $crate::api::ModelError> {
                self.core.predict_proba_one_into(row, output)
            }

            /// Predicts row-major probabilities, allocating
            /// `rows * classes().len()` values.
            pub fn predict_proba(
                &self,
                data: &$crate::data::MatrixView<'_>,
            ) -> Result<Vec<f32>, $crate::api::ModelError> {
                <Self as $crate::api::ProbabilisticClassifier>::predict_proba(self, data)
            }

            /// Predicts row-major probabilities without allocating.
            pub fn predict_proba_into(
                &self,
                data: &$crate::data::MatrixView<'_>,
                output: &mut [f32],
            ) -> Result<(), $crate::api::ModelError> {
                self.core.predict_proba_into(data, output)
            }

            /// Returns the requested fitted-class probability for one sample.
            pub fn predict_class_proba_one(
                &self,
                row: &[f32],
                class: u8,
            ) -> Result<f32, $crate::api::ModelError> {
                self.core.predict_class_proba_one(row, class)
            }

            /// Predicts one fitted-class probability column, allocating the
            /// output.
            pub fn predict_class_proba(
                &self,
                data: &$crate::data::MatrixView<'_>,
                class: u8,
            ) -> Result<Vec<f32>, $crate::api::ModelError> {
                <Self as $crate::api::ProbabilisticClassifier>::predict_class_proba(
                    self, data, class,
                )
            }

            /// Predicts one fitted-class probability column without allocating.
            pub fn predict_class_proba_into(
                &self,
                data: &$crate::data::MatrixView<'_>,
                class: u8,
                output: &mut [f32],
            ) -> Result<(), $crate::api::ModelError> {
                self.core.predict_class_proba_into(data, class, output)
            }

            /// Returns the positive-class probability for one sample.
            ///
            /// Defined only for a binary fit. A multiclass fit has no positive
            /// class and reports [`ModelError::MulticlassOutput`] instead of
            /// returning one column of a vector that has no distinguished
            /// member.
            ///
            /// [`ModelError::MulticlassOutput`]: crate::api::ModelError::MulticlassOutput
            pub fn predict_positive_proba_one(
                &self,
                row: &[f32],
            ) -> Result<f32, $crate::api::ModelError> {
                self.core.predict_positive_proba_one(row)
            }

            /// Predicts the positive-class probability for every row,
            /// allocating the output.
            pub fn predict_positive_proba(
                &self,
                data: &$crate::data::MatrixView<'_>,
            ) -> Result<Vec<f32>, $crate::api::ModelError> {
                self.core.predict_positive_proba(data)
            }

            /// Predicts the positive-class probability for every row without
            /// allocating. `output.len()` must equal the number of input rows.
            pub fn predict_positive_proba_into(
                &self,
                data: &$crate::data::MatrixView<'_>,
                output: &mut [f32],
            ) -> Result<(), $crate::api::ModelError> {
                self.core.predict_positive_proba_into(data, output)
            }

            /// The scalar trees of a binary fit, for in-crate structural tests.
            #[cfg(test)]
            pub(crate) fn binary_trees(&self) -> &[$crate::tree::PackedTree] {
                self.core.forest.binary_trees()
            }
        }

        impl $crate::api::Estimator for $name {
            fn n_features_in(&self) -> usize {
                self.core.n_features_in
            }
        }

        impl $crate::api::Classifier for $name {
            fn classes(&self) -> &[u8] {
                &self.core.classes
            }

            fn predict_into(
                &self,
                data: &$crate::data::MatrixView<'_>,
                output: &mut [u8],
            ) -> Result<(), $crate::api::ModelError> {
                self.core.predict_into(data, output)
            }
        }

        impl $crate::api::ProbabilisticClassifier for $name {
            fn predict_proba_into(
                &self,
                data: &$crate::data::MatrixView<'_>,
                output: &mut [f32],
            ) -> Result<(), $crate::api::ModelError> {
                self.core.predict_proba_into(data, output)
            }

            fn predict_class_proba_into(
                &self,
                data: &$crate::data::MatrixView<'_>,
                class: u8,
                output: &mut [f32],
            ) -> Result<(), $crate::api::ModelError> {
                self.core.predict_class_proba_into(data, class, output)
            }
        }

        impl $crate::api::HasParams for $name {
            type Params = $params;

            fn get_params(&self) -> &Self::Params {
                &self.params
            }
        }

        impl $crate::artifact::ModelArtifact for $name {
            const ARTIFACT_KIND: u16 = $kind;

            /// Encodes the fitted parameters, class list, and canonical logical
            /// trees.
            ///
            /// The two fits are different models with different leaf
            /// arithmetic, so the payload records which one it holds and the
            /// reader refuses to build the other. A binary fit reuses the scalar
            /// logical-tree records unchanged — the same codec the regressor and
            /// the boosted trees use. A multiclass fit writes the same topology
            /// records with a reserved zero where a scalar leaf carries its
            /// value, followed by that tree's leaf distributions in pre-order
            /// leaf rank. Storing rank rather than the runtime leaf ordinal is
            /// what keeps the encoding unique: the ordinals could be permuted
            /// together with the block to name one model twice.
            fn to_artifact(
                &self,
                schema: [u8; 32],
            ) -> Result<Vec<u8>, $crate::artifact::ArtifactError> {
                $crate::ensemble::forest::codec::encode_classifier(
                    Self::ARTIFACT_KIND,
                    &self.params.artifact_fields(self.core.n_features_in),
                    &self.core.classes,
                    &self.core.forest,
                    schema,
                )
            }

            /// Decodes and revalidates a classifier before building runtime
            /// state.
            ///
            /// Counts, parameters, and the class list are checked before any
            /// tree is read, every decoded tree re-enters the same topology
            /// validator fitting uses, and every decoded probability re-enters
            /// the same class-topology invariant a fitted tree satisfies.
            fn from_artifact(
                bytes: &[u8],
                schema: [u8; 32],
            ) -> Result<Self, $crate::artifact::ArtifactError> {
                let (fields, classes, forest) =
                    $crate::ensemble::forest::codec::decode_classifier(
                        Self::ARTIFACT_KIND,
                        bytes,
                        schema,
                    )?;
                Ok(Self {
                    params: $params::from_artifact_fields(&fields),
                    core: $crate::ensemble::forest::model::ClassifierCore {
                        n_features_in: fields.n_features_in,
                        classes,
                        forest,
                    },
                })
            }
        }

        /// Declares weighted fitting, multiclass fitting, persistence, and
        /// probabilities. The artifact covers *both* leaf representations, so
        /// the declaration holds for every fit this type offers rather than for
        /// one of its two entry points.
        impl $crate::api::HasCapabilities for $name {
            const CAPABILITIES: $crate::api::Capabilities = $crate::api::Capabilities::NONE
                .with_sample_weights(true)
                .with_artifact(true)
                .with_multiclass(true)
                .with_probability(true);
        }
    };
}

/// Generates one public ensemble regressor over the shared core.
macro_rules! forest_regressor {
    ($name:ident, $params:ident, $kind:expr, $objective:expr, $($doc:expr),+ $(,)?) => {
        $(#[doc = $doc])+
        #[derive(Clone, Debug, PartialEq)]
        pub struct $name {
            pub(crate) params: $params,
            pub(crate) core: $crate::ensemble::forest::model::RegressorCore,
        }

        impl $name {
            /// Returns the feature width required by this model.
            #[inline]
            pub fn n_features_in(&self) -> usize {
                self.core.n_features_in
            }

            /// Returns the exact parameters used to fit this model.
            #[inline]
            pub fn get_params(&self) -> &$params {
                &self.params
            }

            /// Fits one ensemble of regression trees.
            pub fn fit(
                data: &$crate::data::MatrixView<'_>,
                targets: &$crate::data::RegressionTargets,
                params: $params,
            ) -> Result<Self, $crate::api::ModelError> {
                Self::fit_internal(data, targets, None, params)
            }

            /// Fits with per-row sample weights.
            ///
            /// A weight scales the row's contribution to the variance and leaf
            /// mean of every node it reaches, and composes with the bootstrap
            /// replication count. Weights of exactly one reproduce [`Self::fit`]
            /// bit for bit, and an integer weight is the same fit as repeating
            /// that row that many times.
            pub fn fit_weighted(
                data: &$crate::data::MatrixView<'_>,
                targets: &$crate::data::RegressionTargets,
                sample_weights: &$crate::data::SampleWeights,
                params: $params,
            ) -> Result<Self, $crate::api::ModelError> {
                Self::fit_internal(data, targets, Some(sample_weights), params)
            }

            fn fit_internal(
                data: &$crate::data::MatrixView<'_>,
                targets: &$crate::data::RegressionTargets,
                sample_weights: Option<&$crate::data::SampleWeights>,
                params: $params,
            ) -> Result<Self, $crate::api::ModelError> {
                use $crate::ensemble::forest::{model, training};
                let config = training::ForestConfig::from(&params);
                model::validate_common(data, targets.as_slice().len(), sample_weights, &config)?;
                let trees = training::train_forest(
                    data,
                    targets.as_slice(),
                    sample_weights.map($crate::data::SampleWeights::as_slice),
                    &config,
                    $objective,
                )?;
                Ok(Self {
                    params,
                    core: model::RegressorCore {
                        n_features_in: data.columns(),
                        trees,
                    },
                })
            }

            /// Predicts one regression value for one sample.
            pub fn predict_one(&self, row: &[f32]) -> Result<f32, $crate::api::ModelError> {
                self.core.predict_one(row)
            }

            /// Predicts one value per row, allocating the output vector.
            pub fn predict(
                &self,
                data: &$crate::data::MatrixView<'_>,
            ) -> Result<Vec<f32>, $crate::api::ModelError> {
                <Self as $crate::api::Regressor>::predict(self, data)
            }

            /// Predict every row without allocating. `output.len()` must equal
            /// the number of input rows.
            pub fn predict_into(
                &self,
                data: &$crate::data::MatrixView<'_>,
                output: &mut [f32],
            ) -> Result<(), $crate::api::ModelError> {
                self.core.predict_into(data, output)
            }

        }

        impl $crate::artifact::ModelArtifact for $name {
            const ARTIFACT_KIND: u16 = $kind;

            /// Encodes the fitted parameters and canonical logical trees.
            ///
            /// The private packed inference layout is never serialized. Each
            /// tree is expanded into stable logical records first, so the
            /// compact runtime representation stays free to change.
            fn to_artifact(
                &self,
                schema: [u8; 32],
            ) -> Result<Vec<u8>, $crate::artifact::ArtifactError> {
                $crate::ensemble::forest::codec::encode_regressor(
                    Self::ARTIFACT_KIND,
                    &self.params.artifact_fields(self.core.n_features_in),
                    &self.core.trees,
                    schema,
                )
            }

            /// Decodes and revalidates logical trees before building runtime
            /// state.
            ///
            /// Counts and parameters are checked before any tree is read, and
            /// each decoded tree is rebuilt through the same topology validator
            /// that fitting uses, so the encoded bytes are never trusted.
            fn from_artifact(
                bytes: &[u8],
                schema: [u8; 32],
            ) -> Result<Self, $crate::artifact::ArtifactError> {
                let (fields, trees) = $crate::ensemble::forest::codec::decode_regressor(
                    Self::ARTIFACT_KIND,
                    bytes,
                    schema,
                )?;
                Ok(Self {
                    params: $params::from_artifact_fields(&fields),
                    core: $crate::ensemble::forest::model::RegressorCore {
                        n_features_in: fields.n_features_in,
                        trees,
                    },
                })
            }
        }

        impl $crate::api::Estimator for $name {
            fn n_features_in(&self) -> usize {
                self.core.n_features_in
            }
        }

        impl $crate::api::Regressor for $name {
            fn predict_into(
                &self,
                data: &$crate::data::MatrixView<'_>,
                output: &mut [f32],
            ) -> Result<(), $crate::api::ModelError> {
                self.core.predict_into(data, output)
            }
        }

        impl $crate::api::HasParams for $name {
            type Params = $params;

            fn get_params(&self) -> &Self::Params {
                &self.params
            }
        }

        /// Declares weighted fitting and persistence, and no more.
        ///
        /// The two capabilities the classifier facade adds are genuinely
        /// absent from a regression ensemble: `probability` and `multiclass`
        /// are both statements about a class set, and a forest of regression
        /// trees averages leaf means. `decision_function` records that a
        /// *classifier* exposes a raw score whose squashing is its
        /// probability, which a predicted value is not.
        impl $crate::api::HasCapabilities for $name {
            const CAPABILITIES: $crate::api::Capabilities = $crate::api::Capabilities::NONE
                .with_sample_weights(true)
                .with_artifact(true);
        }
    };
}

pub(crate) use {forest_classifier, forest_regressor};