-
Notifications
You must be signed in to change notification settings - Fork 1
/
perceptron.js
64 lines (53 loc) · 1.37 KB
/
perceptron.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
const sign = (x) => { return x > 0 ? 1 : -1; };
const loop = (list, vls) => {
for(let [el, y] of list){
let sum = 0;
for(let i in el){
sum += vls[i] * el[i];
}
let p = sign(sum);
if(y !== p){
for(let i in vls)
vls[i] = vls[i] + (y * el[i]);
return false;
}
}
return true;
};
const perceptron = function* (list){
let vls = [0, Math.random(), Math.random()];
yield vls;
while(!loop(list, vls)){
yield vls;
}
yield vls;
};
const doubleIn = (a, b) => Math.random() * Math.abs(b - a) + a;
const zipWith = function*(f, xs, ys) {
for (let i = 0; i < xs.length && i < ys.length; i++) {
yield f(xs[i], ys[i]);
}
};
const dot = (xs, ys) => {
let sum = 0;
for (let z of zipWith((x, y) => x * y, xs, ys)) {
sum += z;
}
return sum;
};
const generateTestData = function(n) {
const x1 = doubleIn(-1, 1);
const x2 = doubleIn(-1, 1);
const y1 = doubleIn(-1, 1);
const y2 = doubleIn(-1, 1);
const ws = [(x2 * y1 - x1 * y2), y2-y1, x1-x2];
let list = [];
for (let i = 0; i < n; i++) {
const x = doubleIn(-1, 1);
const y = doubleIn(-1, 1);
const v = [1, x, y];
list.push([v, sign(dot(ws, v))]);
}
return [ws, list];
};
let [ws, list] = generateTestData(100);