neuron/
neuron.rs

1/// Example of a simple neuron with 3 inputs and no activation function.
2///
3/// This example demonstrates how to create a simple neuron with 3 inputs and no activation function.
4/// The neuron has 3 inputs and 1 output. The output is the weighted sum of the inputs.
5///
6/// Contrast this example with the `layer` example.
7/// 
8/// For more information, see [`Neuron`].
9extern crate alpha_micrograd_rust;
10
11use alpha_micrograd_rust::nn::{Activation, Neuron};
12use alpha_micrograd_rust::value::Expr;
13
14fn main() {
15    let mut target = Expr::new_leaf(50.0, "target");
16    target.is_learnable = false;
17
18    let neuron = Neuron::new(3, Activation::None);
19    println!("Initial values: {:}", neuron);
20
21    let mut inputs = vec![
22        Expr::new_leaf(1.0, "x_1"),
23        Expr::new_leaf(2.0, "x_2"),
24        Expr::new_leaf(3.0, "x_3"),
25    ];
26
27    inputs.iter_mut().for_each(|input| {
28        input.is_learnable = false;
29    });
30
31    let mut y = neuron.forward(inputs);
32    y.name = "y".to_string();
33
34    let difference = y - target;
35    let mut square_exponent = Expr::new_leaf(2.0, "square_exponent");
36    square_exponent.is_learnable = false;
37
38    let mut loss = difference.pow(square_exponent, "loss");
39
40    let target = loss.find("target").unwrap();
41    let y = loss.find("y").unwrap();
42    println!("Initial target: {:.2}", target.result);
43    println!("Predicted: {:.2}", y.result);
44    println!("Initial loss: {:.2}", loss.result);
45
46    println!("\nTraining:");
47    let learning_rate = 0.01;
48    for i in 1..=100 {
49        loss.learn(learning_rate);
50        loss.recalculate();
51
52        let y = loss.find("y").expect("Node not found");
53        let target = loss.find("target").expect("Node not found");
54
55        println!(
56            "Iteration {:3}, loss: {:9.4} / predicted: {:.2} (target: {:.2})",
57            i, loss.result, y.result, target.result
58        );
59    }
60
61    println!("Final values: {:}", neuron);
62}