Skip to main content

malware_modeler/
model.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use crate::Bytes;
4use crate::dataset::{Dataset, TrainingData};
5use crate::ftype::FileType;
6use crate::hash::{FxBuildHasher, FxHashMap};
7use crate::ngram::{Ngrammer, NgramsFile};
8use crate::row::RowSlice;
9
10use std::cmp::Ordering;
11use std::fs::File;
12use std::hash::BuildHasherDefault;
13use std::io::{BufReader, BufWriter, Read, Write};
14use std::path::Path;
15
16use anyhow::{Result, anyhow, bail, ensure};
17use jiff::Timestamp;
18use rand::RngExt;
19use rayon::prelude::*;
20use serde::{Deserialize, Serialize};
21
22// Adapted from https://github.com/ibnz36/lrclassifier/blob/06d136445028653af5d2061e002111ef11b14277/src/lib.rs
23// Accessed 01 November 2025
24
25/// The sigmoid function.
26#[inline]
27#[must_use]
28fn sigmoid(x: f32) -> f32 {
29    1.0 / (1.0 + (-x).exp())
30}
31
32/// Weights per rayon task when applying the regularization decay.
33///
34/// Large enough that the per-task overhead is negligible next to the work, small enough to
35/// keep every core busy for the feature counts this crate produces.
36const WEIGHT_CHUNK: usize = 8192;
37
38/// Margin keeping the log-loss away from `ln(0)`.
39///
40/// This has to be representable in `f32`: the spacing below 1.0 is about 6e-8, so a margin
41/// of 1e-8 rounds `1.0 - margin` straight back to 1.0 and the clamp does nothing. A
42/// saturated prediction then reached `ln(0)`, making the reported loss `NaN` or infinite.
43const LOSS_EPSILON: f32 = 1e-6;
44
45/// Row count above which training reports progress.
46///
47/// Small enough that any run worth watching shows a bar, large enough that the tests and any
48/// toy dataset stay quiet.
49const PROGRESS_MIN_ROWS: usize = 4096;
50
51/// Samples between progress bar updates, so the bar costs nothing per sample.
52const PROGRESS_UPDATE_SAMPLES: u64 = 4096;
53
54/// Compile-time guard that [`LOSS_EPSILON`] survives `f32` rounding, which a 1e-8 margin
55/// does not.
56const _: () = assert!(1.0 - LOSS_EPSILON < 1.0);
57
58/// Template for the training progress bar.
59///
60/// A named constant so a test can check it parses: an invalid template falls back to a default
61/// bar that has no `{msg}`, which loses the epoch and loss without failing anything.
62const TRAINING_BAR_TEMPLATE: &str =
63    "{msg} {wide_bar} {human_pos}/{human_len} samples [{elapsed_precise}<{eta_precise}]";
64
65/// Progress bar for a training run, measured in samples across every epoch.
66fn training_progress_bar(total_samples: u64, epochs: u32) -> indicatif::ProgressBar {
67    let style = indicatif::ProgressStyle::with_template(TRAINING_BAR_TEMPLATE)
68        .unwrap_or_else(|_| indicatif::ProgressStyle::default_bar());
69
70    indicatif::ProgressBar::new(total_samples)
71        .with_style(style)
72        .with_message(format!("Epoch 1/{epochs}"))
73}
74
75/// Machine learning model using logistic regression
76#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
77pub struct LogisticRegression {
78    /// Learning rate
79    pub learning_rate: f32,
80
81    /// Bias term
82    pub bias: f32,
83
84    /// Model's weights
85    pub weights: Vec<f32>,
86
87    /// When the model was created
88    pub created: Timestamp,
89
90    /// L1 LASSO regularization
91    pub l1: f32,
92
93    /// L2 Ridge regularization
94    pub l2: f32,
95
96    /// N-grams used to train the model
97    #[serde(
98        serialize_with = "crate::serde::serialize_hex_map",
99        deserialize_with = "crate::serde::deserialize_hex_map"
100    )]
101    /// Keyed with [`crate::hash::FxHasher`]: this map is probed once per byte of a sample
102    /// during [`LogisticRegression::evaluate_file`].
103    pub features: FxHashMap<Bytes, usize>,
104
105    /// N-gram size
106    pub n: u16,
107
108    /// Stride used to find n-grams
109    pub s: u16,
110
111    /// If the model has been trained
112    pub trained: bool,
113
114    /// Amount of n-grams originally used
115    pub original_ngrams: u32,
116
117    /// The type of file this model is trained on
118    pub file_type: FileType,
119
120    /// How well the model performed on the training dataset
121    pub train_performance: PerformanceStats,
122
123    /// How well the model performed on the testing dataset
124    #[serde(default)]
125    pub test_performance: Option<PerformanceStats>,
126}
127
128impl LogisticRegression {
129    /// Magic number indicating that a file is a binary model
130    pub const MAGIC_NUMBER: [u8; 4] = *b"ZZMM";
131
132    /// Model file format version number, a placeholder to allow for future changes
133    const VERSION: u16 = 1;
134
135    /// Flag to indicate that the model has test data evaluation statistics
136    pub const HAS_TEST_STATS: u8 = 1;
137
138    /// Flag to indicate that the model does not have test data evaluation statistics
139    const WITHOUT_TEST_STATS: u8 = 0;
140
141    /// Load a model from a path
142    ///
143    /// # Errors
144    ///
145    /// Errors result if the file isn't a model, doesn't have a file extension, or
146    /// isn't Json or Toml.
147    pub fn load<P: AsRef<Path>>(path: P) -> Result<LogisticRegression> {
148        ensure!(
149            path.as_ref().exists(),
150            "File {} not found",
151            path.as_ref().display()
152        );
153
154        let Some(ext) = path.as_ref().extension().and_then(|ext| ext.to_str()) else {
155            bail!("File {} has no extension", path.as_ref().display());
156        };
157
158        let model = match ext.to_ascii_lowercase().as_str() {
159            "json" => {
160                let model_contents = std::fs::read_to_string(&path)?;
161                serde_json::from_str(model_contents.as_str())?
162            }
163            "toml" => {
164                let model_contents = std::fs::read_to_string(&path)?;
165                toml::from_str(model_contents.as_str())?
166            }
167            "bin" | "model" => {
168                let mut buffer = BufReader::new(File::open(path)?);
169                LogisticRegression::from_bytes(&mut buffer)?
170            }
171            ext => bail!("Unsupported file extension: {ext}"),
172        };
173
174        ensure!(
175            model.features.len() == model.weights.len(),
176            "The amount of features and weights must be equal"
177        );
178
179        Ok(model)
180    }
181
182    /// New logistic regression model from given parameters.
183    #[must_use]
184    #[allow(clippy::cast_possible_truncation)]
185    pub fn new(input_size: usize, learning_rate: f32, l1: f32, l2: f32) -> Self {
186        let mut rng = rand::rng();
187
188        Self {
189            learning_rate,
190            weights: vec![0.0; input_size],
191            l1,
192            l2,
193            created: Timestamp::now(),
194            n: 0,
195            s: 0,
196            features: FxHashMap::default(),
197            trained: false,
198            bias: rng.random(),
199            original_ngrams: input_size as u32,
200            file_type: FileType::NotSet,
201            train_performance: PerformanceStats::default(),
202            test_performance: None,
203        }
204    }
205
206    /// Returns a trained logistic regression model from given parameters and dataset. Returns the model
207    /// and the error value from the last epoch.
208    ///
209    /// # Panics
210    ///
211    /// Panics if `dataset` has no features, or if it fails [`Dataset::validate`] — for
212    /// example if it has no labels, or rows of differing lengths. The weight count is taken
213    /// from the dataset itself, so it always agrees with the data.
214    #[must_use]
215    pub fn new_from_dataset_and_train(
216        dataset: &mut Dataset,
217        test: Option<&Dataset>,
218        epochs: u32,
219        learning_rate: f32,
220        l1: f32,
221        l2: f32,
222    ) -> (Self, f32) {
223        // One weight per *feature*, not per row. Passing the row count produced a model
224        // whose weight vector was unrelated to the data, so `train` below rejected it and
225        // this function panicked on the `unwrap` for any dataset that wasn't square.
226        let mut model = Self::new(dataset.features.len(), learning_rate, l1, l2);
227        model.n = u16::try_from(dataset.features[0].len()).unwrap();
228        model.s = dataset.stride;
229        // Each feature maps to its own column. Mapping them all to 0 (as this did) makes
230        // the map useless for `reduce`, and makes `evaluate_file` record every n-gram it
231        // finds into column 0.
232        model.features = dataset
233            .features
234            .iter()
235            .enumerate()
236            .map(|(index, feature)| (feature.clone(), index))
237            .collect::<FxHashMap<_, _>>();
238        let result = model.train(epochs, dataset).unwrap();
239        let train_performance = model.evaluate_dataset(dataset).unwrap();
240        model.file_type = dataset.ftype;
241        model.train_performance = train_performance.into();
242
243        // `n` is the n-gram size in bytes, not a column count, so comparing it to the test
244        // set's width meant the test performance was only ever computed for a dataset that
245        // happened to have exactly `n` features.
246        if let Some(test) = test
247            && dataset.ftype == test.ftype
248            && test.data.row_len() == model.weights.len()
249            && let Ok(test_performance) = model.evaluate_dataset(test)
250        {
251            model.test_performance = Some(test_performance.into());
252        }
253
254        (model, result)
255    }
256
257    /// Predicts the output for a given input row.
258    ///
259    /// Features beyond the end of the weights vector are ignored, so a row longer than the
260    /// model is silently truncated rather than panicking.
261    #[inline]
262    #[must_use]
263    pub fn predict(&self, input: RowSlice<'_>) -> f32 {
264        sigmoid(input.dot(&self.weights) + self.bias)
265    }
266
267    /// Map each of a dataset's feature columns to the weight that scores it.
268    ///
269    /// Columns whose n-gram the model doesn't carry map to `u32::MAX` and contribute nothing,
270    /// which is correct: the model dropped those features during training.
271    ///
272    /// # Errors
273    ///
274    /// Returns an error unless every feature the model carries is present in the dataset. The
275    /// dataset having extra features is fine — ignoring them is the point of reducing — but a
276    /// model weight with no column behind it would silently contribute nothing.
277    fn column_to_weight<D: TrainingData>(&self, dataset: &D) -> Result<Vec<u32>> {
278        let mut mapping = vec![u32::MAX; dataset.row_len()];
279        // Which of the model's weights the dataset actually supplies a column for.
280        let mut supplied = vec![false; self.weights.len()];
281        let mut covered = 0usize;
282
283        for (column, feature) in dataset.features().iter().enumerate() {
284            if let Some(weight_index) = self.features.get(feature)
285                && *weight_index < self.weights.len()
286                && let Ok(narrowed) = u32::try_from(*weight_index)
287                && let Some(slot) = mapping.get_mut(column)
288            {
289                *slot = narrowed;
290                // Counted once per weight, so a dataset that lists an n-gram twice cannot
291                // inflate the coverage.
292                if let Some(flag) = supplied.get_mut(*weight_index)
293                    && !*flag
294                {
295                    *flag = true;
296                    covered += 1;
297                }
298            }
299        }
300
301        let missing = self.features.len().saturating_sub(covered);
302        ensure!(
303            missing == 0,
304            "The dataset is missing {missing} of the model's {} n-gram features. Every feature \
305             the model carries has to be present, otherwise its weight contributes nothing and \
306             the score is wrong. The dataset has {} features, so it was probably built from a \
307             different n-gram set.",
308            self.features.len(),
309            dataset.features().len()
310        );
311
312        Ok(mapping)
313    }
314
315    /// Predict for a row whose columns are mapped onto the weights by [`Self::column_to_weight`].
316    #[must_use]
317    fn predict_mapped(&self, input: RowSlice<'_>, mapping: &[u32]) -> f32 {
318        let linear_model = input
319            .indices()
320            .iter()
321            .filter_map(|column| mapping.get(*column as usize).copied())
322            .filter(|weight_index| *weight_index != u32::MAX)
323            .filter_map(|weight_index| self.weights.get(weight_index as usize))
324            .sum::<f32>();
325        sigmoid(linear_model + self.bias)
326    }
327
328    /// Trains the classifier once with the given inputs and outputs.
329    ///
330    /// A mutable reference is required because the dataset is shuffled in place each epoch.
331    ///
332    /// # Errors
333    ///
334    /// Returns an error if the data isn't the correct size or if labels are missing.
335    #[allow(clippy::cast_precision_loss)]
336    pub fn train<D: TrainingData>(
337        &mut self,
338        epochs: u32,
339        dataset: &mut D,
340    ) -> Result<f32, &'static str> {
341        if !dataset.has_labels() {
342            return Err("Dataset must have labels");
343        }
344
345        if !dataset.validate() {
346            return Err("Dataset didn't pass validity check!");
347        }
348
349        if dataset.row_len() != self.weights.len() {
350            return Err("Dataset feature length must equal the number of model weights");
351        }
352
353        self.n = u16::try_from(dataset.features().first().map_or(0, Vec::len))
354            .map_err(|_| "N-gram size is unexpectedly large")?;
355
356        // The bar counts samples across the whole run, so its ETA covers every epoch rather
357        // than resetting each one. Converging early just finishes it short.
358        let progress = (dataset.len() >= PROGRESS_MIN_ROWS)
359            .then(|| training_progress_bar(u64::from(epochs) * dataset.len() as u64, epochs));
360        let mut done = 0u64;
361
362        let mut loss = 0.0;
363        #[allow(unused)]
364        for epoch in 0..epochs {
365            loss = 0.0;
366            dataset.shuffle();
367            for (input, output) in dataset.labelled_rows() {
368                let output = f32::from(output);
369                let prediction = self.predict(input);
370                let error = prediction - output;
371                let p = prediction.clamp(LOSS_EPSILON, 1.0 - LOSS_EPSILON);
372                loss += -output * p.ln() - (1.0 - output) * (1.0 - p).ln();
373
374                // The update splits in two: the regularization terms apply to every weight
375                // regardless of the input, while the error term only applies where the
376                // input feature is non-zero. Since rows are a few percent dense, keeping
377                // those separate turns the error term from a pass over all the weights into
378                // a pass over the row's set features.
379                //
380                // The regularization pass is chunked across threads rather than using
381                // `par_iter_mut().enumerate()` per weight: the old version paid rayon's
382                // fork/join and per-element indexing cost once per weight per sample.
383                //
384                // The decay may shrink a weight to zero but never carry it past. Unclamped, a
385                // weight with no signal overshoots zero and then bounces between
386                // `±learning_rate * l1 / 2` forever (`signum` of zero is one, so zero isn't a
387                // resting point either), which left L1 unable to produce a single zero weight.
388                let (learning_rate, l1, l2) = (self.learning_rate, self.l1, self.l2);
389                self.weights.par_chunks_mut(WEIGHT_CHUNK).for_each(|chunk| {
390                    for weight in chunk {
391                        let l1r = l1 * weight.signum();
392                        let l2r = l2 * *weight;
393                        let decayed = *weight - learning_rate * (l1r + l2r);
394                        let same_side =
395                            (*weight > 0.0 && decayed > 0.0) || (*weight < 0.0 && decayed < 0.0);
396                        *weight = if same_side { decayed } else { 0.0 };
397                    }
398                });
399
400                let step = learning_rate * error;
401                for (index, value) in input.iter_nonzero() {
402                    if let Some(weight) = self.weights.get_mut(index) {
403                        *weight -= step * value;
404                    }
405                }
406
407                self.bias -= self.learning_rate * error;
408
409                done += 1;
410                if let Some(bar) = &progress
411                    && done.is_multiple_of(PROGRESS_UPDATE_SAMPLES)
412                {
413                    bar.set_position(done);
414                }
415            }
416            // Mean loss per *sample*. Dividing by the weight count instead scaled the loss
417            // by an arbitrary factor — with 110,000 features and 300,000 rows it reads 2.8x
418            // too small, which also makes the `loss < 1e-6` early stop below fire early.
419            loss /= dataset.len() as f32;
420
421            if let Some(bar) = &progress {
422                // Also the only place the loss is visible in a release build.
423                bar.set_position(done);
424                bar.set_message(format!("Epoch {}/{epochs}, loss {loss:.6}", epoch + 1));
425            }
426
427            #[cfg(debug_assertions)]
428            {
429                let line = format!("Epoch: {epoch}, Log loss: {loss}");
430                // Printing straight to stdout would tear the bar's line.
431                match &progress {
432                    Some(bar) => bar.println(line),
433                    None => println!("{line}"),
434                }
435            }
436
437            if loss < 1e-6 {
438                break;
439            }
440        }
441
442        if let Some(bar) = progress {
443            bar.finish_and_clear();
444        }
445
446        self.trained = true;
447        self.file_type = dataset.file_type();
448        self.s = dataset.stride();
449        self.created = Timestamp::now();
450        if let Ok(confusion_matrix) = self.evaluate_dataset(dataset) {
451            self.train_performance = confusion_matrix.into();
452        }
453        Ok(loss)
454    }
455
456    /// A complete training run: train, drop the features regularization found unnecessary,
457    /// then record the performance on the training data and, if given, on test data.
458    ///
459    /// The `train` command and every cross validation fold go through this, so a fold's
460    /// model is built exactly as a regular one would be.
461    ///
462    /// # Errors
463    ///
464    /// Returns an error if training fails (see [`Self::train`]), or if either dataset can't be
465    /// evaluated, for example because the test data has a different file type.
466    pub fn fit<T: TrainingData, E: TrainingData>(
467        &mut self,
468        epochs: u32,
469        train: &mut T,
470        test: Option<&E>,
471    ) -> Result<TrainingRun> {
472        let loss = self.train(epochs, train).map_err(|e| anyhow!(e))?;
473
474        // Reduce before measuring, so the recorded performance is the saved model's.
475        let features_removed = self.set_features_and_reduce(train)?;
476        self.train_performance = self.evaluate_dataset(train)?.into();
477        self.test_performance = match test {
478            Some(test) => Some(self.evaluate_dataset(test)?.into()),
479            None => None,
480        };
481
482        Ok(TrainingRun {
483            loss,
484            features_removed,
485        })
486    }
487
488    /// Evaluate a dataset
489    ///
490    /// # Errors
491    ///
492    /// If the dataset doesn't match the model weight length or doesn't have labels
493    pub fn evaluate_dataset<D: TrainingData>(&self, dataset: &D) -> Result<ConfusionMatrix> {
494        ensure!(!dataset.is_empty(), "Dataset is empty");
495        ensure!(dataset.has_labels(), "Dataset labels is empty");
496        ensure!(
497            self.file_type == dataset.file_type(),
498            "Dataset file type must match model file type"
499        );
500
501        // Align the dataset's columns to the model's weights by n-gram wherever both sides name
502        // their features. Training ends by dropping the features it found unnecessary, so a
503        // saved model is narrower than the dataset it was trained on and the two no longer line
504        // up positionally — insisting that they do made every model `train` wrote unusable
505        // against the dataset it came from.
506        let mapping = if self.features.is_empty() || dataset.features().is_empty() {
507            ensure!(
508                dataset.row_len() == self.weights.len(),
509                "Dataset has {} features but the model has {} weights, and one of them lists no \
510                 n-grams to align them by.",
511                dataset.row_len(),
512                self.weights.len()
513            );
514            None
515        } else {
516            Some(self.column_to_weight(dataset)?)
517        };
518
519        let mut tp_ = 0;
520        let mut fp_ = 0;
521        let mut tn_ = 0;
522        let mut fn_ = 0;
523        let mut predictions = Vec::with_capacity(dataset.len());
524        let mut labels = Vec::with_capacity(dataset.len());
525
526        // Taking each row with its label keeps the two in step without indexing either: no
527        // bounds check per label, and no way for a skipped row to silently desynchronise
528        // `predictions` from `labels`, which `auc` later zips together.
529        for (row, label) in dataset.labelled_rows() {
530            let prediction = match &mapping {
531                Some(mapping) => self.predict_mapped(row, mapping),
532                None => self.predict(row),
533            };
534
535            match (prediction >= 0.5, label >= 1) {
536                (true, true) => tp_ += 1,
537                (true, false) => fp_ += 1,
538                (false, false) => tn_ += 1,
539                (false, true) => fn_ += 1,
540            }
541
542            predictions.push(prediction);
543            labels.push(label);
544        }
545
546        Ok(ConfusionMatrix {
547            true_p: tp_,
548            true_n: tn_,
549            false_p: fp_,
550            false_n: fn_,
551            labels,
552            predictions,
553        })
554    }
555
556    /// Evaluate a file
557    ///
558    /// # Errors
559    ///
560    /// Errors will result if the model doesn't have features or if the sample file can't be read
561    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
562    pub fn evaluate_file<P: AsRef<Path>>(&self, path: P) -> Result<(&'static str, f32, u32)> {
563        ensure!(
564            !self.features.is_empty(),
565            "Features are required for file evaluation"
566        );
567
568        ensure!(
569            self.file_type.matches_path(&path)?,
570            "File type doesn't match model type"
571        );
572
573        let vector = crate::dataset::featurize_file(path, self.n, &self.features)?;
574        let result = self.predict(vector.as_slice());
575        let features = vector.count_nonzero() as u32;
576        if result > 0.5 {
577            Ok(("Malicious", result, features))
578        } else {
579            Ok(("Benign", result, features))
580        }
581    }
582
583    /// Remove small weights (from regularization), returns the number of weights removed
584    ///
585    /// # Errors
586    ///
587    /// There's an error if the model is not trained
588    #[allow(clippy::cast_precision_loss)]
589    pub fn reduce<D: TrainingData>(&mut self, dataset: &D) -> Result<usize> {
590        const THRESHOLD: f32 = 0.01;
591
592        ensure!(
593            self.trained,
594            "Model must be trained before reducing weights"
595        );
596        ensure!(
597            self.file_type == dataset.file_type(),
598            "Dataset file type must match model file type"
599        );
600
601        // One pass for every column sum, rather than a strided pass per column.
602        let column_sums = dataset.column_sums();
603        ensure!(
604            column_sums.len() >= self.weights.len(),
605            "Dataset has {} features but the model has {} weights",
606            column_sums.len(),
607            self.weights.len()
608        );
609
610        let row_count = dataset.len() as f32;
611        let mut average_features = Vec::with_capacity(self.weights.len());
612        for (index, model_weight) in self.weights.iter().enumerate() {
613            average_features.push((index, (model_weight * column_sums[index] / row_count).abs()));
614        }
615
616        average_features.sort_by(|(_, a), (_, b)| {
617            if a > b {
618                Ordering::Greater
619            } else if a < b {
620                Ordering::Less
621            } else {
622                Ordering::Equal
623            }
624        });
625
626        let mut removed = vec![];
627        let mut running_sum = 0.0;
628        for (index, weight) in average_features {
629            running_sum += weight;
630            if running_sum < THRESHOLD {
631                removed.push(index);
632            }
633        }
634
635        let removed_len = removed.len();
636
637        // Build the old-index -> new-index mapping once, then rebuild the weights in a
638        // single pass. Calling `Vec::remove` per dropped index is quadratic, and searching
639        // the whole feature map per dropped index (as this did) is quadratic again — with
640        // 100,000 features dropped that is on the order of 10^10 map walks.
641        let mut dropped = vec![false; self.weights.len()];
642        for index in &removed {
643            if let Some(flag) = dropped.get_mut(*index) {
644                *flag = true;
645            }
646        }
647
648        let mut new_index_of = vec![None; self.weights.len()];
649        let mut next_index = 0;
650        for (old_index, is_dropped) in dropped.iter().enumerate() {
651            if !is_dropped {
652                new_index_of[old_index] = Some(next_index);
653                next_index += 1;
654            }
655        }
656
657        let mut kept_weights = Vec::with_capacity(next_index);
658        for (old_index, weight) in self.weights.iter().enumerate() {
659            if !dropped[old_index] {
660                kept_weights.push(*weight);
661            }
662        }
663        self.weights = kept_weights;
664
665        // Renumber the surviving features to their new columns. Dropping weights without
666        // doing this left every remaining feature pointing at its old column, so the model's
667        // feature map no longer lined up with its own weights.
668        if !self.features.is_empty() {
669            self.features
670                .retain(|_, index| new_index_of.get(*index).copied().flatten().is_some());
671            for index in self.features.values_mut() {
672                if let Some(Some(new_index)) = new_index_of.get(*index).copied() {
673                    *index = new_index;
674                }
675            }
676        }
677
678        Ok(removed_len)
679    }
680
681    /// Set the features by adding to the struct
682    ///
683    /// # Errors
684    ///
685    /// Returns an error if the number of weights and features doesn't match
686    pub fn set_features(&mut self, features: Vec<Bytes>) -> Result<()> {
687        ensure!(
688            features.len() == self.weights.len(),
689            "Provided features length {} does not equal the number of model features length {}",
690            features.len(),
691            self.weights.len()
692        );
693        self.features = features
694            .into_iter()
695            .enumerate()
696            .map(|(f, i)| (i, f))
697            .collect::<FxHashMap<_, _>>();
698
699        Ok(())
700    }
701
702    /// Convenience function to get the features from the dataset then reduce based on the dataset.
703    ///
704    /// # Errors
705    ///
706    /// An error occurs if the conditions below aren't met:
707    /// * Ensures the number of model weights matches the dataset features
708    /// * Ensures the file types match
709    pub fn set_features_and_reduce<D: TrainingData>(&mut self, dataset: &D) -> Result<usize> {
710        ensure!(
711            self.file_type == dataset.file_type(),
712            "Dataset file type must match model file type"
713        );
714        ensure!(
715            dataset.row_len() == self.weights.len(),
716            "Dataset length must equal the number of model weights"
717        );
718
719        self.features = dataset
720            .features()
721            .iter()
722            .enumerate()
723            .map(|(f, i)| (i.clone(), f))
724            .collect::<FxHashMap<_, _>>();
725
726        self.reduce(dataset)
727    }
728
729    /// Set the features by creating a new struct which has the features
730    ///
731    /// # Errors
732    ///
733    /// Returns an error if the number of weights and features doesn't match
734    pub fn with_features(self, features: Vec<Bytes>) -> Result<Self> {
735        ensure!(
736            features.len() == self.weights.len(),
737            "Provided features length {} does not equal the number of model features length {}",
738            features.len(),
739            self.weights.len()
740        );
741
742        Ok(Self {
743            learning_rate: self.learning_rate,
744            bias: self.bias,
745            weights: self.weights,
746            l1: self.l1,
747            l2: self.l2,
748            trained: self.trained,
749            original_ngrams: self.original_ngrams,
750            file_type: self.file_type,
751            n: self.n,
752            s: self.s,
753            created: self.created,
754            train_performance: self.train_performance,
755            test_performance: self.test_performance,
756            features: features
757                .into_iter()
758                .enumerate()
759                .map(|(f, i)| (i, f))
760                .collect::<FxHashMap<_, _>>(),
761        })
762    }
763
764    /// Save a model to disk.
765    ///
766    /// # Errors
767    ///
768    /// An error occurs if the file type isn't Json or Toml, or if a file
769    /// cannot be created or written.
770    pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<()> {
771        use std::io::Write;
772
773        let Some(ext) = path.as_ref().extension().and_then(|ext| ext.to_str()) else {
774            bail!("File {} has no extension", path.as_ref().display());
775        };
776
777        match ext.to_ascii_lowercase().as_str() {
778            "json" => {
779                let file = File::create(path)?;
780                let mut writer = std::io::BufWriter::with_capacity(1 << 20, file);
781                serde_json::to_writer_pretty(&mut writer, self)?;
782                writer.flush()?;
783                writer.into_inner()?.sync_all()?;
784            }
785            "toml" => {
786                let serialized = toml::to_string_pretty(self)?;
787                std::fs::write(path, serialized)?;
788            }
789            "bin" | "model" => {
790                let mut buffer = BufWriter::new(File::create(path)?);
791                self.to_bytes(&mut buffer)?;
792                buffer.flush()?;
793            }
794            ext => bail!("Unsupported file extension: {ext}"),
795        }
796
797        Ok(())
798    }
799
800    /// Write the model as raw bytes. See [`LogisticRegression::from_bytes`]
801    /// for the data format.
802    ///
803    /// # Errors
804    ///
805    /// Errors result if data cannot be written to the destination.
806    #[allow(clippy::cast_possible_truncation)]
807    pub fn to_bytes<W: Write>(&self, writer: &mut W) -> Result<()> {
808        ensure!(
809            self.n > 1 && self.trained,
810            "Refusing to save an untrained model!"
811        );
812        writer.write_all(&LogisticRegression::MAGIC_NUMBER)?;
813        writer.write_all(&LogisticRegression::VERSION.to_be_bytes())?;
814
815        writer.write_all(&self.n.to_be_bytes())?;
816        writer.write_all(&self.s.to_be_bytes())?;
817        let k = self.features.len() as u32;
818        writer.write_all(&k.to_be_bytes())?;
819
820        for (ngram, index) in &self.features {
821            writer.write_all(ngram)?;
822            let position = *index as u32;
823            writer.write_all(&position.to_be_bytes())?;
824            writer.write_all(&self.weights[*index].to_be_bytes())?;
825        }
826        writer.write_all(&self.original_ngrams.to_be_bytes())?;
827        let timestamp = self.created.as_second().cast_unsigned();
828        writer.write_all(&timestamp.to_be_bytes())?;
829        let ftype_string = self.file_type.to_string();
830        writer.write_all(&(ftype_string.len() as u32).to_be_bytes())?;
831        writer.write_all(&ftype_string.into_bytes())?;
832
833        writer.write_all(&self.learning_rate.to_be_bytes())?;
834        writer.write_all(&self.bias.to_be_bytes())?;
835        writer.write_all(&self.l1.to_be_bytes())?;
836        writer.write_all(&self.l2.to_be_bytes())?;
837
838        writer.write_all(&self.train_performance.true_positives.to_be_bytes())?;
839        writer.write_all(&self.train_performance.true_negatives.to_be_bytes())?;
840        writer.write_all(&self.train_performance.false_positives.to_be_bytes())?;
841        writer.write_all(&self.train_performance.false_negatives.to_be_bytes())?;
842        writer.write_all(&self.train_performance.auc.to_be_bytes())?;
843
844        if let Some(stats) = self.test_performance {
845            writer.write_all(&LogisticRegression::HAS_TEST_STATS.to_be_bytes())?;
846            writer.write_all(&stats.true_positives.to_be_bytes())?;
847            writer.write_all(&stats.true_negatives.to_be_bytes())?;
848            writer.write_all(&stats.false_positives.to_be_bytes())?;
849            writer.write_all(&stats.false_negatives.to_be_bytes())?;
850            writer.write_all(&stats.auc.to_be_bytes())?;
851        } else {
852            writer.write_all(&LogisticRegression::WITHOUT_TEST_STATS.to_be_bytes())?;
853        }
854
855        writer.flush().map_err(Into::into)
856    }
857
858    /// Byte format (all values in [Big Endian](https://en.wikipedia.org/wiki/Endianness)):
859    ///
860    /// * Magic Number [`LogisticRegression::MAGIC_NUMBER`], 4 bytes
861    /// * Version number, 2 bytes, int
862    /// * Size of n-grams, 2 bytes, int
863    /// * N-gram stride, 2 bytes, int
864    /// * Number of n-grams, 4 bytes, int
865    /// * For each n-gram:
866    ///   * N-gram bytes (size of n)
867    ///   * N-gram index, 4 bytes, int
868    ///   * Weight, 4 bytes
869    /// * Original number of n-grams, 4 bytes, int
870    /// * Model creation timestamp, 8 bytes, int
871    /// * String size of the file type, 4 bytes, int
872    /// * String bytes for the file type, size is above length
873    /// * Learning rate, 4 bytes, float
874    /// * Bias, 4 bytes, float
875    /// * L1 regularization, 4 bytes, float
876    /// * L2 regularization, 4 bytes, float
877    /// * Model's training performance stats:
878    ///     * True Positives, 4 bytes, int
879    ///     * True Negatives, 4 bytes, int
880    ///     * False Positives, 4 bytes, int
881    ///     * False Negatives, 4 bytes, int
882    ///     * AUC, 4 bytes, float
883    /// * Flag indicating presence of test performance stats, 1 byte
884    /// * If flag == [`LogisticRegression::HAS_TEST_STATS`]:
885    ///     * True Positives, 4 bytes, int
886    ///     * True Negatives, 4 bytes, int
887    ///     * False Positives, 4 bytes, int
888    ///     * False Negatives, 4 bytes, int
889    ///     * AUC, 4 bytes, float
890    ///
891    /// # Errors
892    ///
893    /// Errors result if the data cannot be read or if the data is too short.
894    #[allow(clippy::cast_precision_loss, clippy::too_many_lines)]
895    pub fn from_bytes<R: Read>(reader: &mut R) -> Result<Self> {
896        let mut magic = [0; LogisticRegression::MAGIC_NUMBER.len()];
897        reader.read_exact(&mut magic)?;
898        ensure!(
899            magic == LogisticRegression::MAGIC_NUMBER,
900            "Invalid magic number"
901        );
902        let mut version = [0; 2];
903        reader.read_exact(&mut version)?;
904        ensure!(
905            u16::from_be_bytes(version) == LogisticRegression::VERSION,
906            "Invalid version"
907        );
908
909        let mut two_bytes = [0; 2];
910        let mut four_bytes = [0; 4];
911        reader.read_exact(&mut two_bytes)?;
912        let n = u16::from_be_bytes(two_bytes);
913        reader.read_exact(&mut two_bytes)?;
914        let s = u16::from_be_bytes(two_bytes);
915        reader.read_exact(&mut four_bytes)?;
916        let k = u32::from_be_bytes(four_bytes);
917
918        let mut ngram = vec![0; n as usize];
919        let mut features =
920            FxHashMap::with_capacity_and_hasher(k as usize, BuildHasherDefault::default());
921        let mut weights = vec![0.0; k as usize];
922        for _ in 0..k {
923            reader.read_exact(&mut ngram)?;
924            reader.read_exact(&mut four_bytes)?;
925            let index = u32::from_be_bytes(four_bytes);
926            features.insert(ngram.clone(), index as usize);
927            reader.read_exact(&mut four_bytes)?;
928            if let Some(w) = weights.get_mut(index as usize) {
929                *w = f32::from_be_bytes(four_bytes);
930            } else {
931                bail!("Invalid weight index {index}");
932            }
933        }
934
935        reader.read_exact(&mut four_bytes)?;
936        let original_ngrams = u32::from_be_bytes(four_bytes);
937
938        let mut eight_bytes = [0u8; 8];
939        reader.read_exact(&mut eight_bytes)?;
940        let timestamp = u64::from_be_bytes(eight_bytes);
941
942        reader.read_exact(&mut four_bytes)?;
943        let string_len = u32::from_be_bytes(four_bytes) as usize;
944        let mut string = vec![0; string_len];
945        reader.read_exact(&mut string)?;
946        let ftype = String::from_utf8(string)?;
947        let file_type =
948            FileType::from_name(&ftype).ok_or_else(|| anyhow!("Unknown file type `{ftype}`!"))?;
949
950        reader.read_exact(&mut four_bytes)?;
951        let learning_rate = f32::from_be_bytes(four_bytes);
952        reader.read_exact(&mut four_bytes)?;
953        let bias = f32::from_be_bytes(four_bytes);
954        reader.read_exact(&mut four_bytes)?;
955        let l1 = f32::from_be_bytes(four_bytes);
956        reader.read_exact(&mut four_bytes)?;
957        let l2 = f32::from_be_bytes(four_bytes);
958
959        reader.read_exact(&mut four_bytes)?;
960        let true_positives = u32::from_be_bytes(four_bytes);
961        reader.read_exact(&mut four_bytes)?;
962        let true_negatives = u32::from_be_bytes(four_bytes);
963        reader.read_exact(&mut four_bytes)?;
964        let false_positives = u32::from_be_bytes(four_bytes);
965        reader.read_exact(&mut four_bytes)?;
966        let false_negatives = u32::from_be_bytes(four_bytes);
967        let mut recall = true_positives as f32 / (true_positives + false_negatives) as f32;
968        let mut precision = true_positives as f32 / (true_positives + false_positives) as f32;
969        let mut f1 = 2.0 * (precision * recall) / (precision + recall);
970        if !recall.is_normal() {
971            recall = 0.0;
972        }
973        if !precision.is_normal() {
974            precision = 0.0;
975        }
976        if !f1.is_normal() {
977            f1 = 0.0;
978        }
979
980        reader.read_exact(&mut four_bytes)?;
981        let auc = f32::from_be_bytes(four_bytes);
982
983        let mut one_byte = [0u8; 1];
984        reader.read_exact(&mut one_byte)?;
985        let test_performance = if one_byte[0] == LogisticRegression::HAS_TEST_STATS {
986            let mut test_performance = PerformanceStats::default();
987            reader.read_exact(&mut four_bytes)?;
988            test_performance.true_positives = u32::from_be_bytes(four_bytes);
989            reader.read_exact(&mut four_bytes)?;
990            test_performance.true_negatives = u32::from_be_bytes(four_bytes);
991            reader.read_exact(&mut four_bytes)?;
992            test_performance.false_positives = u32::from_be_bytes(four_bytes);
993            reader.read_exact(&mut four_bytes)?;
994            test_performance.false_negatives = u32::from_be_bytes(four_bytes);
995            reader.read_exact(&mut four_bytes)?;
996            test_performance.auc = f32::from_be_bytes(four_bytes);
997
998            test_performance.recall = test_performance.true_positives as f32
999                / (test_performance.true_positives + test_performance.false_negatives) as f32;
1000            test_performance.precision = test_performance.true_positives as f32
1001                / (test_performance.true_positives + test_performance.false_positives) as f32;
1002            test_performance.f1 = 2.0 * (test_performance.precision * test_performance.recall)
1003                / (test_performance.precision + test_performance.recall);
1004
1005            if !test_performance.precision.is_normal() {
1006                test_performance.precision = 0.0;
1007            }
1008            if !test_performance.recall.is_normal() {
1009                test_performance.recall = 0.0;
1010            }
1011            if !test_performance.f1.is_normal() {
1012                test_performance.f1 = 0.0;
1013            }
1014
1015            Some(test_performance)
1016        } else {
1017            None
1018        };
1019
1020        Ok(Self {
1021            learning_rate,
1022            bias,
1023            weights,
1024            l1,
1025            l2,
1026            features,
1027            n,
1028            s,
1029            created: Timestamp::from_second(i64::try_from(timestamp)?)?,
1030            trained: true,
1031            original_ngrams,
1032            file_type,
1033            train_performance: PerformanceStats {
1034                true_positives,
1035                true_negatives,
1036                false_positives,
1037                false_negatives,
1038                recall,
1039                precision,
1040                f1,
1041                auc,
1042            },
1043            test_performance,
1044        })
1045    }
1046}
1047
1048impl From<LogisticRegression> for Ngrammer {
1049    #[inline]
1050    fn from(l: LogisticRegression) -> Self {
1051        let ngrams =
1052            dashmap::DashMap::with_capacity_and_hasher(l.features.len(), FxBuildHasher::default());
1053        for (ngram, index) in l.features {
1054            ngrams.insert(ngram, index);
1055        }
1056
1057        Ngrammer {
1058            n: l.n,
1059            k: ngrams.len(),
1060            s: 1,
1061            keep_below: u64::MAX,
1062            paths: vec![],
1063            ftype: l.file_type,
1064            ngrams,
1065        }
1066    }
1067}
1068
1069impl From<LogisticRegression> for NgramsFile {
1070    #[inline]
1071    fn from(l: LogisticRegression) -> Self {
1072        NgramsFile {
1073            ngrams: l.features,
1074            ftype: l.file_type,
1075            n: l.n,
1076            s: l.s,
1077        }
1078    }
1079}
1080
1081/// Outcome of [`LogisticRegression::fit`]
1082#[derive(Debug, Clone, Copy, PartialEq)]
1083pub struct TrainingRun {
1084    /// Mean log loss of the final epoch
1085    pub loss: f32,
1086
1087    /// Features dropped after training
1088    pub features_removed: usize,
1089}
1090
1091/// Model performance statistics
1092#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
1093pub struct PerformanceStats {
1094    /// True positives
1095    pub true_positives: u32,
1096
1097    /// True negatives
1098    pub true_negatives: u32,
1099
1100    /// False positives
1101    pub false_positives: u32,
1102
1103    /// False negatives
1104    pub false_negatives: u32,
1105
1106    /// Recall
1107    pub recall: f32,
1108
1109    /// Precision
1110    pub precision: f32,
1111
1112    /// F1
1113    pub f1: f32,
1114
1115    /// AUC
1116    pub auc: f32,
1117}
1118
1119impl PerformanceStats {
1120    /// Accuracy as correct vs total
1121    #[inline]
1122    #[must_use]
1123    #[allow(clippy::cast_precision_loss)]
1124    pub fn accuracy(&self) -> f32 {
1125        (self.true_positives + self.true_negatives) as f32
1126            / (self.true_positives
1127                + self.true_negatives
1128                + self.false_negatives
1129                + self.false_positives) as f32
1130    }
1131
1132    /// Precision
1133    #[must_use]
1134    #[allow(clippy::cast_precision_loss)]
1135    pub fn precision(&self) -> f32 {
1136        self.true_positives as f32 / (self.true_positives + self.false_positives) as f32
1137    }
1138
1139    /// Recall
1140    #[must_use]
1141    #[allow(clippy::cast_precision_loss)]
1142    pub fn recall(&self) -> f32 {
1143        self.true_positives as f32 / (self.true_positives + self.false_negatives) as f32
1144    }
1145
1146    /// F1 score
1147    #[must_use]
1148    #[allow(clippy::cast_precision_loss)]
1149    pub fn f1(&self) -> f32 {
1150        2.0 * (self.precision() * self.recall()) / (self.precision() + self.recall())
1151    }
1152}
1153
1154impl std::fmt::Display for PerformanceStats {
1155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1156        const WIDTH: usize = 10;
1157
1158        writeln!(f, "Result \\ Actual  |    Malicious   |  Benign")?;
1159        writeln!(
1160            f,
1161            "   Malicious     |     {:<WIDTH$} |    {:<WIDTH$}",
1162            self.true_positives, self.false_positives
1163        )?;
1164        writeln!(
1165            f,
1166            "   Benign        |     {:<WIDTH$} |    {:<WIDTH$}",
1167            self.false_negatives, self.true_negatives
1168        )
1169    }
1170}
1171
1172impl From<ConfusionMatrix> for PerformanceStats {
1173    fn from(value: ConfusionMatrix) -> Self {
1174        PerformanceStats {
1175            true_positives: value.true_p,
1176            true_negatives: value.true_n,
1177            false_positives: value.false_p,
1178            false_negatives: value.false_n,
1179            recall: value.recall(),
1180            precision: value.precision(),
1181            f1: value.f1(),
1182            auc: value.auc(),
1183        }
1184    }
1185}
1186
1187/// Confusion Matrix
1188#[derive(Debug, Clone, PartialEq)]
1189pub struct ConfusionMatrix {
1190    /// True positives
1191    pub true_p: u32,
1192
1193    /// True negatives
1194    pub true_n: u32,
1195
1196    /// False positives
1197    pub false_p: u32,
1198
1199    /// False negatives
1200    pub false_n: u32,
1201
1202    /// Labels of the evaluated rows, in the same order as `predictions`.
1203    ///
1204    /// Owned rather than borrowed from the dataset, since a cross validation fold's labels
1205    /// aren't contiguous in the dataset it borrows from.
1206    labels: Vec<u8>,
1207
1208    /// Model's outputs
1209    predictions: Vec<f32>,
1210}
1211
1212impl ConfusionMatrix {
1213    /// Accuracy as correct vs total
1214    #[inline]
1215    #[must_use]
1216    #[allow(clippy::cast_precision_loss)]
1217    pub fn accuracy(&self) -> f32 {
1218        (self.true_p + self.true_n) as f32 / self.total() as f32
1219    }
1220
1221    /// Precision
1222    #[must_use]
1223    #[allow(clippy::cast_precision_loss)]
1224    pub fn precision(&self) -> f32 {
1225        self.true_p as f32 / (self.true_p + self.false_p) as f32
1226    }
1227
1228    /// Recall
1229    #[must_use]
1230    #[allow(clippy::cast_precision_loss)]
1231    pub fn recall(&self) -> f32 {
1232        self.true_p as f32 / (self.true_p + self.false_n) as f32
1233    }
1234
1235    /// F1 score
1236    #[must_use]
1237    #[allow(clippy::cast_precision_loss)]
1238    pub fn f1(&self) -> f32 {
1239        2.0 * (self.precision() * self.recall()) / (self.precision() + self.recall())
1240    }
1241
1242    /// Total items evaluated
1243    #[inline]
1244    #[must_use]
1245    pub fn total(&self) -> u32 {
1246        self.true_p + self.true_n + self.false_p + self.false_n
1247    }
1248
1249    /// Calculate the area under the curve (AUC)
1250    #[must_use]
1251    #[allow(clippy::float_cmp)]
1252    pub fn auc(&self) -> f32 {
1253        // Adapted from the AUC implementation by Maciej Kula <maciej.kula@gmail.com>
1254        // https://github.com/maciejkula/rustlearn/blob/2ac052559b04860c62d7ba34c563b57a02912e4d/src/metrics/ranking.rs
1255        // The last commit was June 2020 so used here directly instead of importing the crate.
1256        // This code was also Apache 2.0 licensed.
1257
1258        // vector of pairs (score, label) - the order is switched with respect to function arguments
1259        let (mut true_positive_count, mut false_positive_count) = {
1260            let mut pairs: Vec<_> = self
1261                .predictions
1262                .iter()
1263                .copied()
1264                .zip(self.labels.iter().copied())
1265                .collect();
1266
1267            // Sort by scores in descending order
1268            pairs.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));
1269
1270            let mut score_prev = f32::NAN;
1271            // tp .. true positives, fp .. false positives
1272            let (mut tp, mut fp) = (0.0f32, 0.0f32);
1273            let (mut tps, mut fps) = (vec![], vec![]);
1274            for (score, label) in pairs {
1275                let label = f32::from(label);
1276                // `tp` and `fp` from the previous iteration are pushed onto the ROC curve only if
1277                // the `score` changed. This avoids errors due to arbitrary classification of points with
1278                // identical scores
1279                if score != score_prev {
1280                    tps.push(tp);
1281                    fps.push(fp);
1282                    score_prev = score;
1283                }
1284                tp += label;
1285                fp += 1.0 - label;
1286            }
1287            // Push the final point corresponding to the (1,1) ROC coordinates
1288            tps.push(tp);
1289            fps.push(fp);
1290            (tps, fps)
1291        };
1292
1293        let true_positives = true_positive_count[true_positive_count.len() - 1];
1294        let false_positives = false_positive_count[false_positive_count.len() - 1];
1295
1296        for (tp, fp) in true_positive_count
1297            .iter_mut()
1298            .zip(false_positive_count.iter_mut())
1299        {
1300            *tp /= true_positives;
1301            *fp /= false_positives;
1302        }
1303
1304        let mut prev_x = false_positive_count[0];
1305        let mut prev_y = true_positive_count[0];
1306        let mut integral = 0.0;
1307
1308        for (&x, &y) in false_positive_count
1309            .iter()
1310            .skip(1)
1311            .zip(true_positive_count.iter().skip(1))
1312        {
1313            integral += (x - prev_x) * (prev_y + y) / 2.0;
1314
1315            prev_x = x;
1316            prev_y = y;
1317        }
1318
1319        integral
1320    }
1321}
1322
1323impl std::fmt::Display for ConfusionMatrix {
1324    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1325        const WIDTH: usize = 10;
1326
1327        writeln!(f, "Result \\ Actual  |    Malicious   |  Benign")?;
1328        writeln!(
1329            f,
1330            "   Malicious     |     {:<WIDTH$} |    {:<WIDTH$}",
1331            self.true_p, self.false_p
1332        )?;
1333        writeln!(
1334            f,
1335            "   Benign        |     {:<WIDTH$} |    {:<WIDTH$}",
1336            self.false_n, self.true_n
1337        )
1338    }
1339}
1340
1341#[cfg(test)]
1342mod tests {
1343    use super::*;
1344    use crate::dataset::Dataset;
1345
1346    #[test]
1347    fn xor() {
1348        let mut dataset = Dataset::from_csv_string(include_str!("../testdata/xor.csv"), 6).unwrap();
1349        let mut lr = LogisticRegression::new(6, 0.2, 0.0, 0.0);
1350        lr.train(100, &mut dataset).unwrap();
1351
1352        let mut correct = 0u16;
1353        let mut incorrect = 0u16;
1354
1355        for index in 0..dataset.data.len() {
1356            println!(
1357                "Predicted: {}, Expected: {}",
1358                lr.predict(dataset.data.row(index).unwrap()),
1359                dataset.labels[index]
1360            );
1361            if (lr.predict(dataset.data.row(index).unwrap()) >= 0.5 && dataset.labels[index] >= 1)
1362                || (lr.predict(dataset.data.row(index).unwrap()) < 0.5 && dataset.labels[index] < 1)
1363            {
1364                correct += 1;
1365            } else {
1366                incorrect += 1;
1367            }
1368        }
1369
1370        println!("Correct: {correct}, Incorrect: {incorrect}");
1371        assert!(correct > incorrect);
1372
1373        let result = lr.evaluate_dataset(&dataset).unwrap();
1374        println!("{result}");
1375        println!("Accuracy: {:.2}", result.accuracy());
1376        println!("Precision: {:.2}", result.precision());
1377        println!("Recall: {:.2}", result.recall());
1378        println!("F1: {:.2}", result.f1());
1379        println!("Auc: {:.2}", result.auc());
1380    }
1381
1382    #[test]
1383    fn reduction() {
1384        const BOGUS_LEN: usize = 6;
1385
1386        let mut dataset =
1387            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();
1388        let mut lr = LogisticRegression::new(BOGUS_LEN, 0.2, 0.1, 0.1);
1389        lr.set_features(dataset.features.clone()).unwrap();
1390        lr.train(20, &mut dataset).unwrap();
1391        let cm = lr.evaluate_dataset(&dataset).unwrap();
1392        println!("{cm}");
1393        println!("Weights before reduction: {:?}", lr.weights);
1394        println!("Features before reduction: {:?}", lr.features);
1395        lr.reduce(&dataset).expect("Failed to reduce weights");
1396        println!("Weights after reduction: {:?}", lr.weights);
1397        println!("Features after reduction: {:?}", lr.features);
1398        println!("Weights from {BOGUS_LEN} to {}", lr.weights.len());
1399        assert!(
1400            lr.weights.len() < BOGUS_LEN,
1401            "** If this assertion fails, re-run the test once or twice. **"
1402        );
1403        lr.test_performance = Some(cm.into());
1404        println!("Model: {lr:?}");
1405    }
1406
1407    /// `new_from_dataset_and_train` sized the weights from the row count, so it panicked on
1408    /// any dataset that wasn't square, and mapped every feature to column 0.
1409    #[test]
1410    fn new_from_dataset_and_train_sizes_from_features() {
1411        const BOGUS_LEN: usize = 6;
1412        let mut dataset =
1413            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();
1414        assert_ne!(
1415            dataset.len(),
1416            BOGUS_LEN,
1417            "test needs a non-square dataset to be meaningful"
1418        );
1419
1420        let (model, _loss) =
1421            LogisticRegression::new_from_dataset_and_train(&mut dataset, None, 10, 0.2, 0.0, 0.0);
1422
1423        assert_eq!(model.weights.len(), BOGUS_LEN);
1424        assert_eq!(model.features.len(), BOGUS_LEN);
1425
1426        // Every feature must own a distinct column, covering 0..BOGUS_LEN.
1427        let mut columns = model.features.values().copied().collect::<Vec<_>>();
1428        columns.sort_unstable();
1429        assert_eq!(columns, (0..BOGUS_LEN).collect::<Vec<_>>());
1430    }
1431
1432    /// Aligning by n-gram must give exactly what aligning by column position gives, when the
1433    /// two happen to line up.
1434    #[test]
1435    fn mapped_evaluation_matches_positional() {
1436        const BOGUS_LEN: usize = 6;
1437
1438        let mut dataset =
1439            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();
1440        let mut model = LogisticRegression::new(BOGUS_LEN, 0.2, 0.0, 0.0);
1441        model.set_features(dataset.features.clone()).unwrap();
1442        model.train(5, &mut dataset).unwrap();
1443
1444        // Both sides name their features, so this takes the n-gram alignment path.
1445        let matrix = model.evaluate_dataset(&dataset).unwrap();
1446
1447        // The same counts via the positional `predict`.
1448        let (mut tp, mut fp, mut tn, mut negatives) = (0u32, 0u32, 0u32, 0u32);
1449        for (row, label) in dataset.data.iter().zip(&dataset.labels) {
1450            match (model.predict(row) >= 0.5, *label >= 1) {
1451                (true, true) => tp += 1,
1452                (true, false) => fp += 1,
1453                (false, false) => tn += 1,
1454                (false, true) => negatives += 1,
1455            }
1456        }
1457
1458        assert_eq!(
1459            (matrix.true_p, matrix.false_p, matrix.true_n, matrix.false_n),
1460            (tp, fp, tn, negatives)
1461        );
1462    }
1463
1464    /// Training ends by dropping features, so the model `train` writes is narrower than the
1465    /// dataset it came from. Evaluating that dataset has to work, and has to agree with first
1466    /// narrowing the dataset to match — the `dataset-convert --model` route.
1467    #[test]
1468    fn reduced_model_evaluates_the_original_dataset() {
1469        const BOGUS_LEN: usize = 6;
1470
1471        let mut dataset =
1472            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();
1473        let mut model = LogisticRegression::new(BOGUS_LEN, 0.2, 0.1, 0.1);
1474        model.set_features(dataset.features.clone()).unwrap();
1475        model.train(20, &mut dataset).unwrap();
1476
1477        let removed = model.reduce(&dataset).unwrap();
1478        assert!(removed > 0, "test needs the model to shed some features");
1479        assert!(model.weights.len() < dataset.data.row_len());
1480
1481        // The original, wider dataset against the narrowed model.
1482        let wide = model.evaluate_dataset(&dataset).unwrap();
1483        let wide_counts = (wide.true_p, wide.false_p, wide.true_n, wide.false_n);
1484
1485        // The same thing after narrowing the dataset to match the model.
1486        let mut narrowed = dataset.clone();
1487        narrowed.reduce(&model).unwrap();
1488        assert_eq!(narrowed.data.row_len(), model.weights.len());
1489        let narrow = model.evaluate_dataset(&narrowed).unwrap();
1490
1491        assert_eq!(
1492            wide_counts,
1493            (narrow.true_p, narrow.false_p, narrow.true_n, narrow.false_n),
1494            "the two routes must score the same samples the same way"
1495        );
1496    }
1497
1498    /// Only the features the model kept may influence a score. The columns it dropped are not
1499    /// in the saved model at all, so changing them must make no difference whatsoever.
1500    #[test]
1501    fn dropped_features_cannot_affect_evaluation() {
1502        use crate::row::{DataMatrix, DataRow};
1503
1504        const LEN: usize = 6;
1505
1506        let mut dataset =
1507            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), LEN).unwrap();
1508        let mut model = LogisticRegression::new(LEN, 0.2, 0.1, 0.1);
1509        model.set_features(dataset.features.clone()).unwrap();
1510        model.train(20, &mut dataset).unwrap();
1511        model.reduce(&dataset).unwrap();
1512
1513        let dropped = dataset
1514            .features
1515            .iter()
1516            .enumerate()
1517            .filter(|(_, feature)| !model.features.contains_key(*feature))
1518            .map(|(column, _)| column)
1519            .collect::<Vec<_>>();
1520        assert!(
1521            !dropped.is_empty(),
1522            "test needs the model to have dropped something"
1523        );
1524
1525        // Every dropped column set in every row, which is the largest perturbation available.
1526        let perturbed_rows = dataset
1527            .data
1528            .iter()
1529            .map(|row| {
1530                let mut new_row = DataRow::zeroed(row.len());
1531                for (column, _) in row.iter_nonzero() {
1532                    new_row.set(column, 1.0).unwrap();
1533                }
1534                for column in &dropped {
1535                    new_row.set(*column, 1.0).unwrap();
1536                }
1537                new_row
1538            })
1539            .collect::<Vec<_>>();
1540
1541        let perturbed = Dataset {
1542            data: perturbed_rows.into_iter().collect::<DataMatrix>(),
1543            labels: dataset.labels.clone(),
1544            features: dataset.features.clone(),
1545            ftype: dataset.ftype,
1546            stride: dataset.stride,
1547        };
1548
1549        let before = model.evaluate_dataset(&dataset).unwrap();
1550        let after = model.evaluate_dataset(&perturbed).unwrap();
1551
1552        assert_eq!(
1553            (before.true_p, before.false_p, before.true_n, before.false_n),
1554            (after.true_p, after.false_p, after.true_n, after.false_n),
1555            "a dropped feature changed the confusion matrix"
1556        );
1557        assert!(
1558            (before.auc() - after.auc()).abs() < 1e-6,
1559            "a dropped feature changed the AUC: {} vs {}",
1560            before.auc(),
1561            after.auc()
1562        );
1563    }
1564
1565    /// A dataset holding only *some* of the model's features used to be scored silently on the
1566    /// overlap: the missing weights contributed nothing, so the result looked plausible and was
1567    /// wrong. Partial coverage has to be refused.
1568    #[test]
1569    fn partially_covering_dataset_is_rejected() {
1570        const LEN: usize = 6;
1571
1572        let mut dataset =
1573            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), LEN).unwrap();
1574        let mut model = LogisticRegression::new(LEN, 0.2, 0.0, 0.0);
1575        model.set_features(dataset.features.clone()).unwrap();
1576        model.train(2, &mut dataset).unwrap();
1577
1578        // Same width, same file type, and five of the model's six features still present.
1579        let mut partial = dataset.clone();
1580        partial.features[3] = vec![0xF0, 0x0D];
1581
1582        let err = model.evaluate_dataset(&partial).unwrap_err().to_string();
1583        assert!(
1584            err.contains("missing 1 of the model's 6"),
1585            "unexpected error: {err}"
1586        );
1587
1588        // All six present: accepted.
1589        assert!(model.evaluate_dataset(&dataset).is_ok());
1590    }
1591
1592    /// Aligning by n-gram must not quietly score a dataset built from a different feature set.
1593    #[test]
1594    fn unrelated_feature_sets_are_rejected() {
1595        const LEN: usize = 6;
1596
1597        let mut dataset =
1598            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), LEN).unwrap();
1599        let mut model = LogisticRegression::new(LEN, 0.2, 0.0, 0.0);
1600        model.set_features(dataset.features.clone()).unwrap();
1601        model.train(2, &mut dataset).unwrap();
1602
1603        // Same width and file type, but no n-gram in common.
1604        let mut other = dataset.clone();
1605        for (index, feature) in other.features.iter_mut().enumerate() {
1606            *feature = vec![0xF0, u8::try_from(index).unwrap()];
1607        }
1608
1609        let err = model.evaluate_dataset(&other).unwrap_err().to_string();
1610        assert!(
1611            err.contains("missing") && err.contains("different n-gram set"),
1612            "unexpected error: {err}"
1613        );
1614    }
1615
1616    /// `reduce` dropped weights but left the surviving features pointing at their old
1617    /// columns, so the feature map no longer agreed with the model's own weights.
1618    #[test]
1619    fn reduce_renumbers_surviving_features() {
1620        const BOGUS_LEN: usize = 6;
1621
1622        let mut dataset =
1623            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();
1624        let mut model = LogisticRegression::new(BOGUS_LEN, 0.2, 0.1, 0.1);
1625        model.set_features(dataset.features.clone()).unwrap();
1626        model.train(20, &mut dataset).unwrap();
1627
1628        let removed = model.reduce(&dataset).unwrap();
1629        assert_eq!(model.weights.len(), BOGUS_LEN - removed);
1630        assert_eq!(model.features.len(), model.weights.len());
1631
1632        let mut columns = model.features.values().copied().collect::<Vec<_>>();
1633        columns.sort_unstable();
1634        assert_eq!(
1635            columns,
1636            (0..model.weights.len()).collect::<Vec<_>>(),
1637            "feature columns must be a dense 0..weights.len() range after reducing"
1638        );
1639    }
1640
1641    /// The loss clamp used a 1e-8 margin, which is smaller than `f32`'s spacing below 1.0,
1642    /// so `1.0 - 1e-8` rounded back to 1.0 and a saturated prediction reached `ln(0)`.
1643    /// A bad template is not an error at runtime — it silently falls back to a bar with no
1644    /// message, losing the epoch and loss — so it has to be checked here.
1645    #[test]
1646    fn progress_bar_template_parses() {
1647        assert!(
1648            indicatif::ProgressStyle::with_template(super::TRAINING_BAR_TEMPLATE).is_ok(),
1649            "training bar template is invalid: {}",
1650            super::TRAINING_BAR_TEMPLATE
1651        );
1652    }
1653
1654    #[test]
1655    #[allow(clippy::float_cmp)] // Exact comparison is the property under test.
1656    fn loss_stays_finite_when_predictions_saturate() {
1657        const BOGUS_LEN: usize = 6;
1658
1659        let mut dataset =
1660            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();
1661
1662        // Huge weights drive every sigmoid to exactly 0.0 or 1.0 in f32.
1663        let mut model = LogisticRegression::new(BOGUS_LEN, 0.0, 0.0, 0.0);
1664        model.weights = vec![1.0e30; BOGUS_LEN];
1665        model.bias = 1.0e30;
1666        assert!(
1667            model.predict(dataset.data.row(0).unwrap()) == 1.0,
1668            "expected the prediction to saturate"
1669        );
1670
1671        let loss = model.train(1, &mut dataset).unwrap();
1672        assert!(loss.is_finite(), "loss was {loss}");
1673    }
1674
1675    /// L1 has to be able to land a weight on exactly zero, since that is what `reduce` relies
1676    /// on. The decay used to step straight past zero, leaving every weight without signal
1677    /// bouncing between `±learning_rate * l1 / 2` instead.
1678    #[test]
1679    #[allow(clippy::float_cmp)] // Exact comparison is the property under test.
1680    fn l1_decay_stops_at_zero() {
1681        const BOGUS_LEN: usize = 6;
1682
1683        let mut dataset =
1684            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();
1685
1686        let mut model = LogisticRegression::new(BOGUS_LEN, 0.1, 0.1, 0.1);
1687        assert!(model.weights.iter().all(|weight| *weight == 0.0));
1688
1689        // Start off zero on both sides, some within one decay step of it and some further out.
1690        model.weights = vec![0.5, -0.5, 0.004, -0.004, 0.015, -0.015];
1691        model.train(20, &mut dataset).unwrap();
1692
1693        // Columns 3 to 5 are never set in this dataset, so they get no error term and the
1694        // regularization is all that moves them.
1695        for (index, weight) in model.weights.iter().enumerate().skip(2).take(3) {
1696            assert_eq!(
1697                *weight, 0.0,
1698                "weight {index} is {weight}, expected exactly zero"
1699            );
1700        }
1701    }
1702
1703    #[test]
1704    fn auc() {
1705        let y_true = vec![1, 1, 0, 0];
1706        let y_hat = vec![0.5, 0.2, 0.3, -1.0];
1707
1708        let confusion_matrix = ConfusionMatrix {
1709            true_p: 0,
1710            true_n: 0,
1711            false_p: 0,
1712            false_n: 0,
1713            labels: y_true,
1714            predictions: y_hat,
1715        };
1716
1717        let auc = confusion_matrix.auc();
1718        println!("Auc: {auc:.2}, expected 0.75");
1719        assert!((0.73..0.78).contains(&auc));
1720    }
1721}