-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrainModel.html
126 lines (105 loc) · 3.37 KB
/
trainModel.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.dom.min.js"></script>
<script src="https://unpkg.com/ml5@0.4.3/dist/ml5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.min.js"></script>
</head>
<body>
<script>
let model;
let targetLabel = 'C';
let state = 'collection';
let myEnv;
let wave;
let notes = {
C: 261.6256,
D: 293.6648,
E: 329.6276
};
let t1 = 0.1; // attack time in seconds
let l1 = 0.7; // attack level 0.0 to 1.0
let t2 = 0.3; // decay time in seconds
let l2 = 0.1; // decay level 0.0 to 1.0
function setup() {
createCanvas(400, 400);
myEnv = new p5.Envelope(t1, l1, t2, l2);
myEnv.setADSR(0.05, 0.1, 0.5, 1);
myEnv.setRange(1.2, 0);
wave = new p5.Oscillator();
wave.setType('sine');
wave.start();
wave.freq(440);
wave.amp(myEnv);
let options = {
inputs: ['x', 'y'],
outputs: ['label'],
task: 'classification',
debug: true
};
model = ml5.neuralNetwork(options);
}
function keyPressed() {
if(key === 't') {
state = 'training';
model.normalizeData();
let options = {
epochs: 200
};
model.train(options, whileTraining, finishedTraining);
} else {
targetLabel = key.toUpperCase();
}
}
function whileTraining(epoch, loss) {
console.log('training ', epoch, loss);
}
function finishedTraining() {
console.log('finished training');
state = 'prediction';
}
function mousePressed() {
let inputs = {
x: mouseX,
y: mouseY
};
if(state == 'collection') {
let target = {
label: targetLabel
};
model.addData(inputs, target);
stroke(0);
noFill();
ellipse(mouseX, mouseY, 24);
fill(0);
noStroke();
textAlign(CENTER, CENTER);
text(targetLabel, mouseX, mouseY);
} else if(state == 'prediction') {
model.classify(inputs, gotResults);
}
}
function gotResults(error, results) {
if(error) {
console.error(error);
return;
}
console.log(results);
stroke(0);
fill(0, 0, 255, 100);
ellipse(mouseX, mouseY, 24);
fill(0);
noStroke();
textAlign(CENTER, CENTER);
let label = results[0].label;
text(label, mouseX, mouseY);
wave.freq(notes[label]);
myEnv.play();
}
</script>
</body>
</html>