/* Define the number of nodes in each layer. */
const noinput = 2;
const nohidden = 50000;
const nooutput = 1;
/* Define the exemplars to learn from. */
let training_data = [
{ inputs: [0, 0], outputs: [0] },
{ inputs: [0, 1], outputs: [1] },
{ inputs: [1, 0], outputs: [1] },
{ inputs: [1, 1], outputs: [0] }
];
/* An object to represent our neural network. */
var nn;
/* Our learning rate, when training our neural network. */
const learningrate = 0.1;
/* The amount of time for which the network should be trained per draw() cycle. */
const notrain = 10;
/* The step at which a screenshot should be taken. */
AB.screenshotStep = 200;
/* Whether or not we should show all squares or just the corner squares. */
var showall = false;
/* The size of our canvas, and each individual square within. */
const canvassize = 400;
const squaresize = 40;
/* The number of columns and rows to display in our canvas. */
const cols = 10;
const rows = 10;
/* Generate a random weight for each of our nodes. */
function randomWeight() {
var randomWeight = (AB.randomFloatAtoB(-0.5, 0.5));
console.log("Initialising random weight at: " + randomWeight);
return randomWeight;
}
/* Initialise our neural network. */
function setup() {
createCanvas(canvassize, canvassize);
$.getScript("/uploads/codingtrain/matrix.js", function() {
$.getScript("/uploads/codingtrain/nn.js", function() {
nn = new NeuralNetwork(noinput, nohidden, nooutput);
});
});
}
/* Draw the graphical representation of our neural network being trained. */
function draw() {
/* Determine whether or not our libraries have been loaded yet. */
if (typeof nn == 'undefined') return;
/* Set the learning rate for our neural network. */
nn.setLearningRate(learningrate);
/* Set the background colour. */
background('#ffffcc');
/* Train our neural network 'n' times. */
for (let i = 0; i < notrain ; i++) {
let data = random(training_data);
nn.train(data.inputs, data.outputs);
}
/* Draw either some, or all of the squares. */
if (showall) {
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
drawsquare(i, j);
}
}
} else {
for (let i = 0; i < cols; i = i + cols - 1) {
for (let j = 0; j < rows; j = j + rows - 1) {
drawsquare(i, j);
}
}
}
}
/* Draw a square at the specified coordinates. */
function drawsquare(i, j) {
let x1 = i / cols;
let x2 = j / rows;
let inputs = [x1, x2];
let y = nn.predict(inputs);
console.log("Output (" + i + ", " + j + "): " + y);
strokeWeight(2);
stroke('black');
fill(y * 255);
rect(i * squaresize, j * squaresize, squaresize, squaresize);
}