use std::f32::consts::PI;
use vexus::{NeuralNetwork, Sigmoid};
fn normalize(x: f32, min: f32, max: f32) -> f32 {
(x - min) / (max - min)
}
fn denormalize(x: f32, min: f32, max: f32) -> f32 {
x * (max - min) + min
}
fn main() {
let mut nn = NeuralNetwork::new(vec![1, 4, 4, 1], 0.01, Box::new(Sigmoid));
let training_data: Vec<(Vec<f32>, Vec<f32>)> = (-100..=100)
.map(|i| {
let x = i as f32 / 100.0;
let y = x * x;
(vec![normalize(x, -1.0, 1.0)], vec![normalize(y, 0.0, 1.0)])
})
.collect();
println!("Training...");
for epoch in 0..1000000 {
let mut error = 0.0;
for (input, expected) in &training_data {
let _output = nn.forward(input);
error = nn.errors(expected);
nn.backpropagate(expected);
}
if epoch % 10000 == 0 {
println!(
"Epoch {}: MSE = {:.6}",
epoch,
error / training_data.len() as f32
);
}
}
println!("\nTesting...");
let test_points = vec![-1.0, -0.5, 0.0, 0.5, 1.0, 1.0 / PI];
for x in test_points {
let predicted = denormalize(nn.forward(&vec![normalize(x, -1.0, 1.0)])[0], 0.0, 1.0);
println!(
"x = {:.3}, x^2 = {:.3}, predicted = {:.3}, error = {:.3}",
x,
x * x,
predicted,
((x * x) - predicted).abs()
);
}
}