|
| 1 | +// Step 1: load data or create some data |
| 2 | +let data = [ |
| 3 | + { x: 0.99, y: 0.02, label: "right" }, |
| 4 | + { x: 0.76, y: -0.1, label: "right" }, |
| 5 | + { x: -1.0, y: 0.12, label: "left" }, |
| 6 | + { x: -0.9, y: -0.1, label: "left" }, |
| 7 | + { x: 0.02, y: 0.98, label: "down" }, |
| 8 | + { x: -0.2, y: 0.75, label: "down" }, |
| 9 | + { x: 0.01, y: -0.9, label: "up" }, |
| 10 | + { x: -0.1, y: -0.8, label: "up" }, |
| 11 | +]; |
| 12 | + |
| 13 | +let classifer; |
| 14 | +let label = "training"; |
| 15 | + |
| 16 | +let start, end; |
| 17 | + |
| 18 | +function setup() { |
| 19 | + createCanvas(640, 240); |
| 20 | + // Step 2: set your neural network options |
| 21 | + let options = { |
| 22 | + task: "classification", |
| 23 | + debug: true, |
| 24 | + }; |
| 25 | + |
| 26 | + // Step 3: initialize your neural network |
| 27 | + classifier = ml5.neuralNetwork(options); |
| 28 | + |
| 29 | + // Step 4: add data to the neural network |
| 30 | + for (let i = 0; i < data.length; i++) { |
| 31 | + let item = data[i]; |
| 32 | + let inputs = [item.x, item.y]; |
| 33 | + let outputs = [item.label]; |
| 34 | + classifier.addData(inputs, outputs); |
| 35 | + } |
| 36 | + |
| 37 | + // Step 5: normalize your data; |
| 38 | + classifier.normalizeData(); |
| 39 | + |
| 40 | + // Step 6: train your neural network |
| 41 | + classifier.train({ epochs: 100 }, finishedTraining); |
| 42 | +} |
| 43 | +// Step 7: use the trained model |
| 44 | +function finishedTraining() { |
| 45 | + label = "ready"; |
| 46 | +} |
| 47 | + |
| 48 | +// Step 8: make a classification |
| 49 | + |
| 50 | +function draw() { |
| 51 | + background(200); |
| 52 | + textAlign(CENTER, CENTER); |
| 53 | + textSize(64); |
| 54 | + text(label, width / 2, height / 2); |
| 55 | + if (start && end) { |
| 56 | + strokeWeight(8); |
| 57 | + line(start.x, start.y, end.x, end.y); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +function mousePressed() { |
| 62 | + start = createVector(mouseX, mouseY); |
| 63 | +} |
| 64 | + |
| 65 | +function mouseDragged() { |
| 66 | + end = createVector(mouseX, mouseY); |
| 67 | +} |
| 68 | + |
| 69 | +function mouseReleased() { |
| 70 | + let dir = p5.Vector.sub(end, start); |
| 71 | + dir.normalize(); |
| 72 | + let inputs = [dir.x, dir.y]; |
| 73 | + console.log(inputs); |
| 74 | + classifier.classify(inputs, gotResults); |
| 75 | +} |
| 76 | + |
| 77 | +// Step 9: define a function to handle the results of your classification |
| 78 | +function gotResults(error, results) { |
| 79 | + label = results[0].label; |
| 80 | + console.log(results); |
| 81 | +} |
0 commit comments