-
Notifications
You must be signed in to change notification settings - Fork 5
/
4_transfer-learning.html
63 lines (47 loc) · 2.01 KB
/
4_transfer-learning.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
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/[email protected]"></script>
<script src="../webcam.js"></script>
<video autoplay playsinline muted id="webcam" width="640" height="480"></video>
<h1 id="description"></h1>
<div>
<input id="label" type="text">
<button id="train">Train</button>
</div>
<script>
let model;
let webcamElement;
let classifier;
const classLabels = new Set();
window.onload = async () => {
const trainButton = document.getElementById('train');
const description = document.getElementById('description');
webcamElement = await setupWebcam(document.getElementById('webcam'));
model = await mobilenet.load();
classifier = knnClassifier.create();
trainButton.addEventListener('click', addTrainingExample);
while (true) {
if (classifier.getNumClasses() > 0) {
const activation = model.infer(webcamElement, 'conv_preds');
const prediction = await classifier.predictClass(activation);
if (prediction.confidences[prediction.classIndex] > 0.5) {
description.innerText = [...classLabels][prediction.classIndex];
} else {
description.innerText = "Not sure"
}
} else {
description.innerText = "Nothing trained yet"
}
await tf.nextFrame();
}
};
function addTrainingExample() {
const label = document.getElementById('label').value.toUpperCase();
if (!label) return;
classLabels.add(label);
const classId = [...classLabels].indexOf(label);
const activation = model.infer(webcamElement, 'conv_preds');
classifier.addExample(activation, classId);
console.log('added training example for ' + label)
}
</script>