-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsketch.js
More file actions
121 lines (101 loc) · 2.41 KB
/
sketch.js
File metadata and controls
121 lines (101 loc) · 2.41 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
const canvasW = 400;
const canvasH = 400;
let button = null;
let button2 = null;
let pFrameRate = null;
let trainingPoints = [];
let brain = null;
let letstrain = false;
let showPercentage = false;
function f(x) {
return 2 * x + 50;
}
function setup() {
brain = new Perceptron();
createCanvas(canvasW, canvasH);
button = createButton('Start training');
button.mousePressed(onClickOnTrainButton);
button2 = createButton('Show percentage');
button2.mousePressed(onClickOnShowPercentButton);
pFrameRate = createP('');
for (let i = 0; i < 2000; i++) {
trainingPoints.push(new Point(random(-(canvasW / 2), canvasW / 2), random(-(canvasH / 2), canvasH / 2), f));
}
show();
}
function show() {
background(235);
translate(canvasW / 2, canvasH / 2);
fill(0);
for (let i = 0; i < 500; i++) {
let point = trainingPoints[i];
let guess = brain.guess([point.x, point.y]);
point.color = brain.getColor(guess);
point.show();
}
stroke(3);
strokeWeight(3);
line(-(canvasW / 2), f(-(canvasW / 2)), canvasW / 2, f(canvasW / 2));
displayGuessedLine();
if (showPercentage) {
displayPercentage();
}
}
let tick = 0;
function draw() {
if (tick === 10) {
pFrameRate.html(nfc(frameRate(), 0));
tick = 0;
}
if (letstrain) {
brain.trainAll(trainingPoints);
show();
}
tick++;
}
function displayGuessedLine() {
let x1 = -(canvasW / 2);
let y1 = (-brain.weights[2] - brain.weights[0] * x1) / brain.weights[1];
let x2 = canvasW / 2;
let y2 = (-brain.weights[2] - brain.weights[0] * x2) / brain.weights[1];
stroke(100);
strokeWeight(2);
line(x1, y1, x2, y2);
}
function onClickOnTrainButton() {
letstrain = !letstrain;
button.html((letstrain ? 'Stop' : 'Start') + ' training');
}
function onClickOnShowPercentButton() {
showPercentage = !showPercentage;
button2.html((showPercentage ? 'Hide' : 'Show') + ' percentage');
}
function keyTyped() {
if (key === 't') {
onClickOnTrainButton();
}
if (key === 'p') {
onClickOnShowPercentButton();
}
}
function displayPercentage() {
let good = 0;
let iterations = 1000;
for (let i = 0; i < iterations; i++) {
let pt = trainingPoints[i];
let guess = brain.guess([pt.x, pt.y]);
if (guess === pt.class) {
good++
}
}
let percentage = good / iterations * 100;
let xP = -(canvasW / 2) + 5;
let yP = canvasH / 2 - 55;
fill(255);
rect(xP, yP, 150, 50);
fill(0);
stroke(0);
strokeWeight(2);
textSize(32);
text(nfc(percentage, 2) + '%', xP + 5, yP + 35);
}