brainy 0.2.3

A library for neural networks.
Documentation
//! Use to create a layer in a neural network.

use crate::matrix::fill;
use crate::matrix::Matrix;

/**
Represents the maps between layers.
enum(usize, usize) is input and output dimension in that order.
If enum(usize), the input and output dimension is the same.
*/
pub enum Map
{
    MatrixMultiply(usize, usize),
    Sigmoid(usize)
}

/// Matrix multiplication map where the parameters are in an unwrapped matrix.
fn matrix_multiply(a: Matrix, x: Matrix) -> Matrix
{
    Matrix::wrap(a, x.rows) * x
}

/// Element wise sigmoid map: f(x) = 1/(1 + exp(-x))
fn sigmoid(_a: Matrix, x: Matrix) -> Matrix
{
    let mut y = x;
    for i in 0..y.elements.len()
    {
        let u: f64 = -1.0 * y[(i, 0)];
        y[(i, 0)] = 1.0 / (1.0 + u.exp());
    }
    y
}

/// Layer in a neural network.
pub struct Layer
{
    /// Parameter column vector
    pub a: Matrix,
    
    /// Input column vector
    pub x: Matrix,

    /// Function pointer for feedforward map
    pub feedforwardptr: fn(Matrix, Matrix) -> Matrix,
}

impl Layer
{
    pub fn new(map: Map) -> Self
    { 
        match map
        {
            Map::MatrixMultiply(i, o) => 
            {
                let x = Matrix::new(i, 1);
                let mut a = Matrix::new(i * o, 1);
                fill(&mut a.elements);
                Self {a, x, feedforwardptr: matrix_multiply}
            }

            Map::Sigmoid(d) => 
            {
                let x = Matrix::new(d, 1);
                let a = Matrix {rows: 0, cols: 0, elements: Vec::new()};
                Self {a, x, feedforwardptr: sigmoid}
            }
        }
    }

    /// Calls feedforwardptr.
    pub fn feedforward(&self) -> Matrix
    {
        (self.feedforwardptr)(self.a.clone(), self.x.clone())
    }
}