Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const uid = require("cuid");
- function Neuron() {
- this.id = uid(); // ID
- this.bias = bias == undefined ? Math.random() * 2 - 1 : bias; // this.bias ∈ ℝ && -1 < this.bias < 1
- // Incoming Connections
- this.incoming = {
- neurons: {}, // new Map()
- weights: {} // new Map()
- }
- // Outgoing Connections
- this.outgoing = {
- neurons: {}, // new Map()
- weights: {} // new Map()
- }
- this._output; // f'(x)
- this.output; // f(x)
- this.error; // E'(f(x))
- this.connect = function(neuron, weight) {
- this.outgoing.neurons[neuron.id] = neuron;
- neuron.incoming.neurons[this.id] = this;
- this.outgoing.weights[neuron.id] = neuron.incoming.weights[this.id] = weight == undefined ? Math.random() * 2 - 1 : weight; // weight ∈ ℝ && -1 < weight < 1
- }
- this.activate = function(input) {
- const self = this;
- function sigmoid(x) { return 1 / (1 + Math.exp(-x)) } // f(x) = 1 / (1 + e^(-x))
- function _sigmoid(x) { return sigmoid(x) * (1 - sigmoid(x)) } // f'(x) = f(x) * (1 - f(x))
- // Input Neurons
- if(input) {
- this._output = 1; // f'(x)
- this.output = input; // f(x)
- }
- // Hidden/Output Neurons
- else {
- // Σ (x • w)
- const sum = Object.keys(this.incoming.targets).reduce(function(total, target, index) {
- return total += self.incoming.targets[target].output * self.incoming.weights[target];
- }, this.bias);
- this._output = _sigmoid(sum); // f'(x)
- this.output = sigmoid(sum); // f(x)
- }
- return this.output;
- }
- }
- module.exports = Neuron;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement