Skip to main content

malware_modeler/
crossval.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use crate::Bytes;
4use crate::dataset::{Dataset, TrainingData};
5use crate::ftype::FileType;
6use crate::model::{LogisticRegression, PerformanceStats};
7use crate::row::RowSlice;
8
9use std::fmt::{Display, Formatter};
10use std::str::FromStr;
11
12use anyhow::{Result, anyhow, ensure};
13use rand::seq::SliceRandom;
14
15/// A subset of a dataset's rows, borrowed rather than copied.
16///
17/// Holds only row numbers into the dataset, so a view costs eight bytes per row however wide
18/// the rows are, and shuffling it reorders those numbers without touching the dataset.
19#[derive(Debug, Clone)]
20pub struct DatasetView<'a> {
21    /// The dataset the rows come from
22    dataset: &'a Dataset,
23
24    /// Row numbers into `dataset`, in this view's order
25    rows: Vec<usize>,
26}
27
28impl<'a> DatasetView<'a> {
29    /// A view of the given rows of a dataset.
30    ///
31    /// # Errors
32    ///
33    /// Returns an error if the dataset's labels don't match its rows, or a row number is out
34    /// of range.
35    pub fn new(dataset: &'a Dataset, rows: Vec<usize>) -> Result<Self> {
36        ensure!(
37            dataset.labels.len() == dataset.data.len(),
38            "Dataset has {} labels for {} rows",
39            dataset.labels.len(),
40            dataset.data.len()
41        );
42        ensure!(
43            rows.iter().all(|row| *row < dataset.len()),
44            "Row number out of range for a dataset of {} rows",
45            dataset.len()
46        );
47        Ok(Self { dataset, rows })
48    }
49
50    /// The dataset this view borrows from.
51    #[must_use]
52    pub fn dataset(&self) -> &'a Dataset {
53        self.dataset
54    }
55
56    /// Row numbers into the dataset, in this view's order.
57    #[must_use]
58    pub fn rows(&self) -> &[usize] {
59        &self.rows
60    }
61
62    /// Count the (benign, malicious) rows in the view.
63    #[must_use]
64    pub fn class_counts(&self) -> (usize, usize) {
65        let malicious = self
66            .rows
67            .iter()
68            .filter(|row| self.dataset.labels[**row] >= 1)
69            .count();
70        (self.rows.len() - malicious, malicious)
71    }
72}
73
74impl TrainingData for DatasetView<'_> {
75    fn len(&self) -> usize {
76        self.rows.len()
77    }
78
79    fn row_len(&self) -> usize {
80        self.dataset.data.row_len()
81    }
82
83    fn features(&self) -> &[Bytes] {
84        &self.dataset.features
85    }
86
87    fn file_type(&self) -> FileType {
88        self.dataset.ftype
89    }
90
91    fn stride(&self) -> u16 {
92        self.dataset.stride
93    }
94
95    fn has_labels(&self) -> bool {
96        // Checked against the dataset when the view was made.
97        true
98    }
99
100    fn labelled_rows(&self) -> impl Iterator<Item = (RowSlice<'_>, u8)> + '_ {
101        self.rows.iter().filter_map(|row| {
102            Some((
103                self.dataset.data.row(*row)?,
104                *self.dataset.labels.get(*row)?,
105            ))
106        })
107    }
108
109    fn shuffle(&mut self) {
110        self.rows.shuffle(&mut rand::rng());
111    }
112
113    fn column_sums(&self) -> Vec<f32> {
114        let mut sums = vec![0.0f32; self.row_len()];
115        for (row, _) in self.labelled_rows() {
116            for (index, value) in row.iter_nonzero() {
117                if let Some(sum) = sums.get_mut(index) {
118                    *sum += value;
119                }
120            }
121        }
122        sums
123    }
124
125    fn validate(&self) -> bool {
126        !self.rows.is_empty() && self.dataset.validate()
127    }
128}
129
130/// One fold of a cross validation: a label-balanced training set and the held-out rows.
131#[derive(Debug, Clone)]
132pub struct Fold<'a> {
133    /// Which fold this is, from zero
134    pub index: usize,
135
136    /// Rows to train on, the same number of benign and malicious
137    pub train: DatasetView<'a>,
138
139    /// Rows held out for testing, in the dataset's class proportions
140    pub test: DatasetView<'a>,
141}
142
143/// Stratified n-fold cross validation over a dataset, borrowing its rows.
144///
145/// The benign and malicious rows are each shuffled and dealt evenly across the folds, so every
146/// fold holds the dataset's class proportions and every row is tested exactly once. A fold's
147/// training set is every other fold's rows with the majority class randomly cut down to the
148/// size of the minority class, so the model always trains on balanced labels; the rows cut
149/// are simply unused by that fold.
150#[derive(Debug, Clone)]
151pub struct CrossValidation<'a> {
152    /// The dataset the folds borrow from
153    dataset: &'a Dataset,
154
155    /// Row numbers in each fold
156    folds: Vec<Vec<usize>>,
157}
158
159impl<'a> CrossValidation<'a> {
160    /// Deal a dataset's rows into `folds` stratified folds.
161    ///
162    /// # Errors
163    ///
164    /// Returns an error if there are fewer than two folds, the dataset fails
165    /// [`Dataset::validate`] or has no labels, or either class has fewer rows than there are
166    /// folds.
167    pub fn new(dataset: &'a Dataset, folds: usize) -> Result<Self> {
168        ensure!(folds >= 2, "Cross validation needs at least two folds");
169        ensure!(
170            !dataset.labels.is_empty() && dataset.labels.len() == dataset.len(),
171            "Cross validation requires a label for every row"
172        );
173        ensure!(dataset.validate(), "Dataset didn't pass validity check");
174
175        let mut rng = rand::rng();
176        let (mut benign, mut malicious): (Vec<usize>, Vec<usize>) =
177            (0..dataset.len()).partition(|row| dataset.labels[*row] == 0);
178        ensure!(
179            benign.len() >= folds && malicious.len() >= folds,
180            "Each class needs at least one row per fold, but there are {} benign and {} \
181             malicious rows for {folds} folds",
182            benign.len(),
183            malicious.len()
184        );
185        benign.shuffle(&mut rng);
186        malicious.shuffle(&mut rng);
187
188        // Dealing the malicious rows on from where the benign ones stopped keeps the fold
189        // sizes within one row of each other.
190        let mut dealt = vec![Vec::with_capacity(dataset.len() / folds + 1); folds];
191        for (position, row) in benign.into_iter().chain(malicious).enumerate() {
192            dealt[position % folds].push(row);
193        }
194
195        Ok(Self {
196            dataset,
197            folds: dealt,
198        })
199    }
200
201    /// Number of folds.
202    #[must_use]
203    pub const fn folds(&self) -> usize {
204        self.folds.len()
205    }
206
207    /// The training and test sets for one fold.
208    ///
209    /// Which majority-class rows are left out of the training set is chosen afresh on every
210    /// call, so two calls for the same fold can train on different rows.
211    ///
212    /// # Errors
213    ///
214    /// Returns an error if `index` isn't a fold.
215    pub fn fold(&self, index: usize) -> Result<Fold<'a>> {
216        let test = self
217            .folds
218            .get(index)
219            .ok_or_else(|| anyhow!("Fold {index} out of range, there are {}", self.folds()))?
220            .clone();
221
222        let (mut benign, mut malicious): (Vec<usize>, Vec<usize>) = self
223            .folds
224            .iter()
225            .enumerate()
226            .filter(|(other, _)| *other != index)
227            .flat_map(|(_, rows)| rows.iter().copied())
228            .partition(|row| self.dataset.labels[*row] == 0);
229
230        let mut rng = rand::rng();
231        let per_class = benign.len().min(malicious.len());
232        for class in [&mut benign, &mut malicious] {
233            if class.len() > per_class {
234                class.shuffle(&mut rng);
235                class.truncate(per_class);
236            }
237        }
238        benign.append(&mut malicious);
239
240        Ok(Fold {
241            index,
242            train: DatasetView::new(self.dataset, benign)?,
243            test: DatasetView::new(self.dataset, test)?,
244        })
245    }
246
247    /// Train and test a fresh model on one fold, see [`LogisticRegression::fit`].
248    ///
249    /// # Errors
250    ///
251    /// Returns an error if `index` isn't a fold or training fails.
252    ///
253    /// # Panics
254    ///
255    /// This won't panic as there will be a test result.
256    pub fn run_fold(
257        &self,
258        index: usize,
259        epochs: u32,
260        learning_rate: f32,
261        l1: f32,
262        l2: f32,
263    ) -> Result<FoldResult> {
264        let Fold {
265            mut train, test, ..
266        } = self.fold(index)?;
267
268        let mut model = LogisticRegression::new(train.row_len(), learning_rate, l1, l2);
269        let run = model.fit(epochs, &mut train, Some(&test))?;
270
271        Ok(FoldResult {
272            index,
273            train_rows: train.len(),
274            test_rows: test.len(),
275            loss: run.loss,
276            features_removed: run.features_removed,
277            test_performance: model.test_performance.unwrap(),
278            model,
279        })
280    }
281
282    /// Train and test a fresh model on every fold in turn.
283    ///
284    /// # Errors
285    ///
286    /// Returns an error if any fold fails to train.
287    pub fn run(
288        &self,
289        epochs: u32,
290        learning_rate: f32,
291        l1: f32,
292        l2: f32,
293        metric: SelectionMetric,
294    ) -> Result<CrossValidationReport> {
295        let folds = (0..self.folds())
296            .map(|index| self.run_fold(index, epochs, learning_rate, l1, l2))
297            .collect::<Result<Vec<_>>>()?;
298        CrossValidationReport::new(folds, metric)
299    }
300}
301
302/// The model trained on one fold, and how it did.
303#[derive(Debug, Clone)]
304pub struct FoldResult {
305    /// Which fold this is, from zero
306    pub index: usize,
307
308    /// Rows trained on
309    pub train_rows: usize,
310
311    /// Rows held out and tested on
312    pub test_rows: usize,
313
314    /// Mean log loss of the final epoch
315    pub loss: f32,
316
317    /// Features dropped after training
318    pub features_removed: usize,
319
320    /// The trained model. Its `test_performance` is on the held-out fold.
321    pub model: LogisticRegression,
322
323    /// Performance results on the test data
324    pub test_performance: PerformanceStats,
325}
326
327/// The measure used to pick the best fold's model.
328#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
329pub enum SelectionMetric {
330    /// Correct predictions over all predictions
331    Accuracy,
332
333    /// True positives over predicted positives
334    Precision,
335
336    /// True positives over actual positives
337    Recall,
338
339    /// Harmonic mean of precision and recall
340    F1,
341
342    /// Area under the ROC curve, which doesn't depend on the 0.5 threshold
343    #[default]
344    Auc,
345}
346
347impl SelectionMetric {
348    /// Every metric, in display order.
349    pub const ALL: [Self; 5] = [
350        Self::Accuracy,
351        Self::Precision,
352        Self::Recall,
353        Self::F1,
354        Self::Auc,
355    ];
356
357    /// This metric's score for some performance statistics.
358    #[must_use]
359    pub fn score(self, stats: &PerformanceStats) -> f32 {
360        match self {
361            Self::Accuracy => stats.accuracy(),
362            Self::Precision => stats.precision,
363            Self::Recall => stats.recall,
364            Self::F1 => stats.f1,
365            Self::Auc => stats.auc,
366        }
367    }
368}
369
370impl Display for SelectionMetric {
371    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
372        f.write_str(match self {
373            Self::Accuracy => "accuracy",
374            Self::Precision => "precision",
375            Self::Recall => "recall",
376            Self::F1 => "f1",
377            Self::Auc => "auc",
378        })
379    }
380}
381
382impl FromStr for SelectionMetric {
383    type Err = anyhow::Error;
384
385    fn from_str(value: &str) -> Result<Self> {
386        Self::ALL
387            .into_iter()
388            .find(|metric| metric.to_string().eq_ignore_ascii_case(value))
389            .ok_or_else(|| {
390                anyhow!("Unknown metric '{value}', expected accuracy, precision, recall, f1 or auc")
391            })
392    }
393}
394
395/// Every fold's model and performance, and which is best.
396#[derive(Debug, Clone)]
397pub struct CrossValidationReport {
398    /// Each fold's result, in fold order
399    pub folds: Vec<FoldResult>,
400
401    /// The measure the best fold was picked by
402    pub metric: SelectionMetric,
403
404    /// Position in `folds` of the best fold
405    best: usize,
406}
407
408impl CrossValidationReport {
409    /// Collect the fold results and pick the best by `metric` on the held-out data, breaking
410    /// ties by AUC (or by F1 when AUC is the metric).
411    ///
412    /// A fold whose score is `NaN`, such as precision when nothing was predicted malicious,
413    /// counts as worse than any other.
414    ///
415    /// # Errors
416    ///
417    /// Returns an error if there are no folds.
418    pub fn new(folds: Vec<FoldResult>, metric: SelectionMetric) -> Result<Self> {
419        let tie_breaker = if metric == SelectionMetric::Auc {
420            SelectionMetric::F1
421        } else {
422            SelectionMetric::Auc
423        };
424        let score = |metric: SelectionMetric, fold: &FoldResult| {
425            let score = metric.score(&fold.test_performance);
426            if score.is_nan() {
427                f32::NEG_INFINITY
428            } else {
429                score
430            }
431        };
432        let best = folds
433            .iter()
434            .enumerate()
435            .max_by(|(_, a), (_, b)| {
436                score(metric, a)
437                    .total_cmp(&score(metric, b))
438                    .then_with(|| score(tie_breaker, a).total_cmp(&score(tie_breaker, b)))
439            })
440            .map(|(position, _)| position)
441            .ok_or_else(|| anyhow!("Cross validation produced no folds"))?;
442
443        Ok(Self {
444            folds,
445            metric,
446            best,
447        })
448    }
449
450    /// The best fold.
451    #[must_use]
452    pub fn best(&self) -> &FoldResult {
453        &self.folds[self.best]
454    }
455
456    /// Take the best fold's model, discarding the others.
457    #[must_use]
458    pub fn into_best(mut self) -> LogisticRegression {
459        self.folds.swap_remove(self.best).model
460    }
461
462    /// Mean and sample standard deviation of a metric on the held-out folds.
463    ///
464    /// Folds scoring `NaN` are left out.
465    #[must_use]
466    #[allow(clippy::cast_precision_loss)]
467    pub fn mean_std(&self, metric: SelectionMetric) -> (f32, f32) {
468        let scores = self
469            .folds
470            .iter()
471            .map(|fold| metric.score(&fold.test_performance))
472            .filter(|score| !score.is_nan())
473            .collect::<Vec<_>>();
474        if scores.is_empty() {
475            return (f32::NAN, f32::NAN);
476        }
477
478        let mean = scores.iter().sum::<f32>() / scores.len() as f32;
479        let std = if scores.len() > 1 {
480            (scores.iter().map(|s| (s - mean).powi(2)).sum::<f32>() / (scores.len() - 1) as f32)
481                .sqrt()
482        } else {
483            0.0
484        };
485        (mean, std)
486    }
487}
488
489impl Display for CrossValidationReport {
490    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
491        writeln!(
492            f,
493            "Fold | Train rows | Test rows |  Loss    | Features | Accuracy | Precision | Recall | F1     | AUC"
494        )?;
495        for fold in &self.folds {
496            let stats = fold.test_performance;
497            writeln!(
498                f,
499                "{:>4} | {:>10} | {:>9} | {:<8.6} | {:>8} | {:<8.4} | {:<9.4} | {:<6.4} | {:<6.4} | {:<6.4}{}",
500                fold.index + 1,
501                fold.train_rows,
502                fold.test_rows,
503                fold.loss,
504                fold.model.weights.len(),
505                stats.accuracy(),
506                stats.precision,
507                stats.recall,
508                stats.f1,
509                stats.auc,
510                if fold.index == self.best().index {
511                    "  <- best"
512                } else {
513                    ""
514                }
515            )?;
516        }
517
518        writeln!(f)?;
519        for metric in SelectionMetric::ALL {
520            let (mean, std) = self.mean_std(metric);
521            writeln!(f, "{:<10} {mean:.4} ± {std:.4}", format!("{metric}:"))?;
522        }
523        writeln!(
524            f,
525            "\nBest fold by {}: {}",
526            self.metric,
527            self.best().index + 1
528        )
529    }
530}
531
532#[cfg(test)]
533mod tests {
534    use super::*;
535    use crate::row::{DataMatrix, DataRow};
536
537    /// Build a dataset whose rows encode their own index in binary, so folds can be checked
538    /// for lost or duplicated rows and for labels that didn't travel with their rows.
539    fn indexed_dataset(benign: usize, malicious: usize) -> Dataset {
540        const BITS: usize = 16;
541        let total = benign + malicious;
542        Dataset {
543            data: (0..total)
544                .map(|row| {
545                    let mut r = DataRow::zeroed(BITS);
546                    for bit in 0..BITS {
547                        if row & (1 << bit) != 0 {
548                            r.set(bit, 1.0).unwrap();
549                        }
550                    }
551                    r
552                })
553                .collect::<DataMatrix>(),
554            labels: (0..total).map(|row| u8::from(row >= benign)).collect(),
555            features: (0..BITS).map(|b| vec![u8::try_from(b).unwrap()]).collect(),
556            ftype: FileType::PDF,
557            stride: 1,
558        }
559    }
560
561    /// Decode the dataset row numbers of a view, checking each label came with its row.
562    fn row_ids(view: &DatasetView<'_>, benign: usize) -> Vec<usize> {
563        view.labelled_rows()
564            .map(|(row, label)| {
565                let id = row.iter_nonzero().map(|(bit, _)| 1 << bit).sum::<usize>();
566                assert_eq!(label, u8::from(id >= benign), "row {id} lost its label");
567                id
568            })
569            .collect()
570    }
571
572    #[test]
573    fn every_row_is_tested_exactly_once() {
574        let dataset = indexed_dataset(700, 300);
575        let cv = CrossValidation::new(&dataset, 5).unwrap();
576
577        let mut tested = vec![];
578        for index in 0..cv.folds() {
579            let fold = cv.fold(index).unwrap();
580            // Stratified: each fold holds the dataset's 70/30 split.
581            assert_eq!(fold.test.class_counts(), (140, 60));
582            tested.extend(row_ids(&fold.test, 700));
583        }
584        tested.sort_unstable();
585        assert_eq!(tested, (0..1000).collect::<Vec<_>>());
586    }
587
588    #[test]
589    fn training_folds_are_balanced_and_disjoint_from_test() {
590        let dataset = indexed_dataset(700, 300);
591        let cv = CrossValidation::new(&dataset, 5).unwrap();
592
593        for index in 0..cv.folds() {
594            let fold = cv.fold(index).unwrap();
595            assert_eq!(fold.train.class_counts(), (240, 240));
596
597            let train = row_ids(&fold.train, 700);
598            let test = row_ids(&fold.test, 700);
599            assert!(train.iter().all(|row| !test.contains(row)));
600
601            let mut unique = train.clone();
602            unique.sort_unstable();
603            unique.dedup();
604            assert_eq!(unique.len(), train.len(), "fold {index} repeats a row");
605        }
606    }
607
608    /// Views reorder row numbers, not the dataset.
609    #[test]
610    fn shuffling_a_view_leaves_the_dataset_alone() {
611        let dataset = indexed_dataset(50, 50);
612        let before = dataset.clone();
613        let cv = CrossValidation::new(&dataset, 2).unwrap();
614        let mut fold = cv.fold(0).unwrap();
615
616        let mut ids = row_ids(&fold.train, 50);
617        fold.train.shuffle();
618        let mut shuffled = row_ids(&fold.train, 50);
619        ids.sort_unstable();
620        shuffled.sort_unstable();
621        assert_eq!(ids, shuffled);
622        assert_eq!(dataset.data, before.data);
623        assert_eq!(dataset.labels, before.labels);
624    }
625
626    #[test]
627    fn view_column_sums_match_its_rows() {
628        let dataset = indexed_dataset(20, 20);
629        let all = DatasetView::new(&dataset, (0..dataset.len()).collect()).unwrap();
630        assert_eq!(TrainingData::column_sums(&all), dataset.column_sums());
631
632        let one = DatasetView::new(&dataset, vec![5]).unwrap();
633        let sums = TrainingData::column_sums(&one);
634        assert_eq!(sums[0], 1.0);
635        assert_eq!(sums[1], 0.0);
636        assert_eq!(sums[2], 1.0);
637        assert_eq!(sums.iter().sum::<f32>(), 2.0);
638    }
639
640    #[test]
641    fn rejects_bad_input() {
642        let dataset = indexed_dataset(10, 3);
643        assert!(CrossValidation::new(&dataset, 1).is_err());
644        assert!(CrossValidation::new(&dataset, 4).is_err());
645        assert!(CrossValidation::new(&dataset, 3).is_ok());
646        assert!(CrossValidation::new(&dataset, 3).unwrap().fold(3).is_err());
647
648        let mut unlabelled = dataset.clone();
649        unlabelled.labels.clear();
650        assert!(CrossValidation::new(&unlabelled, 2).is_err());
651        assert!(DatasetView::new(&dataset, vec![13]).is_err());
652    }
653
654    #[test]
655    fn run_keeps_a_model_per_fold_and_picks_the_best() {
656        // Bit 6 of the row number is set exactly for the malicious rows, so there is signal
657        // to learn.
658        let dataset = indexed_dataset(64, 64);
659        let folds = 4;
660
661        let cv = CrossValidation::new(&dataset, folds).unwrap();
662        let report = cv.run(5, 0.2, 0.0, 0.0, SelectionMetric::Auc).unwrap();
663        assert_eq!(report.folds.len(), folds);
664        assert!(report.folds.iter().all(|f| f.model.trained));
665        assert!(
666            report
667                .folds
668                .iter()
669                .all(|f| f.model.test_performance.is_some())
670        );
671
672        let best_auc = report.best().test_performance.auc;
673        assert!(
674            report
675                .folds
676                .iter()
677                .all(|f| f.test_performance.auc <= best_auc)
678        );
679        assert!(report.to_string().contains("<- best"));
680
681        let best = report.best().model.clone();
682        assert_eq!(report.into_best(), best);
683    }
684
685    #[test]
686    fn metric_round_trips_through_strings() {
687        for metric in SelectionMetric::ALL {
688            assert_eq!(
689                metric.to_string().parse::<SelectionMetric>().unwrap(),
690                metric
691            );
692        }
693        assert_eq!(
694            "AUC".parse::<SelectionMetric>().unwrap(),
695            SelectionMetric::Auc
696        );
697        assert!("bogus".parse::<SelectionMetric>().is_err());
698    }
699}