Skip to main content

lib_jsl_machine_learning/
datasets.rs

1//! Deterministic synthetic datasets for demonstrating and testing the learning algorithms.
2//!
3//! Every generator takes a seed, so results are reproducible. Feature matrices have one sample per
4//! row.
5//!
6//! See the book entry [Foundations](https://jwkunz.github.io/lib_jsl/book/machine_learning/foundations.html#synthetic-data-sets).
7
8use crate::common::MlRng;
9use lib_jsl_core::{R1D, R2D};
10use std::f64::consts::{PI, TAU};
11
12/// Gaussian blobs: `per_cluster` points around each centre with standard deviation `spread`.
13/// Returns the points and the true cluster of each.
14pub fn make_blobs(per_cluster: usize, centres: &[Vec<f64>], spread: f64, seed: u64) -> (R2D, Vec<usize>) {
15    let mut rng = MlRng::new(seed);
16    let dims = centres.first().map_or(0, Vec::len);
17    let mut x = R2D::zeros((per_cluster * centres.len(), dims));
18    let mut labels = Vec::with_capacity(x.nrows());
19    for (c, centre) in centres.iter().enumerate() {
20        for i in 0..per_cluster {
21            for (d, &mu) in centre.iter().enumerate() {
22                x[[c * per_cluster + i, d]] = rng.gaussian(mu, spread);
23            }
24            labels.push(c);
25        }
26    }
27    (x, labels)
28}
29
30/// Two interleaving half circles ("moons"): `n` points per moon with Gaussian noise.
31pub fn make_moons(n: usize, noise: f64, seed: u64) -> (R2D, Vec<usize>) {
32    let mut rng = MlRng::new(seed);
33    let mut x = R2D::zeros((2 * n, 2));
34    let mut labels = Vec::with_capacity(2 * n);
35    for i in 0..n {
36        let t = PI * i as f64 / (n.max(2) - 1) as f64;
37        x[[i, 0]] = t.cos() + rng.gaussian(0.0, noise);
38        x[[i, 1]] = t.sin() + rng.gaussian(0.0, noise);
39        x[[n + i, 0]] = 1.0 - t.cos() + rng.gaussian(0.0, noise);
40        x[[n + i, 1]] = 0.5 - t.sin() + rng.gaussian(0.0, noise);
41        labels.push(0);
42    }
43    labels.extend(std::iter::repeat_n(1, n));
44    (x, labels)
45}
46
47/// Two concentric circles: the inner has radius `factor` times the outer's (radius 1).
48pub fn make_circles(n: usize, noise: f64, factor: f64, seed: u64) -> (R2D, Vec<usize>) {
49    let mut rng = MlRng::new(seed);
50    let mut x = R2D::zeros((2 * n, 2));
51    let mut labels = Vec::with_capacity(2 * n);
52    for i in 0..n {
53        let t = TAU * i as f64 / n as f64;
54        x[[i, 0]] = t.cos() + rng.gaussian(0.0, noise);
55        x[[i, 1]] = t.sin() + rng.gaussian(0.0, noise);
56        x[[n + i, 0]] = factor * t.cos() + rng.gaussian(0.0, noise);
57        x[[n + i, 1]] = factor * t.sin() + rng.gaussian(0.0, noise);
58        labels.push(0);
59    }
60    labels.extend(std::iter::repeat_n(1, n));
61    (x, labels)
62}
63
64/// A linear regression problem `y = Xw + b + noise` with standard-normal features. Returns
65/// `(x, y, true weights, true intercept)`.
66pub fn make_regression(samples: usize, features: usize, noise: f64, seed: u64) -> (R2D, R1D, R1D, f64) {
67    let mut rng = MlRng::new(seed);
68    let w = R1D::from_iter((0..features).map(|_| rng.range(-3.0, 3.0)));
69    let intercept = rng.range(-2.0, 2.0);
70    let x = R2D::from_shape_fn((samples, features), |_| rng.gaussian(0.0, 1.0));
71    let y = x.dot(&w) + intercept + R1D::from_iter((0..samples).map(|_| rng.gaussian(0.0, noise)));
72    (x, y, w, intercept)
73}
74
75/// A noisy sine curve `y = sin(x)` sampled at `samples` random points in `[0, 2π]`, as a one-column
76/// feature matrix; a classic nonlinear regression demonstration.
77pub fn make_sine(samples: usize, noise: f64, seed: u64) -> (R2D, R1D) {
78    let mut rng = MlRng::new(seed);
79    let xs: Vec<f64> = (0..samples).map(|_| rng.range(0.0, TAU)).collect();
80    let y = R1D::from_iter(xs.iter().map(|&v| v.sin() + rng.gaussian(0.0, noise)));
81    (R2D::from_shape_fn((samples, 1), |(i, _)| xs[i]), y)
82}
83
84/// The "Swiss roll": a 2D sheet rolled up in 3D, a standard test for manifold learning. Returns the
85/// 3D points and each point's position along the roll.
86pub fn make_swiss_roll(samples: usize, noise: f64, seed: u64) -> (R2D, Vec<f64>) {
87    let mut rng = MlRng::new(seed);
88    let mut x = R2D::zeros((samples, 3));
89    let mut t = Vec::with_capacity(samples);
90    for i in 0..samples {
91        let angle = 1.5 * PI * (1.0 + 2.0 * rng.uniform());
92        x[[i, 0]] = angle * angle.cos() + rng.gaussian(0.0, noise);
93        x[[i, 1]] = 21.0 * rng.uniform() + rng.gaussian(0.0, noise);
94        x[[i, 2]] = angle * angle.sin() + rng.gaussian(0.0, noise);
95        t.push(angle);
96    }
97    (x, t)
98}
99
100/// Three Gaussian classes in four dimensions with deliberately overlapping, correlated features,
101/// a small stand-in for a tabular classification benchmark.
102pub fn make_classification(per_class: usize, seed: u64) -> (R2D, Vec<usize>) {
103    let centres = vec![vec![0.0, 0.0, 0.0, 0.0], vec![2.5, 1.0, -1.0, 0.5], vec![-1.0, 2.5, 1.5, -1.5]];
104    let (mut x, labels) = make_blobs(per_class, &centres, 1.0, seed);
105    for i in 0..x.nrows() {
106        let leak = 0.5 * x[[i, 0]];
107        x[[i, 1]] += leak; // correlate features 0 and 1
108    }
109    (x, labels)
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn shapes_labels_and_determinism() {
118        let (x, l) = make_blobs(20, &[vec![0.0, 0.0], vec![10.0, 10.0], vec![-10.0, 5.0]], 0.5, 1);
119        assert_eq!((x.dim(), l.len()), ((60, 2), 60));
120        assert_eq!(make_blobs(5, &[vec![1.0]], 1.0, 7).0, make_blobs(5, &[vec![1.0]], 1.0, 7).0);
121        assert_ne!(make_blobs(5, &[vec![1.0]], 1.0, 7).0, make_blobs(5, &[vec![1.0]], 1.0, 8).0);
122        // Blob means land near their centres.
123        let mean0: f64 = (0..20).map(|i| x[[i, 0]]).sum::<f64>() / 20.0;
124        assert!(mean0.abs() < 0.5);
125        let (m, ml) = make_moons(50, 0.05, 3);
126        assert_eq!((m.dim(), ml.iter().sum::<usize>()), ((100, 2), 50));
127        let (c, _) = make_circles(40, 0.0, 0.5, 4);
128        assert!((c[[0, 0]].hypot(c[[0, 1]]) - 1.0).abs() < 1e-12 && (c[[40, 0]].hypot(c[[40, 1]]) - 0.5).abs() < 1e-12);
129        assert_eq!(make_swiss_roll(30, 0.0, 1).0.dim(), (30, 3));
130        assert_eq!(make_classification(10, 1).0.dim(), (30, 4));
131        let (sx, sy) = make_sine(25, 0.1, 5);
132        assert_eq!((sx.dim(), sy.len()), ((25, 1), 25));
133    }
134
135    #[test]
136    fn regression_data_follows_its_true_model() {
137        let (x, y, w, b) = make_regression(200, 3, 0.0, 9);
138        let resid = &y - &(x.dot(&w) + b);
139        assert!(resid.iter().all(|r| r.abs() < 1e-12));
140    }
141}