Skip to main content

lib_jsl_machine_learning/
neural_network.rs

1//! Multilayer perceptrons trained by backpropagation.
2//!
3//! A fully connected feed-forward network `x → f(W₁x + b₁) → … → W_L h + b_L`, with a linear
4//! output and squared-error loss for regression or a softmax output and cross-entropy loss for
5//! classification. Gradients come from backpropagation; weights are updated by mini-batch Adam
6//! (Kingma and Ba) with L2 weight decay. Inputs (and regression targets) are standardised
7//! internally, and weights start from He (ReLU) or Glorot (tanh, sigmoid) initialisation.
8//!
9//! See the book entry [Multilayer perceptrons and backpropagation](https://jwkunz.github.io/lib_jsl/book/learning/neural-networks.html).
10
11use crate::common::{Classifier, MlRng, Regressor, argmax, check_xy, class_count};
12use lib_jsl_core::{ErrorsJSL, R1D, R2D, VR1D, VR2D};
13use ndarray::Axis;
14
15/// The hidden-layer nonlinearity.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum Activation {
18    Relu,
19    Tanh,
20    Sigmoid,
21}
22
23impl Activation {
24    fn apply(self, z: f64) -> f64 {
25        match self {
26            Activation::Relu => z.max(0.0),
27            Activation::Tanh => z.tanh(),
28            Activation::Sigmoid => 1.0 / (1.0 + (-z).exp()),
29        }
30    }
31
32    /// The derivative expressed through the activation value `a = f(z)`.
33    fn derivative(self, a: f64) -> f64 {
34        match self {
35            Activation::Relu => f64::from(u8::from(a > 0.0)),
36            Activation::Tanh => 1.0 - a * a,
37            Activation::Sigmoid => a * (1.0 - a),
38        }
39    }
40}
41
42/// Network shape and training settings.
43#[derive(Debug, Clone)]
44pub struct MlpParameters {
45    /// Sizes of the hidden layers.
46    pub hidden: Vec<usize>,
47    pub activation: Activation,
48    pub learning_rate: f64,
49    pub epochs: usize,
50    pub batch_size: usize,
51    /// L2 penalty `λ/2 Σ w²` on the weights (not the biases).
52    pub weight_decay: f64,
53    pub seed: u64,
54}
55
56impl Default for MlpParameters {
57    fn default() -> Self {
58        MlpParameters { hidden: vec![32, 32], activation: Activation::Tanh, learning_rate: 0.01, epochs: 300, batch_size: 32, weight_decay: 1e-4, seed: 0 }
59    }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63enum Output {
64    Linear,
65    Softmax,
66}
67
68/// The network: weights `w[l]` of shape `(outputs, inputs)` and biases `b[l]`.
69#[derive(Debug, Clone)]
70struct Network {
71    w: Vec<R2D>,
72    b: Vec<R1D>,
73    activation: Activation,
74    output: Output,
75}
76
77impl Network {
78    fn new(sizes: &[usize], activation: Activation, output: Output, rng: &mut MlRng) -> Self {
79        let mut w = Vec::new();
80        let mut b = Vec::new();
81        for pair in sizes.windows(2) {
82            let (fan_in, fan_out) = (pair[0], pair[1]);
83            let scale = match activation {
84                Activation::Relu => (2.0 / fan_in as f64).sqrt(),
85                _ => (2.0 / (fan_in + fan_out) as f64).sqrt(),
86            };
87            w.push(R2D::from_shape_fn((fan_out, fan_in), |_| rng.gaussian(0.0, scale)));
88            b.push(R1D::zeros(fan_out));
89        }
90        Network { w, b, activation, output }
91    }
92
93    /// Activations of every layer for a batch (`activations[0]` is the input).
94    fn forward(&self, x: &R2D) -> Vec<R2D> {
95        let mut activations = vec![x.clone()];
96        let last = self.w.len() - 1;
97        for (l, (w, b)) in self.w.iter().zip(&self.b).enumerate() {
98            let mut z = activations[l].dot(&w.t()) + b;
99            if l < last {
100                z.mapv_inplace(|v| self.activation.apply(v));
101            } else if self.output == Output::Softmax {
102                for mut row in z.rows_mut() {
103                    let m = row.fold(f64::NEG_INFINITY, |a, &v| a.max(v));
104                    row.mapv_inplace(|v| (v - m).exp());
105                    let s = row.sum();
106                    row.mapv_inplace(|v| v / s);
107                }
108            }
109            activations.push(z);
110        }
111        activations
112    }
113
114    // ANCHOR: backprop
115    /// The mean loss over the batch (plus the weight penalty) and its gradients.
116    fn loss_and_gradient(&self, x: &R2D, targets: &R2D, weight_decay: f64) -> (f64, Vec<R2D>, Vec<R1D>) {
117        let a = self.forward(x);
118        let batch = x.nrows() as f64;
119        let output = a.last().expect("at least one layer");
120        let data_loss = match self.output {
121            Output::Linear => 0.5 * (output - targets).mapv(|v| v * v).sum() / batch,
122            Output::Softmax => -(output.mapv(|p| p.max(1e-300).ln()) * targets).sum() / batch,
123        };
124        let penalty = 0.5 * weight_decay * self.w.iter().map(|w| w.mapv(|v| v * v).sum()).sum::<f64>();
125        // For both pairings (linear + squared error, softmax + cross-entropy) δ_L = (ŷ − y)/B.
126        let mut delta = (output - targets) / batch;
127        let layers = self.w.len();
128        let mut gw = vec![R2D::zeros((0, 0)); layers];
129        let mut gb = vec![R1D::zeros(0); layers];
130        for l in (0..layers).rev() {
131            // Assigned into a row-major array: the product can come back column-major (for example
132            // when an activation matrix has a single column), and the Adam step reads the gradient
133            // as a flat slice in the same order as the weights.
134            let mut g = R2D::zeros(self.w[l].dim());
135            g.assign(&delta.t().dot(&a[l]));
136            g.scaled_add(weight_decay, &self.w[l]);
137            gw[l] = g;
138            gb[l] = delta.sum_axis(Axis(0));
139            if l > 0 {
140                let back = delta.dot(&self.w[l]);
141                delta = back * a[l].mapv(|v| self.activation.derivative(v));
142            }
143        }
144        (data_loss + penalty, gw, gb)
145    }
146    // ANCHOR_END: backprop
147}
148
149/// Adam optimiser state for one parameter tensor.
150struct Adam {
151    m: Vec<f64>,
152    v: Vec<f64>,
153}
154
155impl Adam {
156    // ANCHOR: adam
157    fn step(&mut self, parameters: &mut [f64], gradient: &[f64], rate: f64, t: i32) {
158        let (b1, b2, eps) = (0.9f64, 0.999f64, 1e-8);
159        let (c1, c2) = (1.0 - b1.powi(t), 1.0 - b2.powi(t));
160        for i in 0..parameters.len() {
161            self.m[i] = b1 * self.m[i] + (1.0 - b1) * gradient[i];
162            self.v[i] = b2 * self.v[i] + (1.0 - b2) * gradient[i] * gradient[i];
163            parameters[i] -= rate * (self.m[i] / c1) / ((self.v[i] / c2).sqrt() + eps);
164        }
165    }
166    // ANCHOR_END: adam
167}
168
169/// Feature standardisation learned from the training data.
170#[derive(Debug, Clone)]
171struct Standardizer {
172    mean: R1D,
173    scale: R1D,
174}
175
176impl Standardizer {
177    fn fit(x: VR2D) -> Self {
178        let mean = x.mean_axis(Axis(0)).expect("non-empty");
179        let scale = x.std_axis(Axis(0), 0.0).mapv(|s| if s > 1e-12 { s } else { 1.0 });
180        Standardizer { mean, scale }
181    }
182
183    fn apply(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
184        if x.ncols() != self.mean.len() {
185            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.mean.len())));
186        }
187        Ok((&x - &self.mean) / &self.scale)
188    }
189}
190
191/// Trains a network by mini-batch Adam; returns it with the per-epoch mean training loss.
192fn train(parameters: &MlpParameters, x: &R2D, targets: &R2D, output: Output) -> Result<(Network, Vec<f64>), ErrorsJSL> {
193    if parameters.hidden.contains(&0) || parameters.batch_size == 0 || parameters.epochs == 0 || parameters.learning_rate.is_nan() || parameters.learning_rate <= 0.0 {
194        return Err(ErrorsJSL::InvalidInputRange("Need non-zero layer sizes, batch size and epochs, and a positive learning rate."));
195    }
196    let mut rng = MlRng::new(parameters.seed);
197    let sizes: Vec<usize> = std::iter::once(x.ncols()).chain(parameters.hidden.iter().copied()).chain(std::iter::once(targets.ncols())).collect();
198    let mut net = Network::new(&sizes, parameters.activation, output, &mut rng);
199    let mut adam_w: Vec<Adam> = net.w.iter().map(|w| Adam { m: vec![0.0; w.len()], v: vec![0.0; w.len()] }).collect();
200    let mut adam_b: Vec<Adam> = net.b.iter().map(|b| Adam { m: vec![0.0; b.len()], v: vec![0.0; b.len()] }).collect();
201    let n = x.nrows();
202    let mut order: Vec<usize> = (0..n).collect();
203    let mut history = Vec::with_capacity(parameters.epochs);
204    let mut t = 0;
205    for _ in 0..parameters.epochs {
206        rng.shuffle(&mut order);
207        let mut epoch_loss = 0.0;
208        for chunk in order.chunks(parameters.batch_size) {
209            t += 1;
210            let (xb, yb) = (x.select(Axis(0), chunk), targets.select(Axis(0), chunk));
211            let (loss, gw, gb) = net.loss_and_gradient(&xb, &yb, parameters.weight_decay);
212            epoch_loss += loss * chunk.len() as f64;
213            for l in 0..net.w.len() {
214                adam_w[l].step(net.w[l].as_slice_mut().expect("contiguous"), gw[l].as_slice().expect("contiguous"), parameters.learning_rate, t);
215                adam_b[l].step(net.b[l].as_slice_mut().expect("contiguous"), gb[l].as_slice().expect("contiguous"), parameters.learning_rate, t);
216            }
217        }
218        let mean_loss = epoch_loss / n as f64;
219        if !mean_loss.is_finite() {
220            return Err(ErrorsJSL::RuntimeError("Training diverged; lower the learning rate."));
221        }
222        history.push(mean_loss);
223    }
224    Ok((net, history))
225}
226
227/// A multilayer perceptron for regression (linear output, squared-error loss).
228#[derive(Debug, Clone)]
229pub struct MlpRegressor {
230    pub parameters: MlpParameters,
231    network: Option<Network>,
232    inputs: Option<Standardizer>,
233    target_mean: f64,
234    target_scale: f64,
235    /// Mean training loss per epoch (on standardised targets).
236    pub training_loss: Vec<f64>,
237}
238
239impl MlpRegressor {
240    pub fn new(parameters: MlpParameters) -> Self {
241        MlpRegressor { parameters, network: None, inputs: None, target_mean: 0.0, target_scale: 1.0, training_loss: Vec::new() }
242    }
243}
244
245impl Regressor for MlpRegressor {
246    fn fit(&mut self, x: VR2D, y: VR1D) -> Result<(), ErrorsJSL> {
247        check_xy(x, y.len())?;
248        let standardizer = Standardizer::fit(x);
249        self.target_mean = y.mean().expect("non-empty");
250        self.target_scale = y.std(0.0).max(1e-12);
251        let targets = y.mapv(|v| (v - self.target_mean) / self.target_scale).insert_axis(Axis(1));
252        let (net, history) = train(&self.parameters, &standardizer.apply(x)?, &targets, Output::Linear)?;
253        self.network = Some(net);
254        self.inputs = Some(standardizer);
255        self.training_loss = history;
256        Ok(())
257    }
258
259    fn predict(&self, x: VR2D) -> Result<R1D, ErrorsJSL> {
260        let (net, standardizer) = self.network.as_ref().zip(self.inputs.as_ref()).ok_or(ErrorsJSL::RuntimeError("The model has not been fitted."))?;
261        let output = net.forward(&standardizer.apply(x)?).pop().expect("output layer");
262        Ok(output.column(0).mapv(|v| v * self.target_scale + self.target_mean))
263    }
264}
265
266/// A multilayer perceptron for classification (softmax output, cross-entropy loss).
267#[derive(Debug, Clone)]
268pub struct MlpClassifier {
269    pub parameters: MlpParameters,
270    network: Option<Network>,
271    inputs: Option<Standardizer>,
272    /// Mean training cross-entropy per epoch.
273    pub training_loss: Vec<f64>,
274}
275
276impl MlpClassifier {
277    pub fn new(parameters: MlpParameters) -> Self {
278        MlpClassifier { parameters, network: None, inputs: None, training_loss: Vec::new() }
279    }
280
281    /// Class probabilities, one row per sample.
282    pub fn predict_proba(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
283        let (net, standardizer) = self.network.as_ref().zip(self.inputs.as_ref()).ok_or(ErrorsJSL::RuntimeError("The model has not been fitted."))?;
284        Ok(net.forward(&standardizer.apply(x)?).pop().expect("output layer"))
285    }
286}
287
288impl Classifier for MlpClassifier {
289    fn fit(&mut self, x: VR2D, labels: &[usize]) -> Result<(), ErrorsJSL> {
290        check_xy(x, labels.len())?;
291        let k = class_count(labels).max(2);
292        let targets = R2D::from_shape_fn((labels.len(), k), |(i, c)| f64::from(u8::from(labels[i] == c)));
293        let standardizer = Standardizer::fit(x);
294        let (net, history) = train(&self.parameters, &standardizer.apply(x)?, &targets, Output::Softmax)?;
295        self.network = Some(net);
296        self.inputs = Some(standardizer);
297        self.training_loss = history;
298        Ok(())
299    }
300
301    fn predict(&self, x: VR2D) -> Result<Vec<usize>, ErrorsJSL> {
302        let p = self.predict_proba(x)?;
303        Ok(p.rows().into_iter().map(|r| argmax(&r.to_vec()).unwrap_or(0)).collect())
304    }
305}
306
307/// The one-hot encoding of labels (exposed for building custom targets).
308pub fn one_hot(labels: &[usize], classes: usize) -> R2D {
309    R2D::from_shape_fn((labels.len(), classes), |(i, c)| f64::from(u8::from(labels[i] == c)))
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315    use crate::datasets::{make_moons, make_sine};
316    use crate::metrics::{accuracy, mean_squared_error};
317    use crate::preprocessing::train_test_split;
318
319    #[test]
320    fn backpropagation_matches_finite_differences() {
321        let mut rng = MlRng::new(3);
322        for (activation, output) in [(Activation::Tanh, Output::Linear), (Activation::Sigmoid, Output::Softmax), (Activation::Relu, Output::Softmax)] {
323            let net = Network::new(&[3, 5, 4, 2], activation, output, &mut rng);
324            let x = R2D::from_shape_fn((6, 3), |_| rng.gaussian(0.0, 1.0));
325            let y = if output == Output::Linear { R2D::from_shape_fn((6, 2), |_| rng.gaussian(0.0, 1.0)) } else { one_hot(&[0, 1, 1, 0, 1, 0], 2) };
326            let (_, gw, gb) = net.loss_and_gradient(&x, &y, 0.01);
327            let h = 1e-6;
328            for l in 0..3 {
329                for idx in [(0, 0), (1, 2)] {
330                    let mut plus = net.clone();
331                    plus.w[l][idx] += h;
332                    let mut minus = net.clone();
333                    minus.w[l][idx] -= h;
334                    let numeric = (plus.loss_and_gradient(&x, &y, 0.01).0 - minus.loss_and_gradient(&x, &y, 0.01).0) / (2.0 * h);
335                    assert!((numeric - gw[l][idx]).abs() < 1e-6, "{activation:?} layer {l} {idx:?}: {numeric} vs {}", gw[l][idx]);
336                }
337                let mut plus = net.clone();
338                plus.b[l][0] += h;
339                let mut minus = net.clone();
340                minus.b[l][0] -= h;
341                let numeric = (plus.loss_and_gradient(&x, &y, 0.01).0 - minus.loss_and_gradient(&x, &y, 0.01).0) / (2.0 * h);
342                assert!((numeric - gb[l][0]).abs() < 1e-6, "bias layer {l}");
343            }
344        }
345    }
346
347    #[test]
348    fn learns_xor_and_two_moons() {
349        let x = R2D::from_shape_vec((4, 2), vec![0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]).unwrap();
350        let labels = [0, 1, 1, 0];
351        let mut xor = MlpClassifier::new(MlpParameters { hidden: vec![8], epochs: 500, batch_size: 4, learning_rate: 0.05, ..Default::default() });
352        xor.fit(x.view(), &labels).unwrap();
353        assert_eq!(xor.predict(x.view()).unwrap(), labels);
354        let (xm, lm) = make_moons(400, 0.15, 7);
355        let (train_idx, test_idx) = train_test_split(400, 0.25, 8).unwrap();
356        let lt: Vec<usize> = train_idx.iter().map(|&i| lm[i]).collect();
357        let ls: Vec<usize> = test_idx.iter().map(|&i| lm[i]).collect();
358        let mut moons = MlpClassifier::new(MlpParameters { epochs: 150, ..Default::default() });
359        moons.fit(xm.select(Axis(0), &train_idx).view(), &lt).unwrap();
360        let accuracy_value = accuracy(&ls, &moons.predict(xm.select(Axis(0), &test_idx).view()).unwrap()).unwrap();
361        assert!(accuracy_value > 0.95, "{accuracy_value}");
362        assert!(moons.training_loss.last().unwrap() < &(0.3 * moons.training_loss[0]));
363    }
364
365    #[test]
366    fn regresses_a_sine_and_validates() {
367        let (x, y) = make_sine(300, 0.05, 9);
368        let mut mlp = MlpRegressor::new(MlpParameters { hidden: vec![32], epochs: 400, activation: Activation::Tanh, ..Default::default() });
369        mlp.fit(x.view(), y.view()).unwrap();
370        let grid = R2D::from_shape_fn((50, 1), |(i, _)| 0.2 + 5.8 * i as f64 / 49.0);
371        let truth = grid.column(0).mapv(f64::sin);
372        let mse = mean_squared_error(truth.view(), mlp.predict(grid.view()).unwrap().view()).unwrap();
373        assert!(mse < 0.01, "{mse}");
374        // One input feature through two hidden layers (a product that comes out column-major).
375        let mut deep = MlpRegressor::new(MlpParameters { hidden: vec![16, 16], epochs: 300, batch_size: 16, ..Default::default() });
376        deep.fit(x.view(), y.view()).unwrap();
377        let deep_mse = mean_squared_error(truth.view(), deep.predict(grid.view()).unwrap().view()).unwrap();
378        assert!(deep_mse < 0.02, "{deep_mse}");
379        let mut bad = MlpRegressor::new(MlpParameters { hidden: vec![0], ..Default::default() });
380        assert!(bad.fit(x.view(), y.view()).is_err());
381        assert!(MlpClassifier::new(MlpParameters::default()).predict(x.view()).is_err());
382        // A different number of features is an error, not a silent broadcast.
383        assert!(mlp.predict(R2D::zeros((3, 2)).view()).is_err());
384        let (xm, lm) = make_moons(20, 0.1, 1);
385        let mut c = MlpClassifier::new(MlpParameters { epochs: 2, ..Default::default() });
386        c.fit(xm.view(), &lm).unwrap();
387        assert!(c.predict(R2D::zeros((2, 1)).view()).is_err());
388    }
389}