-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultilayerperceptron.js
83 lines (67 loc) · 2.44 KB
/
multilayerperceptron.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//requires: Perceptron
//class enclosure
(function() {
"use strict";
//constructor
const MultiLayerPerceptron = function(/*numInputs, [numHidden1, numHidden2, ...] numOutputs*/) {
this.numInputs = arguments[0];
this.numOutputs = arguments[arguments.length - 1];
this.numLayers = arguments.length - 1;
this.layers = [];
this.previousState = [];
for (let i = 0; i < this.numLayers; i++) {
const numInputs = arguments[i];
const numOutputs = arguments[i + 1];
this.layers[i] = new ml.Perceptron(numInputs, numOutputs);
this.previousState[i] = this.layers[i].previousState;
}
};
const proto = MultiLayerPerceptron.prototype;
//public
proto.setActivationFunction = function(args) { //accepts a string or a function
for (let i = 0; i < this.layers.length; i++) {
this.layers[i].setActivationFunction(args);
}
};
proto.calculate = function(inputs) {
let cache = inputs;
for (let i = 0; i < this.numLayers; i++) {
cache = this.layers[i].calculate(cache);
}
return cache;
};
proto.calculateWithState = function(inputs) {
let cache = inputs;
for (let i = 0; i < this.numLayers; i++) {
cache = this.layers[i].calculateWithState(cache);
}
return cache;
};
proto.randomize = function() {
for (let i = 0; i < this.layers.length; i++) {
this.layers[i].randomize();
}
};
proto.toStaggeredArray = function() {
const chromosome = [];
for (let p = 0; p < this.numLayers; p++) {
const layer = this.layers[p];
const gene = layer.toStaggeredArray();
for (let base = 0; base < gene.length; base++) {
chromosome.push(gene[base]);
};
};
return chromosome;
};
proto.fromStaggeredArray = function(chromosome) {
let i = 0;
for (let gene = 0; gene < this.numLayers; gene++) {
const layer = this.layers[gene];
const numBases = layer.numOutputs * layer.numInputs + layer.numOutputs;
layer.fromStaggeredArray(chromosome.slice(i, i + numBases));
i += numBases;
};
};
//attach class to namespace
ml.MultiLayerPerceptron = MultiLayerPerceptron;
})();