NeuralNet

by SwampFall

JavaScript

function Perceptron(val) {
	this.init(val);
}

Perceptron.prototype = {
	init : function(val) {
  	this.value = val;
  },
  
  activate : function() {
  	this.value = this.value;
  }
}

function Weight(val) {
  this.init(val);
}

Weight.prototype = {
	init : function(val) {
  	this.value = val;
  }
}

function Layer(values, count) {
	this.init(values, count);
}

Layer.prototype = {
	init : function(values, count) {
  	this.nodes = [];
    this.weights = [];
    for (var i = 0; i < values.length; i++) {
    	this.nodes.push(new Perceptron(values[i]));
    }
    for (var i = 0; i < count; i++) {
    	this.weights.push(new Weight(Math.random()));
    }
  },
  
  forward : function(prevLayer) {
  	for (var i = 0; i < this.nodes.length; i++) {
     	this.nodes[i].value = 0;
    	for (var j = 0; j < this.weights.length; j++) {
        this.nodes[i].value += this.weights[j].value * prevLayer.nodes[j].value;
      }
      this.nodes[i].activate();
    }
  }
}

function Network(layers) {
	this.init(layers);
}

Network.prototype = {
	init : function(layers) {
  	this.layers = [];
    for (var i = 0; i < layers.length; i++) {
    	if (i <= 0) {
      	this.layers.push(new Layer(layers[i], 0));
      } else {
    		this.layers.push(new Layer(layers[i], layers[i - 1].length));
      }
    }
    this.output = this.layers[this.layers.length - 1].nodes;
  },
  
  forward : function() {
  	for (var i = 1; i < this.layers.length; i++) {
    	this.layers[i].forward(this.layers[i - 1]);
    }
  },
  
  train : function() {
  
  }
}

var input = [
	[5, 3, 7, 2, 1],
  [8, 3, 9, 4, 2, 7, 1],
  [1, 2, 3, 4],
  [1, 1, 1]];

var network = new Network(input);

alert(network.output[0].value);

network.forward();

alert(network.output[0].value);