fashion_skip/
skip.rs

1// Copyright (C) 2024 Hallvard Høyland Lavik
2
3use neurons::{activation, 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.convolution(
90        1,
91        (3, 3),
92        (1, 1),
93        (1, 1),
94        (1, 1),
95        activation::Activation::ReLU,
96        None,
97    );
98    network.convolution(
99        1,
100        (3, 3),
101        (1, 1),
102        (1, 1),
103        (1, 1),
104        activation::Activation::ReLU,
105        None,
106    );
107    network.maxpool((2, 2), (2, 2));
108    network.dense(10, activation::Activation::Softmax, true, None);
109
110    network.connect(0, 2);
111
112    network.set_optimizer(optimizer::Adam::create(0.001, 0.9, 0.999, 1e-8, None));
113    network.set_objective(objective::Objective::CrossEntropy, None);
114
115    println!("{}", network);
116
117    // Train the network
118    let (train_loss, val_loss, val_acc) = network.learn(
119        &x_train,
120        &y_train,
121        Some((&x_test, &y_test, 10)),
122        32,
123        25,
124        Some(5),
125    );
126    plot::loss(
127        &train_loss,
128        &val_loss,
129        &val_acc,
130        "SKIP : Fashion-MNIST",
131        "./output/mnist-fashion/skip.png",
132    );
133
134    // Validate the network
135    let (val_loss, val_acc) = network.validate(&x_test, &y_test, 1e-6);
136    println!(
137        "Final validation accuracy: {:.2} % and loss: {:.5}",
138        val_acc * 100.0,
139        val_loss
140    );
141
142    // Use the network
143    let prediction = network.predict(x_test.get(0).unwrap());
144    println!(
145        "Prediction on input: Target: {}. Output: {}.",
146        y_test[0].argmax(),
147        prediction.argmax()
148    );
149
150    // let x = x_test.get(5).unwrap();
151    // let y = y_test.get(5).unwrap();
152    // Plot the pre- and post-activation heatmaps for each (image) layer.
153    // let (pre, post, _) = network.forward(x);
154    // for (i, (i_pre, i_post)) in pre.iter().zip(post.iter()).enumerate() {
155    //     let pre_title = format!("layer_{}_pre", i);
156    //     let post_title = format!("layer_{}_post", i);
157    //     let pre_file = format!("layer_{}_pre.png", i);
158    //     let post_file = format!("layer_{}_post.png", i);
159    //     plot::heatmap(&i_pre, &pre_title, &pre_file);
160    //     plot::heatmap(&i_post, &post_title, &post_file);
161    // }
162}