xxxxxxxxxx
75
let currentNumbers = [0,0];
let nn;
let training = true;
let classifyX;
let classifyY;
let output = "";
function setup() {
createCanvas(400, 400);
let options = {
// object literal
task: "regression",
debug: true,
};
nn = ml5.neuralNetwork(options);
}
function draw() {
background(255);
textSize(48);
text(currentNumbers[0], 50, height/2);
text(currentNumbers[1], width-50, height/2);
text(output, width/2, height-100);
}
function mousePressed() {
if (training) {
let inputs = [currentNumbers[0], currentNumbers[1]];
let average = (currentNumbers[0] + currentNumbers[1]) /2;
let outputs = [ average ];
console.log("Added " + currentNumbers[0] + " AVG " + currentNumbers[1] + " = " + average);
nn.addData(inputs, outputs);
} else {
let inputs = [currentNumbers[0], currentNumbers[1]];
nn.predict(inputs, donePredicting);
}
}
function keyPressed() {
if (key >= '0' && key <= '9') {
currentNumbers.push(parseInt(key));
if(currentNumbers.length > 2) {
currentNumbers.shift(); // keep only last two numbers
}
} else if(key == "s" || key == "S") {
nn.saveData();
} else if(key == "1" || key == "L") {
nn.loadData("data.json");
} else if (key == "t") {
nn.normalizeData();
let options = {
epochs: 64,
batchSize: 12,
} ;
nn.train(options, doneTraining);
}
}
function doneTraining() {
console.log("Done training!");
training = false;
}
function donePredicting(error, results) {
console.log(results);
output = results[0].value;
}