xxxxxxxxxx
114
// Machine Learning for Artists and Designers
// NYUSH F24 - gohai
let curColor = "green";
let nn;
let training = true;
let classifyX;
let classifyY;
let resultColor = "white";
let resultX = 0;
let resultY = 0;
function setup() {
createCanvas(400, 400);
// For this example to work across all browsers
// "webgl" or "cpu" needs to be set as the backend
ml5.setBackend("webgl");
let options = {
// object literal
task: "classification",
debug: true,
};
nn = ml5.neuralNetwork(options);
}
function draw() {
background(255);
let points = nn.neuralNetworkData.data.raw;
for (let i = 0; i < points.length; i++) {
noStroke();
fill(points[i].ys[0]);
ellipse(points[i].xs[0], points[i].xs[1], 8, 8);
}
if (training == false) {
fill(resultColor);
circle(resultX, resultY, 16);
}
}
function mousePressed() {
if (training) {
// loop to synthesize a couple of
// samples around the mouse position
for (let i = 0; i < 8; i++) {
let inputs = [mouseX + random(-8, 8), mouseY + random(-8, 8)];
let outputs = [curColor];
nn.addData(inputs, outputs);
}
} else {
let inputs = [mouseX, mouseY];
nn.classify(inputs, doneClassifying);
classifyX = mouseX;
classifyY = mouseY;
}
}
function keyPressed() {
if (key == "g" || key == "G") {
curColor = "green";
} else if (key == "r" || key == "R") {
curColor = "red";
} else if (key == "b" || key == "B") {
curColor = "blue";
} else if (key == "s") {
nn.save(); // downloads the trained model
} else if (key == "S") {
nn.saveData(); // downloads the training data
} else if (key == "l") {
// loads the model
nn.load(
{
model: "model.json",
metadata: "model_meta.json",
weights: "model.weights.bin",
},
finishedLoading
);
} else if (key == "L") {
nn.loadData("data.json"); // loads the training data
} 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 doneClassifying(results) {
//console.log(results);
resultColor = results[0].label;
resultX = classifyX;
resultY = classifyY;
}
function finishedLoading() {
console.log("Loaded model!");
training = false;
}