Skip to main content

lib_jsl_machine_learning/
common.rs

1//! Shared building blocks: model traits, a seeded random helper and small numeric utilities.
2//!
3//! Data is stored as `ndarray` arrays: a feature matrix `x` of shape `(samples, features)` (a
4//! [`VR2D`] view) and targets as a [`VR1D`] (regression) or `&[usize]` class labels (classification).
5//!
6//! See the book entry [Foundations](https://jwkunz.github.io/lib_jsl/book/machine_learning/foundations.html).
7
8use lib_jsl_core::{ErrorsJSL, R1D, R2D, VR1D, VR2D};
9use lib_jsl_random::distributions::gaussian::gaussian_distribution_box_muller;
10use lib_jsl_random::uniform_generator::UniformGenerator;
11use lib_jsl_random::xoshiro256plusplus::Xoshiro256PlusPlus;
12
13// ANCHOR: traits
14/// A model mapping feature rows to real-valued predictions.
15pub trait Regressor {
16    fn fit(&mut self, x: VR2D, y: VR1D) -> Result<(), ErrorsJSL>;
17    fn predict(&self, x: VR2D) -> Result<R1D, ErrorsJSL>;
18}
19
20/// A model mapping feature rows to class labels `0..classes`.
21pub trait Classifier {
22    fn fit(&mut self, x: VR2D, labels: &[usize]) -> Result<(), ErrorsJSL>;
23    fn predict(&self, x: VR2D) -> Result<Vec<usize>, ErrorsJSL>;
24}
25
26/// A model that groups rows without labels. Noise points (density-based methods) get `None`.
27pub trait Clusterer {
28    fn fit_predict(&mut self, x: VR2D) -> Result<Vec<Option<usize>>, ErrorsJSL>;
29}
30
31/// A learned transformation of feature rows (scaling, projection, embedding).
32pub trait Transformer {
33    fn fit(&mut self, x: VR2D) -> Result<(), ErrorsJSL>;
34    fn transform(&self, x: VR2D) -> Result<R2D, ErrorsJSL>;
35    fn fit_transform(&mut self, x: VR2D) -> Result<R2D, ErrorsJSL> {
36        self.fit(x)?;
37        self.transform(x)
38    }
39}
40// ANCHOR_END: traits
41
42/// A small seeded random-number helper used by the stochastic algorithms.
43#[derive(Debug, Clone)]
44pub struct MlRng {
45    rng: Xoshiro256PlusPlus,
46}
47
48impl MlRng {
49    pub fn new(seed: u64) -> Self {
50        MlRng { rng: Xoshiro256PlusPlus::from_seed(seed) }
51    }
52
53    /// Uniform in `[0, 1)`.
54    pub fn uniform(&mut self) -> f64 {
55        self.rng.next_f64()
56    }
57
58    /// Uniform in `[lo, hi)`.
59    pub fn range(&mut self, lo: f64, hi: f64) -> f64 {
60        lo + (hi - lo) * self.uniform()
61    }
62
63    /// Uniform integer in `0..n` (`n > 0`).
64    pub fn below(&mut self, n: usize) -> usize {
65        ((self.uniform() * n as f64) as usize).min(n - 1)
66    }
67
68    /// A normal sample with the given mean and standard deviation.
69    pub fn gaussian(&mut self, mean: f64, sd: f64) -> f64 {
70        // Box-Muller needs u0 in (0, 1]; next_f64 returns [0, 1).
71        loop {
72            let (z, _) = gaussian_distribution_box_muller(&mut self.rng, mean, sd);
73            if z.is_finite() {
74                return z;
75            }
76        }
77    }
78
79    /// Fisher-Yates shuffle in place.
80    pub fn shuffle<T>(&mut self, items: &mut [T]) {
81        for i in (1..items.len()).rev() {
82            items.swap(i, self.below(i + 1));
83        }
84    }
85
86    /// `k` distinct indices from `0..n` (all of them, shuffled, if `k >= n`).
87    pub fn sample_indices(&mut self, n: usize, k: usize) -> Vec<usize> {
88        let mut all: Vec<usize> = (0..n).collect();
89        self.shuffle(&mut all);
90        all.truncate(k.min(n));
91        all
92    }
93}
94
95/// Squared Euclidean distance between two equal-length slices.
96pub fn squared_distance(a: &[f64], b: &[f64]) -> f64 {
97    a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum()
98}
99
100/// The rows of a matrix as owned vectors.
101pub fn rows(x: VR2D) -> Vec<Vec<f64>> {
102    x.rows().into_iter().map(|r| r.to_vec()).collect()
103}
104
105/// Checks a non-empty feature matrix with finite values.
106pub fn check_features(x: VR2D) -> Result<(), ErrorsJSL> {
107    if x.nrows() == 0 || x.ncols() == 0 {
108        return Err(ErrorsJSL::InvalidInputRange("The feature matrix must have at least one row and column."));
109    }
110    if x.iter().any(|v| !v.is_finite()) {
111        return Err(ErrorsJSL::InvalidInputRange("The feature matrix contains non-finite values."));
112    }
113    Ok(())
114}
115
116/// Checks features and a matching-length target.
117pub fn check_xy(x: VR2D, len: usize) -> Result<(), ErrorsJSL> {
118    check_features(x)?;
119    if x.nrows() != len {
120        return Err(ErrorsJSL::IncompatibleArraySizes((x.nrows(), len)));
121    }
122    Ok(())
123}
124
125/// The number of classes implied by labels (max label + 1).
126pub fn class_count(labels: &[usize]) -> usize {
127    labels.iter().max().map_or(0, |m| m + 1)
128}
129
130/// The index of the largest value (first on ties); `None` if empty or all NaN.
131pub fn argmax(values: &[f64]) -> Option<usize> {
132    values.iter().enumerate().filter(|(_, v)| !v.is_nan()).fold(None, |best: Option<(usize, f64)>, (i, &v)| match best {
133        Some((_, b)) if b >= v => best,
134        _ => Some((i, v)),
135    }).map(|(i, _)| i)
136}
137
138/// The matrix of Euclidean distances between all pairs of rows.
139pub fn pairwise_distances(x: VR2D) -> R2D {
140    let r: Vec<Vec<f64>> = rows(x);
141    let mut d = R2D::zeros((r.len(), r.len()));
142    for i in 0..r.len() {
143        for j in i + 1..r.len() {
144            let v = squared_distance(&r[i], &r[j]).sqrt();
145            d[[i, j]] = v;
146            d[[j, i]] = v;
147        }
148    }
149    d
150}