-
Notifications
You must be signed in to change notification settings - Fork 5
/
knn.js
126 lines (93 loc) · 1.99 KB
/
knn.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
let class_val;
let status='stop';
let input=[];
let output=[];
let class_lab;
let knnClassifier;
let classes;
function setup(){
var canvas=createCanvas(500,500);
canvas.parent('sketch-holder');
background(255,255,255);
strokeWeight(2);
classes=createSelect();
classes.position(600,300);
classes.option('A');
classes.option('B');
classes.option('C');
knnClassifier = ml5.KNNClassifier();
training_start=createButton('Start Training');
training_start.position(600,350);
training_start.mousePressed(training);
training_stop=createButton('Stop Training');
training_stop.position(600,400);
training_stop.mousePressed(training_stops);
predict=createButton('Predict');
predict.position(600,450);
predict.mousePressed(predicts);
reset=createButton('Reset');
reset.position(600,500);
reset.mousePressed(reloads);
}
function reloads(){
knnClassifier.clearAllLabels();
location.reload();
}
function training_stops(){
status='stop';
}
function predicts(){
status='predict';
}
function training(){
status='train';
}
function gotresults(err,result){
if(err){
console.error(err);
}
else if (mouseX<=500 && mouseY<=500) {
class_lab=result.label;
console.log(result.label);
if(class_lab=='A'){
fill(255,0,0);
}
else if(class_lab=='B'){
fill(0,255,0);
}
else if(class_lab=='C'){
fill(0,0,255);
}
ellipse(mouseX,mouseY,30,30);
text(class_lab,mouseX,mouseY);
}
}
function mousePressed(){
stroke(0);
if(status=='train'){
class_val=classes.value();
if(class_val=='A'){
fill(255,0,0);
}
else if(class_val=='B'){
fill(0,255,0);
}
else if(class_val=='C'){
fill(0,0,255);
}
if (mouseX<=500 && mouseY<=500) {
console.log(status);
ellipse(mouseX,mouseY,30,30);
text(class_val,mouseX,mouseY);
knnClassifier.addExample([mouseX,mouseY],class_val);
}
}
if(status=='predict'){
if(knnClassifier.getNumLabels()>0){
console.log(status);
knnClassifier.classify([mouseX,mouseY],gotresults);
}
}
}
function draw(){
}