fashion_feedback/
feedback.rs

1// Copyright (C) 2024 Hallvard Høyland Lavik
2
3use neurons::{activation, feedback, network, objective, optimizer, plot, tensor};
4
5use std::fs::File;
6use std::io::{BufReader, Read, Result};
7
8fn read(reader: &mut dyn Read) -> Result<u32> {
9    let mut buffer = [0; 4];
10    reader.read_exact(&mut buffer)?;
11    Ok(u32::from_be_bytes(buffer))
12}
13
14fn load_mnist(path: &str) -> Result<Vec<tensor::Tensor>> {
15    let mut reader = BufReader::new(File::open(path)?);
16    let mut images: Vec<tensor::Tensor> = Vec::new();
17
18    let _magic_number = read(&mut reader)?;
19    let num_images = read(&mut reader)?;
20    let num_rows = read(&mut reader)?;
21    let num_cols = read(&mut reader)?;
22
23    for _ in 0..num_images {
24        let mut image: Vec<Vec<f32>> = Vec::new();
25        for _ in 0..num_rows {
26            let mut row: Vec<f32> = Vec::new();
27            for _ in 0..num_cols {
28                let mut pixel = [0];
29                reader.read_exact(&mut pixel)?;
30                row.push(pixel[0] as f32 / 255.0);
31            }
32            image.push(row);
33        }
34        images.push(tensor::Tensor::triple(vec![image]).resize(tensor::Shape::Triple(1, 14, 14)));
35    }
36
37    Ok(images)
38}
39
40fn load_labels(file_path: &str, numbers: usize) -> Result<Vec<tensor::Tensor>> {
41    let mut reader = BufReader::new(File::open(file_path)?);
42    let _magic_number = read(&mut reader)?;
43    let num_labels = read(&mut reader)?;
44
45    let mut _labels = vec![0; num_labels as usize];
46    reader.read_exact(&mut _labels)?;
47
48    Ok(_labels
49        .iter()
50        .map(|&x| tensor::Tensor::one_hot(x as usize, numbers))
51        .collect())
52}
53
54fn main() {
55    let x_train = load_mnist("./examples/datasets/mnist-fashion/train-images-idx3-ubyte").unwrap();
56    let y_train = load_labels(
57        "./examples/datasets/mnist-fashion/train-labels-idx1-ubyte",
58        10,
59    )
60    .unwrap();
61    let x_test = load_mnist("./examples/datasets/mnist-fashion/t10k-images-idx3-ubyte").unwrap();
62    let y_test = load_labels(
63        "./examples/datasets/mnist-fashion/t10k-labels-idx1-ubyte",
64        10,
65    )
66    .unwrap();
67    println!(
68        "Train: {} images, Test: {} images",
69        x_train.len(),
70        x_test.len()
71    );
72
73    let x_train: Vec<&tensor::Tensor> = x_train.iter().collect();
74    let y_train: Vec<&tensor::Tensor> = y_train.iter().collect();
75    let x_test: Vec<&tensor::Tensor> = x_test.iter().collect();
76    let y_test: Vec<&tensor::Tensor> = y_test.iter().collect();
77
78    let mut network = network::Network::new(tensor::Shape::Triple(1, 14, 14));
79
80    network.convolution(
81        1,
82        (3, 3),
83        (1, 1),
84        (1, 1),
85        (1, 1),
86        activation::Activation::ReLU,
87        None,
88    );
89    network.feedback(
90        vec![feedback::Layer::Convolution(
91            1,
92            activation::Activation::ReLU,
93            (3, 3),
94            (1, 1),
95            (1, 1),
96            (1, 1),
97            None,
98        )],
99        3,
100        false,
101        false,
102        feedback::Accumulation::Mean,
103    );
104    network.convolution(
105        1,
106        (3, 3),
107        (1, 1),
108        (1, 1),
109        (1, 1),
110        activation::Activation::ReLU,
111        None,
112    );
113    network.maxpool((2, 2), (2, 2));
114    network.dense(10, activation::Activation::Softmax, true, None);
115
116    // Include skip connection bypassing the feedback block
117    // network.connect(1, 2);
118    // network.set_accumulation(feedback::Accumulation::Add);
119
120    network.set_optimizer(optimizer::Adam::create(0.001, 0.9, 0.999, 1e-8, None));
121    network.set_objective(objective::Objective::CrossEntropy, None);
122
123    println!("{}", network);
124
125    // Train the network
126    let (train_loss, val_loss, val_acc) = network.learn(
127        &x_train,
128        &y_train,
129        Some((&x_test, &y_test, 10)),
130        32,
131        25,
132        Some(5),
133    );
134    plot::loss(
135        &train_loss,
136        &val_loss,
137        &val_acc,
138        "FEEDBACK : Fashion-MNIST",
139        "./output/mnist-fashion/feedback.png",
140    );
141
142    // Validate the network
143    let (val_loss, val_acc) = network.validate(&x_test, &y_test, 1e-6);
144    println!(
145        "Final validation accuracy: {:.2} % and loss: {:.5}",
146        val_acc * 100.0,
147        val_loss
148    );
149
150    // Use the network
151    let prediction = network.predict(x_test.get(0).unwrap());
152    println!(
153        "Prediction on input: Target: {}. Output: {}.",
154        y_test[0].argmax(),
155        prediction.argmax()
156    );
157
158    // let x = x_test.get(5).unwrap();
159    // let y = y_test.get(5).unwrap();
160    // Plot the pre- and post-activation heatmaps for each (image) layer.
161    // let (pre, post, _) = network.forward(x);
162    // for (i, (i_pre, i_post)) in pre.iter().zip(post.iter()).enumerate() {
163    //     let pre_title = format!("layer_{}_pre", i);
164    //     let post_title = format!("layer_{}_post", i);
165    //     let pre_file = format!("layer_{}_pre.png", i);
166    //     let post_file = format!("layer_{}_post.png", i);
167    //     plot::heatmap(&i_pre, &pre_title, &pre_file);
168    //     plot::heatmap(&i_post, &post_title, &post_file);
169    // }
170}