square_function/
square_function.rs

1use std::f32::consts::PI;
2
3use vexus::{NeuralNetwork, Sigmoid};
4
5fn normalize(x: f32, min: f32, max: f32) -> f32 {
6    (x - min) / (max - min)
7}
8
9fn denormalize(x: f32, min: f32, max: f32) -> f32 {
10    x * (max - min) + min
11}
12
13fn main() {
14    let mut nn = NeuralNetwork::new(vec![1, 4, 4, 1], 0.01, Box::new(Sigmoid));
15    // Create a neural network with 1 input, one hidden layer of 10 neurons, and 1 output
16
17    // Generate training data: f(x) = x^2 for x in [-1, 1]
18    let training_data: Vec<(Vec<f32>, Vec<f32>)> = (-100..=100)
19        .map(|i| {
20            let x = i as f32 / 100.0;
21            let y = x * x;
22            (vec![normalize(x, -1.0, 1.0)], vec![normalize(y, 0.0, 1.0)])
23        })
24        .collect();
25
26    // Train the network
27    println!("Training...");
28    for epoch in 0..1000000 {
29        let mut error = 0.0;
30        for (input, expected) in &training_data {
31            let _output = nn.forward(input);
32            error = nn.errors(expected);
33            nn.backpropagate(expected);
34        }
35
36        if epoch % 10000 == 0 {
37            println!(
38                "Epoch {}: MSE = {:.6}",
39                epoch,
40                error / training_data.len() as f32
41            );
42        }
43    }
44
45    // Test the network
46    println!("\nTesting...");
47    let test_points = vec![-1.0, -0.5, 0.0, 0.5, 1.0, 1.0 / PI];
48    for x in test_points {
49        let predicted = denormalize(nn.forward(&vec![normalize(x, -1.0, 1.0)])[0], 0.0, 1.0);
50        println!(
51            "x = {:.3}, x^2 = {:.3}, predicted = {:.3}, error = {:.3}",
52            x,
53            x * x,
54            predicted,
55            ((x * x) - predicted).abs()
56        );
57    }
58}