-
Notifications
You must be signed in to change notification settings - Fork 1
/
Neuron.mjs
69 lines (57 loc) · 1.79 KB
/
Neuron.mjs
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
import { Sigmoid } from "./Activators";
import { Synapse } from './Synapse';
import { NeuralFactor } from "./NeuralFactor";
export class Neuron {
constructor(parentLayer = null, activator = Sigmoid) {
this.bias = this.initBias();
this.error = 0;
this.synapses = new Map();
this.output = 0;
this.activator = activator;
this.parentLayer = parentLayer;
}
initBias() {
return new NeuralFactor();
}
findSynapse(neuron) {
return this.synapses.get(neuron);
}
addSynapse(sourceNeuron) {
const synapse = new Synapse(sourceNeuron, this, new NeuralFactor());
this.synapses.set(sourceNeuron, synapse);
}
pulse() {
let output = 0;
this.synapses.forEach(synapse => {
output += synapse.fromNeuron.output * synapse.factor.weight;
});
this.output = this.activator.calculate(output + this.bias.weight);
};
train(learningRate) {
this.bias.weight += this.bias.delta * learningRate;
this.bias.delta = 0;
this.synapses.forEach(synapse => synapse.train(learningRate));
}
updateDelta() {
this.bias.delta += this.error * this.bias.weight;
}
updateError() {
let error = 0;
this.parentLayer.nextLayer
.getNeurons()
.forEach((neuron) => {
error += (neuron.error * neuron.findSynapse(this).factor.weight) * this.activator.derivate(this.output);
});
this.error = error;
}
}
export class OutputNeuron extends Neuron {
updateError(desiredResult) {
this.error = (desiredResult - this.output) * this.activator.derivate(this.output);
}
}
export class InputNeuron extends Neuron {
initBias() {
return new NeuralFactor(0);
}
}