ann-js
Artificial neural network in vanilla JS
This is a 3-layer neural network that uses sigmoid activation function
and stochastic gradient descent as its backpropagation algorithm.
Installation
Install from the npm repository:
npm install ann-js
Small example
Teaching the network logical XOR operation:
const NeuralNetwork = require("./3layer.js");
const NN = NeuralNetwork(2, 7, 1, 0.6);
const inputs = [
{ input: [1, 1], expected: 0 },
{ input: [1, 0], expected: 1 },
{ input: [0, 1], expected: 1 },
{ input: [1, 1], expected: 0 }
];
for (let i = 0; i < 10000; i++) {
for (let j = 0; j < inputs.length; j++) {
NN.train(inputs[j]);
}
}
for(let i = 0; i < inputs.length; i++) {
console.log("input:", inputs[i].input, "| output:", NN.test(inputs[i].input));
}
Methods
Constructor: NeuralNetwork(numInputs, numHidden, numOutputs, [ learningRate, [ bias ]])
Learning rate is by default set to 0.5 and bias si set to 1.
const NN = NeuralNetwork(1, 3, 2);
const NN = NeuralNetwork(2, 1, 2, 0.9, 2);
.train(trainObject)
Trains the network on a single training example
NN.train({ input: [1, 0], expected: 1 });
NN.train({ input: [1, 1, 1], expected: [1, 0] });
The .input property is what the network will be fed with, .expected is the result
we're hoping to see.
.test(input)
Performs a single feed forward on the network and returns the result
const NN = NeuralNetwork(1, 2, 1);
NN.test(7);
const NN = NeuralNetwork(1, 2, 2);
NN.test(14);
.load(file, callback) && .save(file, callback)
Asynchronously saved or loads the weights of the network.
NN.load("saved.json", err => {
if(err) {
return console.error(err);
}
});
NN.save("saved.json", err => {
if(err) {
return console.error(err);
}
});
.loadSync(file) & .saveSync(file)
Synchronous versions of .load & .sync
NN1.loadSync("saved1.json");
NN2.loadSync("saved2.json");