|
| 1 | +// Step 1: load data or create some data |
| 2 | +let data = [ |
| 3 | + { r: 255, g: 0, b: 0, color: "red-ish" }, |
| 4 | + { r: 254, g: 0, b: 0, color: "red-ish" }, |
| 5 | + { r: 253, g: 0, b: 0, color: "red-ish" }, |
| 6 | + { r: 0, g: 255, b: 0, color: "green-ish" }, |
| 7 | + { r: 0, g: 254, b: 0, color: "green-ish" }, |
| 8 | + { r: 0, g: 253, b: 0, color: "green-ish" }, |
| 9 | + { r: 0, g: 0, b: 255, color: "blue-ish" }, |
| 10 | + { r: 0, g: 0, b: 254, color: "blue-ish" }, |
| 11 | + { r: 0, g: 0, b: 253, color: "blue-ish" }, |
| 12 | +]; |
| 13 | + |
| 14 | +let classifer; |
| 15 | +let r = 255; |
| 16 | +let g = 0; |
| 17 | +let b = 0; |
| 18 | +let rSlider, gSlider, bSlider; |
| 19 | +let label = "training"; |
| 20 | + |
| 21 | +function setup() { |
| 22 | + createCanvas(640, 240); |
| 23 | + rSlider = createSlider(0, 255, 255).position(10, 20); |
| 24 | + gSlider = createSlider(0, 255, 0).position(10, 40); |
| 25 | + bSlider = createSlider(0, 255, 0).position(10, 60); |
| 26 | + |
| 27 | + // Step 2: set your neural network options |
| 28 | + let options = { |
| 29 | + task: "classification", |
| 30 | + debug: true, |
| 31 | + }; |
| 32 | + |
| 33 | + // Step 3: initialize your neural network |
| 34 | + classifier = ml5.neuralNetwork(options); |
| 35 | + |
| 36 | + // Step 4: add data to the neural network |
| 37 | + for (let i = 0; i < data.length; i++) { |
| 38 | + let item = data[i]; |
| 39 | + let inputs = [item.r, item.g, item.b]; |
| 40 | + let outputs = [item.color]; |
| 41 | + classifier.addData(inputs, outputs); |
| 42 | + } |
| 43 | + |
| 44 | + // Step 5: normalize your data; |
| 45 | + classifier.normalizeData(); |
| 46 | + |
| 47 | + // Step 6: train your neural network |
| 48 | + const trainingOptions = { |
| 49 | + epochs: 32, |
| 50 | + batchSize: 12, |
| 51 | + }; |
| 52 | + classifier.train(trainingOptions, finishedTraining); |
| 53 | +} |
| 54 | +// Step 7: use the trained model |
| 55 | +function finishedTraining() { |
| 56 | + classify(); |
| 57 | +} |
| 58 | + |
| 59 | +// Step 8: make a classification |
| 60 | +function classify() { |
| 61 | + const input = [r, g, b]; |
| 62 | + classifier.classify(input, handleResults); |
| 63 | +} |
| 64 | + |
| 65 | +function draw() { |
| 66 | + r = rSlider.value(); |
| 67 | + g = gSlider.value(); |
| 68 | + b = bSlider.value(); |
| 69 | + background(r, g, b); |
| 70 | + textAlign(CENTER, CENTER); |
| 71 | + textSize(64); |
| 72 | + text(label, width / 2, height / 2); |
| 73 | +} |
| 74 | + |
| 75 | +// Step 9: define a function to handle the results of your classification |
| 76 | +function handleResults(error, results) { |
| 77 | + if (error) { |
| 78 | + console.error(error); |
| 79 | + return; |
| 80 | + } |
| 81 | + label = results[0].label; |
| 82 | + // console.log(results); // {label: 'red', confidence: 0.8}; |
| 83 | + classify(); |
| 84 | +} |
0 commit comments