Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use super::Matrix;
- use super::Vector;
- use std::cell::RefCell;
- use std::rc::Rc;
- #[derive(Debug)]
- pub struct Network {
- pub vectors: Vec<Rc<RefCell<Vector>>>,
- pub matrices: Vec<Rc<RefCell<Matrix>>>,
- }
- impl Network {
- /// Creates a new network with the given vectors and matrices.
- #[allow(dead_code)]
- pub fn new(vectors: Vec<Rc<RefCell<Vector>>>, matrices: Vec<Rc<RefCell<Matrix>>>) -> Network {
- Network { vectors, matrices }
- }
- /// Executes this network in a feed forward fashion.
- #[allow(dead_code)]
- pub fn forward(&mut self, input: Vec<f32>) -> Vec<f32> {
- // load data into input vector.
- self.vectors[0].borrow_mut().set(input);
- // feed forward data.
- for i in 0..self.matrices.len() {
- let mut output = self.vectors [i + 1].borrow_mut();
- let input = self.vectors [i + 0].borrow();
- let matrix = self.matrices[i + 0].borrow();
- // multiply forward and write to output.
- output.set(matrix.forward(&input).data);
- output.activate(|x| {
- let exp_0 = (-x).exp();
- let exp_1 = (x).exp();
- (exp_0 - exp_1) / (exp_0 + exp_1)
- });
- }
- // unload data
- self.vectors.last().unwrap().borrow().data.clone()
- }
- /// Creates a new network with the given size constraints.
- #[allow(dead_code)]
- pub fn create(sizes: Vec<usize>) -> Network {
- let vectors = sizes
- .iter()
- .map(|size| Rc::new(RefCell::new(Vector::new(*size))))
- .collect::<Vec<_>>();
- let matrices = (0..vectors.len() - 1)
- .map(|i| {
- let input = vectors[i].borrow();
- let output = vectors[i + 1].borrow();
- Rc::new(RefCell::new(Matrix::random(input.width, output.width)))
- })
- .collect::<Vec<_>>();
- Network::new(vectors, matrices)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement