Skip to main content

Crate only_brain

Crate only_brain 

Source
Expand description

§Only Brain

A very simple Neural Network library built in Rust with the objective to allow the user to create, manipulate and train a neural network directly. The user has direct access to weights and biases of the network, allowing them to implement their own training and manipulation methods.

§Example

The input and output widths are part of the network’s type, so a wrongly sized input is a compile error. Hidden layers are given at construction time, and weights and biases are plain arrays, slices or Vecs.

use only_brain::NeuralNetwork;

// A 2 -> 2 -> 1 network.
let mut nn = NeuralNetwork::<2, 1>::new(&[2]);

// One row per neuron, one weight per neuron of the previous layer.
nn.set_layer_weights(1, &[[0.1, 0.2],
                          [0.3, 0.4]]);
nn.set_layer_biases(1, &[0.1, 0.2]);

nn.set_layer_weights(2, &[[0.9, 0.8]]);
nn.set_layer_biases(2, &[0.1]);

let output = nn.feed_forward(&[0.5, 0.2]);

println!("{:?}", output);

§Training it your way

The library leaves learning to you. Two views of the same network make that easy:

use only_brain::{ActivationFunction, NeuralNetwork};

/// Scores a genome, as a genetic algorithm's fitness function would.
fn fitness(genome: &[f64]) -> f64 {
    let mut nn = NeuralNetwork::<2, 1>::from_parameters(&[3], genome);
    nn.set_activation_function(ActivationFunction::Tanh);
    nn.set_output_activation(ActivationFunction::Sigmoid);

    let [output] = nn.feed_forward(&[1.0, 0.0]);
    -(1.0 - output).powi(2)
}

let genome = vec![0.1; NeuralNetwork::<2, 1>::parameter_count_for(&[3])];
println!("fitness: {}", fitness(&genome));

Each layer has its own ActivationFunction, and dump_model and load_model save and load networks in a versioned format that keeps reading files written by earlier versions.

Macros§

bvector
Macro to construct a BVector with compile-time dimension inferred from the number of elements provided.

Structs§

BVector
This module provides a vector type BVector that is optimized for compile-time dimension and uses SIMD operations for performance.
NeuralNetwork
Neural Network
Perceptron
Perceptron

Enums§

ActivationFunction
The function a layer applies to each neuron’s weighted sum.
ModelError
Something that went wrong while saving or loading a model.

Constants§

MODEL_FORMAT_VERSION
The model format version dump_model and write_model write. load_model and read_model read this version and every earlier one.

Functions§

binary_step
dump_model
Writes a model to path, in the newest format version.
get_activation_function
Returns the plain function behind an ActivationFunction.
identity
load_model
Reads a model from path, checking that its shape matches IN and OUT.
read_model
Reads one model from any reader, checking that its shape matches IN and OUT.
relu
sigmoid
tanh
write_model
Writes a model to any writer, in the newest format version.