From dcb323cfa08c0cfe6e616e1937f605d0fd4815ef Mon Sep 17 00:00:00 2001 From: Ulysse McConnell Date: Tue, 2 Jul 2019 16:25:37 +0200 Subject: [PATCH] Add Network class --- lib/index.js | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/lib/index.js b/lib/index.js index 7665afc..b05b770 100644 --- a/lib/index.js +++ b/lib/index.js @@ -212,3 +212,89 @@ export class Layer { return this.next; } } + +/** + * Neural Network Class + * @extends Array + * @example + * // Import Constructors and helpers + * import { Network, Layer, Weights, Biases } from "./index.js"; + * import { sigmoid } from "./helpers.js"; + * + * // Create network + * let network = new Network([2048, 1024, 512, 256]); + * // Run network + * network + * .addWeights() + * .addBiases() + * .connect() + * .run() + * .apply(sigmoid); + */ +export class Network extends Array { + /** + * Creates a neural network with given layers + * @param {Array} layers array of Layer objects or numbers representing layer length + */ + constructor(layers) { + super(...layers.map(el => (el instanceof Layer ? el : new Layer(el)))); + } + + /** + * Adds randomly filled bias matrix with correct dimensions to every layer by calling Biases constructor + * @returns {Network} + */ + addBiases() { + this.forEach((layer, i) => { + if (i > 0) { + layer.addBiases(new Biases(layer.length).fillRandom()); + } + }); + return this; + } + + /** + * Adds randomly filled weight matrix with correct dimensions to every layer by calling Weights constructor + * @returns {Network} + */ + addWeights() { + this.forEach((layer, i) => { + if (i < this.length - 1) { + layer.addWeights( + new Weights(layer.length, this[i + 1].length).fillRandom() + ); + } + }); + return this; + } + + /** + * Applies a function to every layer by calling layer.apply() on every layer + * @param {Function} func mapping function called on every layer with layer.apply() + * @returns {Network} + */ + apply(func) { + this.forEach((layer, i) => (i > 0 ? layer.apply(func) : "")); + return this; + } + + /** + * Connects every layers with its succedding layer by calling layer.connect + * @returns {Network} + */ + connect() { + this.forEach((layer, i) => + i < this.length - 1 ? layer.connect(this[i + 1]) : "" + ); + return this; + } + + /** + * Runs the neural network + * @returns {Network} + */ + run() { + this.forEach(layer => (layer.next ? layer.run() : "")); + return this; + } +}