|
1 |
| -console.log(ml5); |
| 1 | +// Step 1: load data or create some data |
| 2 | +const 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 | +]; |
2 | 13 |
|
| 14 | +// Step 2: set your neural network options |
| 15 | +const options = { |
| 16 | + task: "classification", |
| 17 | + debug: true, |
| 18 | +}; |
| 19 | + |
| 20 | +// Step 3: initialize your neural network |
| 21 | +const nn = ml5.neuralNetwork(options); |
| 22 | + |
| 23 | +// Step 4: add data to the neural network |
| 24 | +data.forEach((item) => { |
| 25 | + const inputs = { |
| 26 | + r: item.r, |
| 27 | + g: item.g, |
| 28 | + b: item.b, |
| 29 | + }; |
| 30 | + const output = { |
| 31 | + color: item.color, |
| 32 | + }; |
| 33 | + |
| 34 | + nn.addData(inputs, output); |
| 35 | +}); |
| 36 | + |
| 37 | +// Step 5: normalize your data; |
| 38 | +nn.normalizeData(); |
| 39 | + |
| 40 | +// Step 6: train your neural network |
| 41 | +const trainingOptions = { |
| 42 | + epochs: 32, |
| 43 | + batchSize: 12, |
| 44 | +}; |
| 45 | +nn.train(trainingOptions, finishedTraining); |
| 46 | + |
| 47 | +// Step 7: use the trained model |
| 48 | +function finishedTraining() { |
| 49 | + classify(); |
| 50 | +} |
| 51 | + |
| 52 | +// Step 8: make a classification |
| 53 | +function classify() { |
| 54 | + const input = { |
| 55 | + r: 255, |
| 56 | + g: 0, |
| 57 | + b: 0, |
| 58 | + }; |
| 59 | + nn.classify(input, handleResults); |
| 60 | +} |
| 61 | + |
| 62 | +// Step 9: define a function to handle the results of your classification |
| 63 | +function handleResults(error, result) { |
| 64 | + if (error) { |
| 65 | + console.error(error); |
| 66 | + return; |
| 67 | + } |
| 68 | + console.log(result); // {label: 'red', confidence: 0.8}; |
| 69 | +} |
0 commit comments