-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathneuron.js
107 lines (79 loc) · 1.54 KB
/
neuron.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
'use strict';
var sprintf = require('printf');
class AbstractNeuron {
constructor(n, W) {
if (W.length !== n + 1) {
throw new RangeError('Invalid weight array length');
}
this.n = n;
this.W = W;
}
s(X) {
if (X.length !== this.n) {
throw new RangeError('Invalid input array length');
}
var s = this.W[this.n];
for(var i = 0; i < this.n; i++) {
s += this.W[i] * X[i];
}
return s;
}
toString() {
return this.W.map(w => sprintf('%15.8f', w)).join(' ');
}
}
class AbstractTresholdNeuron extends AbstractNeuron {
y(X) {
return this.s(X) > 0 ? 1 : -1;
}
}
class Perceptron extends AbstractTresholdNeuron {
train(X, d) {
var y = this.y(X);
if(y !== d) {
this.W[this.n] += d;
for(var i = 0; i < this.n; i++) {
this.W[i] += d * X[i];
}
}
return y - d;
}
}
class AbstractAdaline extends AbstractTresholdNeuron {
constructor(n, W, eta = 0.5) {
super(n, W);
if(eta < 0) {
throw new RangeError('Eta cannot be negative');
}
this.eta = eta;
}
}
class Adaline extends AbstractAdaline {
train(X, d) {
var s = this.s(X),
epsilon = d - s;
var k = this.eta * epsilon;
this.W[this.n] += k;
for(var i = 0; i < this.n; i++) {
this.W[i] += k * X[i];
}
return -epsilon;
}
}
class AdalineRLS extends AbstractAdaline {
train(X, d) {
var s = this.s(X),
epsilon = d - s;
var k = this.eta * epsilon;
this.W[this.n] += k;
for(var i = 0; i < this.n; i++) {
this.W[i] += k * X[i];
}
return -epsilon;
}
}
module.exports = {
Perceptron,
Adaline,
AdalineRLS
};