xor_file/
xor_file.rs

1use std::fs;
2use vexus::NeuralNetwork;
3
4fn main() {
5    let file_path = "xor_model.json";
6
7    // Try to load the neural network from a file, or create a new one if the file does not exist
8    let mut nn = if let Ok(nn) = NeuralNetwork::from_file(file_path) {
9        println!("Loaded neural network from file.");
10        nn
11    } else {
12        println!("Creating a new neural network.");
13        NeuralNetwork::new(vec![2, 4, 1], 0.1)
14    };
15
16    // Training data for XOR
17    let training_data = vec![
18        (vec![0.0, 0.0], vec![0.0]),
19        (vec![0.0, 1.0], vec![1.0]),
20        (vec![1.0, 0.0], vec![1.0]),
21        (vec![1.0, 1.0], vec![0.0]),
22    ];
23
24    // Train the network
25    for _ in 0..1000000 {
26        for (inputs, expected) in &training_data {
27            nn.forward(inputs.clone());
28            let outputs = nn.get_outputs();
29            let errors = vec![expected[0] - outputs[0]];
30            nn.backwards(errors);
31        }
32    }
33
34    // Test the network
35    for (inputs, expected) in &training_data {
36        nn.forward(inputs.clone());
37        let outputs = nn.get_outputs();
38        println!(
39            "Input: {:?}, Expected: {:?}, Got: {:.4}",
40            inputs, expected[0], outputs[0]
41        );
42    }
43
44    // Save the trained neural network to a file
45    if let Err(e) = nn.save_to_file(file_path) {
46        eprintln!("Failed to save neural network to file: {}", e);
47    } else {
48        println!("Neural network saved to file.");
49    }
50}