Skip to content

Commit 7dfb1a0

Browse files
committed
added test example
1 parent c6738fa commit 7dfb1a0

File tree

3 files changed

+71
-4
lines changed

3 files changed

+71
-4
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ npm run build
1919
This will create a build in the dist folder.
2020

2121

22-
Open `test/index.html` in the browser to see the build working.
22+
Open `test/index.html` in the browser to see the build working, running an example from the ml5 website.
2323

2424

2525
## Process

test/index.html

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@
66
<meta name="viewport" content="width=device-width, initial-scale=1.0">
77
<title>Document</title>
88
<script src="../package/dist/ml5.js"></script>
9-
<script src="script.js"></script>
9+
1010

1111
</head>
1212
<body>
13-
13+
<script src="script.js"></script>
1414
</body>
1515
</html>

test/script.js

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,69 @@
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+
];
213

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

Comments
 (0)