ftir_cnn_feedback/
feedback.rs

1// Copyright (C) 2024 Hallvard Høyland Lavik
2
3use neurons::{activation, feedback, network, objective, optimizer, plot, tensor};
4
5use std::{
6    fs::File,
7    io::{BufRead, BufReader},
8};
9
10fn data(
11    path: &str,
12) -> (
13    (
14        Vec<tensor::Tensor>,
15        Vec<tensor::Tensor>,
16        Vec<tensor::Tensor>,
17    ),
18    (
19        Vec<tensor::Tensor>,
20        Vec<tensor::Tensor>,
21        Vec<tensor::Tensor>,
22    ),
23    (
24        Vec<tensor::Tensor>,
25        Vec<tensor::Tensor>,
26        Vec<tensor::Tensor>,
27    ),
28) {
29    let reader = BufReader::new(File::open(&path).unwrap());
30
31    let mut x_train: Vec<tensor::Tensor> = Vec::new();
32    let mut y_train: Vec<tensor::Tensor> = Vec::new();
33    let mut class_train: Vec<tensor::Tensor> = Vec::new();
34
35    let mut x_test: Vec<tensor::Tensor> = Vec::new();
36    let mut y_test: Vec<tensor::Tensor> = Vec::new();
37    let mut class_test: Vec<tensor::Tensor> = Vec::new();
38
39    let mut x_val: Vec<tensor::Tensor> = Vec::new();
40    let mut y_val: Vec<tensor::Tensor> = Vec::new();
41    let mut class_val: Vec<tensor::Tensor> = Vec::new();
42
43    for line in reader.lines().skip(1) {
44        let line = line.unwrap();
45        let record: Vec<&str> = line.split(',').collect();
46
47        let mut data: Vec<f32> = Vec::new();
48        for i in 0..571 {
49            data.push(record.get(i).unwrap().parse::<f32>().unwrap());
50        }
51        let data: Vec<Vec<Vec<f32>>> = vec![vec![data]];
52        match record.get(573).unwrap() {
53            &"Train" => {
54                x_train.push(tensor::Tensor::triple(data));
55                y_train.push(tensor::Tensor::single(vec![record
56                    .get(571)
57                    .unwrap()
58                    .parse::<f32>()
59                    .unwrap()]));
60                class_train.push(tensor::Tensor::one_hot(
61                    record.get(572).unwrap().parse::<usize>().unwrap() - 1, // For zero-indexed.
62                    28,
63                ));
64            }
65            &"Test" => {
66                x_test.push(tensor::Tensor::triple(data));
67                y_test.push(tensor::Tensor::single(vec![record
68                    .get(571)
69                    .unwrap()
70                    .parse::<f32>()
71                    .unwrap()]));
72                class_test.push(tensor::Tensor::one_hot(
73                    record.get(572).unwrap().parse::<usize>().unwrap() - 1, // For zero-indexed.
74                    28,
75                ));
76            }
77            &"Val" => {
78                x_val.push(tensor::Tensor::triple(data));
79                y_val.push(tensor::Tensor::single(vec![record
80                    .get(571)
81                    .unwrap()
82                    .parse::<f32>()
83                    .unwrap()]));
84                class_val.push(tensor::Tensor::one_hot(
85                    record.get(572).unwrap().parse::<usize>().unwrap() - 1, // For zero-indexed.
86                    28,
87                ));
88            }
89            _ => panic!("> Unknown class."),
90        }
91    }
92
93    // let mut generator = random::Generator::create(12345);
94    // let mut indices: Vec<usize> = (0..x.len()).collect();
95    // generator.shuffle(&mut indices);
96
97    (
98        (x_train, y_train, class_train),
99        (x_test, y_test, class_test),
100        (x_val, y_val, class_val),
101    )
102}
103
104fn main() {
105    // Load the ftir dataset
106    let ((x_train, y_train, class_train), (x_test, y_test, class_test), (x_val, y_val, class_val)) =
107        data("./examples/datasets/ftir.csv");
108
109    let x_train: Vec<&tensor::Tensor> = x_train.iter().collect();
110    let y_train: Vec<&tensor::Tensor> = y_train.iter().collect();
111    let class_train: Vec<&tensor::Tensor> = class_train.iter().collect();
112
113    let x_test: Vec<&tensor::Tensor> = x_test.iter().collect();
114    let y_test: Vec<&tensor::Tensor> = y_test.iter().collect();
115    let class_test: Vec<&tensor::Tensor> = class_test.iter().collect();
116
117    let x_val: Vec<&tensor::Tensor> = x_val.iter().collect();
118    let y_val: Vec<&tensor::Tensor> = y_val.iter().collect();
119    let class_val: Vec<&tensor::Tensor> = class_val.iter().collect();
120
121    println!("Train data {}x{}", x_train.len(), x_train[0].shape,);
122    println!("Test data {}x{}", x_test.len(), x_test[0].shape,);
123    println!("Validation data {}x{}", x_val.len(), x_val[0].shape,);
124
125    vec!["REGRESSION", "CLASSIFICATION"]
126        .iter()
127        .for_each(|method| {
128            // Create the network
129            let mut network = network::Network::new(tensor::Shape::Triple(1, 1, 571));
130
131            network.feedback(
132                vec![feedback::Layer::Convolution(
133                    1,
134                    activation::Activation::ReLU,
135                    (1, 9),
136                    (1, 1),
137                    (0, 4),
138                    (1, 1),
139                    None,
140                )],
141                2,
142                false,
143                false,
144                feedback::Accumulation::Mean,
145            );
146            network.dense(32, activation::Activation::ReLU, false, None);
147
148            if method == &"REGRESSION" {
149                network.dense(1, activation::Activation::Linear, false, None);
150                network.set_objective(objective::Objective::RMSE, None);
151            } else {
152                network.dense(28, activation::Activation::Softmax, false, None);
153                network.set_objective(objective::Objective::CrossEntropy, None);
154            }
155
156            network.set_optimizer(optimizer::Adam::create(0.001, 0.9, 0.999, 1e-8, None));
157
158            println!("{}", network);
159
160            // Train the network
161            let (train_loss, val_loss, val_acc);
162            if method == &"REGRESSION" {
163                println!("> Training the network for regression.");
164
165                (train_loss, val_loss, val_acc) = network.learn(
166                    &x_train,
167                    &y_train,
168                    Some((&x_val, &y_val, 50)),
169                    16,
170                    500,
171                    Some(100),
172                );
173            } else {
174                println!("> Training the network for classification.");
175
176                (train_loss, val_loss, val_acc) = network.learn(
177                    &x_train,
178                    &class_train,
179                    Some((&x_val, &class_val, 50)),
180                    16,
181                    500,
182                    Some(100),
183                );
184            }
185            plot::loss(
186                &train_loss,
187                &val_loss,
188                &val_acc,
189                &format!("FEEDBACK : FTIR : {}", method),
190                &format!("./output/ftir/cnn-{}-feedback.png", method.to_lowercase()),
191            );
192
193            if method == &"REGRESSION" {
194                // Use the network
195                let prediction = network.predict(x_test.get(0).unwrap());
196                println!(
197                    "Prediction. Target: {}. Output: {}.",
198                    y_test[0].data, prediction.data
199                );
200            } else {
201                // Validate the network
202                let (val_loss, val_acc) = network.validate(&x_test, &class_test, 1e-6);
203                println!(
204                    "Final validation accuracy: {:.2} % and loss: {:.5}",
205                    val_acc * 100.0,
206                    val_loss
207                );
208
209                // Use the network
210                let prediction = network.predict(x_test.get(0).unwrap());
211                println!(
212                    "Prediction. Target: {}. Output: {}.",
213                    class_test[0].argmax(),
214                    prediction.argmax()
215                );
216            }
217        });
218}