Skip to content

Commit

Permalink
Add Network class
Browse files Browse the repository at this point in the history
  • Loading branch information
umcconnell committed Jul 2, 2019
1 parent 7f06732 commit dcb323c
Showing 1 changed file with 86 additions and 0 deletions.
86 changes: 86 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

0 comments on commit dcb323c

Please sign in to comment.