4 Rust Crate
Juniper Gardiner edited this page 2025-09-01 14:24:47 +01:00

Rust Crate Documentation

The Rust crate is designed to be simple to use and understand, without needing to worry so much about the underlying C code.

To explain how it works, we will break down one of the tests to perform a simple XOR operation.

let (structure, learning_rate, num_epochs) = (vec![2, 2, 1], 1.0, 400);
let mut neural_network = Network32Sigmoid::new(&structure);
let training_data: Vec<(Vec<f32>, Vec<f32>)> = vec![
    (vec![0.0, 0.0], vec![0.0]),
    (vec![1.0, 1.0], vec![0.0]),
    (vec![0.0, 1.0], vec![1.0]),
    (vec![1.0, 0.0], vec![1.0]),
];
let outputs = neural_network.compute_noavx(vec![0.0, 0.0]);
let final_output = outputs[outputs.len() - 1].clone();
assert!(final_output > 0.0 && final_output < 0.1);

in the first line, we define a couple of values.

The structure defines how the neural network is laid out - In this case we have two inputs, a middle layer with 2 neurons and one output.

Alongside this, we have the learning_rate and num_epochs - The learning rate can be used to increase the effectiveness of training, but having it too high could cause it to overgeneralize, while having it too low might leave an inaccurate result, while the number of epochs is the amount of loops the training process goes through.

We then define the neural network using Network32Sigmoid::new(&structure) - Using the structure defined earlier to define its layout, this will randomize the network, but if you'd like to have a completely empty network for any reason, you can alternatively use Network32Sigmoid::empty(&structure).

Finally - We define some training data. Since this is an XOR test, we simply have two two vectors stored itself, in a vector. Two values are stored, the first being the input, and the second being the output - These are them put inside another vector to allow for more than one sample of data. In this case we define all possible inputs and outputs, but depending on the nature of the network you don't need to account for every possibility (Obviously, as that's the point of neural networks to start with!)

Finally we run the network, providing a vector with the inputs (0.0 and 0.0). In this case, without AVX, if you'd like to understand what AVX is, check out the documentation for vector multiplication - In this case we can replace noavx with avx2 or avx512 depending on the system.

We then take the output, which as we only have a single output value, we can just take the last value of the vector. compute_X will return a vector containing all the neuron outputs (In this case, 5 values in total, with the first two being the inputs and the last one being the output).