only_brain/lib.rs
1//! # Only Brain
2//!
3//! A very simple Neural Network library built in Rust with the objective to allow
4//! the user to create, manipulate and train a neural network directly. The user has
5//! direct access to weights and biases of the network, allowing them to implement
6//! their own training and manipulation methods.
7//!
8//! # Example
9//!
10//! The input and output widths are part of the network's type, so a wrongly sized
11//! input is a compile error. Hidden layers are given at construction time, and weights
12//! and biases are plain arrays, slices or `Vec`s.
13//!
14//! ```
15//! use only_brain::NeuralNetwork;
16//!
17//! // A 2 -> 2 -> 1 network.
18//! let mut nn = NeuralNetwork::<2, 1>::new(&[2]);
19//!
20//! // One row per neuron, one weight per neuron of the previous layer.
21//! nn.set_layer_weights(1, &[[0.1, 0.2],
22//! [0.3, 0.4]]);
23//! nn.set_layer_biases(1, &[0.1, 0.2]);
24//!
25//! nn.set_layer_weights(2, &[[0.9, 0.8]]);
26//! nn.set_layer_biases(2, &[0.1]);
27//!
28//! let output = nn.feed_forward(&[0.5, 0.2]);
29//!
30//! println!("{:?}", output);
31//! ```
32//!
33//! # Training it your way
34//!
35//! The library leaves learning to you. Two views of the same network make that easy:
36//!
37//! - **Per layer**: [`NeuralNetwork::layer_weights`], [`NeuralNetwork::set_layer_biases`]
38//! and friends, for methods that reason about layers, such as backpropagation.
39//! - **Flat**: [`NeuralNetwork::parameters`], [`NeuralNetwork::set_parameters`] and
40//! [`NeuralNetwork::from_parameters`], for methods that search a list of numbers,
41//! such as genetic algorithms. A genome of
42//! [`NeuralNetwork::parameter_count_for`] genes is a network.
43//!
44//! ```
45//! use only_brain::{ActivationFunction, NeuralNetwork};
46//!
47//! /// Scores a genome, as a genetic algorithm's fitness function would.
48//! fn fitness(genome: &[f64]) -> f64 {
49//! let mut nn = NeuralNetwork::<2, 1>::from_parameters(&[3], genome);
50//! nn.set_activation_function(ActivationFunction::Tanh);
51//! nn.set_output_activation(ActivationFunction::Sigmoid);
52//!
53//! let [output] = nn.feed_forward(&[1.0, 0.0]);
54//! -(1.0 - output).powi(2)
55//! }
56//!
57//! let genome = vec![0.1; NeuralNetwork::<2, 1>::parameter_count_for(&[3])];
58//! println!("fitness: {}", fitness(&genome));
59//! ```
60//!
61//! Each layer has its own [`ActivationFunction`], and [`dump_model`] and
62//! [`load_model`] save and load networks in a versioned format that keeps reading
63//! files written by earlier versions.
64mod neural_network;
65mod layer;
66mod activation_functions;
67mod perceptron;
68
69mod io;
70mod bvector;
71
72pub use io::*;
73pub use neural_network::*;
74pub use perceptron::*;
75pub use activation_functions::*;
76pub use bvector::*;
77
78
79/// Compiles and runs the README's examples as doctests, so they cannot go stale.
80#[doc = include_str!("../README.md")]
81#[cfg(doctest)]
82pub struct ReadmeDoctests;