xxxxxxxxxx
86
let trainingData;
let testingData;
loadData()
async function loadData() {
let test = [
{ image: [10,8,51,4], label: 1},
{ image: [2,3,21,34], label: 2},
{ image: [20,13,31,44], label: 3},
{ image: [13,17,61,64], label: 4},
{ image: [15,19,1,24], label: 5},
].map(val => {
const temp = val;
const label = temp.label;
temp.label = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
temp.label[label] = 1;
temp.labelNum = label;
return temp;
})
testingData = test;
let train = [
{ image: [2,3,41,4], label: 2},
].map(val => {
const temp = val;
const label = temp.label;
temp.label = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
temp.label[label] = 1;
return temp;
})
trainingData = train;
addData();
}
const options = {
inputs: 784,
outputs: 1,
task: 'classification',
debug: true
}
const nn = ml5.neuralNetwork(options);
/*
The data is an array of objects:
[{..},{..},{..},...{..},{..}]
Where each object looks like this:
{image: Array(784), label: Array(10)}
Where "image" is an array of greyscale pixel values
and label is an array representing the label, for example
0 => [1,0,0,0,0,0,0,0,0,0]
1 => [0,1,0,0,0,0,0,0,0,0]
*/
function addData() {
for(let datapt of trainingData) {
nn.addData(datapt.image, datapt.label);
}
console.log('DATA ADDED!');
train();
}
function train() {
nn.normalizeData();
const options = {
epochs: 20
}
nn.train(options, finishedTraining)
}
async function finishedTraining() {
console.log('FINISHED TRAINING!');
console.log('Use test(index) to test NN')
}
function test(index) {
console.log('Label:' +testingData[index].labelNum);
console.log(testingData[index].image);
nn.classify(testingData[index].image, gotResults);
}
function gotResults(error, results) {
if(error) console.error(error);
else console.log(results);
}