// Cloned by Parth Bhatnagar on 5 Dec 2021 from World "Character recognition neural network" by "Coding Train" project
// Please leave this clone trail here.
// Port of Character recognition neural network from here:
// https://github.com/CodingTrain/Toy-Neural-Network-JS/tree/master/examples/mnist
// with many modifications
// --- defined by MNIST - do not change these ---------------------------------------
const pix = 28;
const pixel_squared = pix * pix;
// number of training and test exemplars in the data set:
const no_of_train = 60000;
const no_of_test = 10000;
// no of nodes in network
const no_of_input = pixel_squared;
const no_of_hidden = 64;
const no_of_output = 10;
const lr = 0.1;
let do_training = true;
// how many to train and test per timestep
const train_per_step = 30;
const test_per_step = 5;
const zoom_factor = 7;
const zoom_pixels = zoom_factor * pix;
const canvas_W = (pix + zoom_pixels) + 50;
const canvas_H = (zoom_pixels * 3) + 100;
const thickness_of_doodle = 20;
const blur_doodle = 5;
let mnist;
// all data is loaded into this
// mnist.train_images
// mnist.train_labels
// mnist.test_images
// mnist.test_labels
let nn;
let trainrun = 2;
let train_index = 0;
let testrun = 2;
let test_index = 0;
let total_tests = 0;
let total_correct = 0;
let doodle, demo;
let doodle_exists = false;
let demo_exists = false;
let mousedrag = false;
var Train_ip, Test_ip, Demo_ip, Doodle_ip;
function randomWeight()
{
return ( AB.randomFloatAtoB ( -1, 1 ) );
}
// make run header bigger
AB.headerCSS ( { "max-height": "95vh" } );
//--- start of AB.msgs structure: ---------------------------------------------------------
// We output a serious of AB.msgs to put data at various places in the run header
var thehtml;
// 1 Doodle header
thehtml = "<hr> <h1> 1. Doodle </h1> Top row: Doodle (left) and shrunk (right). <br> " +
" Draw your doodle in top LHS. <button onclick='wipeDoodle();' class='normbutton' >Clear doodle</button> <br> ";
AB.msg ( thehtml, 1 );
// 2 Doodle variable data (guess)
// 3 Training header
thehtml = "<hr> <h1> 2. Training </h1> Middle row: Training image magnified (left) and original (right). <br> " +
" <button onclick='do_training = false;' class='normbutton' >Stop training</button> <br> ";
AB.msg ( thehtml, 3 );
// 4 variable training data
// 5 Testing header
thehtml = "<h3> Hidden tests </h3> " ;
AB.msg ( thehtml, 5 );
// 6 variable testing data
// 7 Demo header
thehtml = "<hr> <h1> 3. Demo </h1> Bottom row: Test image magnified (left) and original (right). <br>" +
" The network is <i>not</i> trained on any of these images. <br> " +
" <button onclick='makeDemo();' class='normbutton' >Demo test image</button> <br> ";
AB.msg ( thehtml, 7 );
// 8 Demo variable data (random demo ID)
// 9 Demo variable data (changing guess)
const greenspan = "<span style='font-weight:bold; font-size:x-large; color:darkgreen'> " ;
//--- end of AB.msgs structure: ---------------------------------------------------------
function setup()
{
createCanvas ( canvas_W, canvas_H );
doodle = createGraphics ( zoom_pixels, zoom_pixels ); // doodle on larger canvas
doodle.pixelDensity(1);
// JS load other JS
// maybe have a loading screen while loading the JS and the data set
AB.loadingScreen();
$.getScript ( "/uploads/codingtrain/matrix.js", function()
{
$.getScript ( "/uploads/codingtrain/nn.js", function()
{
$.getScript ( "/uploads/codingtrain/mnist.js", function()
{
console.log ("All JS loaded");
nn = new NeuralNetwork(no_of_input, no_of_hidden, no_of_output);
nn.setLearningRate (lr);
loadData();
});
});
});
}
// load data set from local file (on this server)
function loadData()
{
loadMNIST (function(data)
{
mnist = data;
console.log ("All data loaded into mnist object:");
console.log(mnist);
AB.removeLoading();
});
}
function getImage (img)
{
let theimage = createImage (pix, pix);
theimage.loadPixels();
let i = 0;
while ( i < pixel_squared)
{
let bright = img[i];
let index = i * 4;
theimage.pixels[index + 0] = bright;
theimage.pixels[index + 1] = bright;
theimage.pixels[index + 2] = bright;
theimage.pixels[index + 3] = 255;
i++;
}
theimage.updatePixels();
return theimage;
}
function getInputs (img)
{
let inputs = [];
let i = 0;
while ( i < pixel_squared)
{
let bright = img[i];
inputs[i] = bright / 255;
i++;
}
return (inputs);
}
function Train (show)
{
let img = mnist.train_images[train_index];
let label = mnist.train_labels[train_index];
if (show)
{
var theimage = getImage ( img );
image ( theimage, 0, zoom_pixels+50, zoom_pixels, zoom_pixels);
image ( theimage, zoom_pixels+50, zoom_pixels+50, pix, pix);
}
let inputs = getInputs (img);
let targets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
targets[label] = 1;
// console.log(train_index);
// console.log(inputs);
// console.log(targets);
Train_ip = inputs; // can inspect in console
nn.train ( inputs, targets );
thehtml = " trainrun: " + trainrun + "<br> no: " + train_index ;
AB.msg ( thehtml, 4 );
train_index++;
if ( train_index == no_of_train )
{
train_index = 0;
console.log( "finished trainrun: " + trainrun );
trainrun++;
}
}
function Test()
{
let img = mnist.test_images[test_index];
let label = mnist.test_labels[test_index];
// set up the inputs
let inputs = getInputs ( img );
Test_ip = inputs;
let prediction = nn.predict(inputs);
let guess = findMax(prediction);
total_tests++;
if (guess == label) total_correct++;
let percent = (total_correct / total_tests) * 100 ;
thehtml = " testrun: " + testrun + "<br> no: " + total_tests + " <br> " +
" correct: " + total_correct + "<br>" +
" score: " + greenspan + percent.toFixed(2) + "</span>";
AB.msg (thehtml, 6);
test_index++;
if (test_index == no_of_test)
{
console.log( "finished testrun: " + testrun + " score: " + percent.toFixed(2) );
testrun++;
test_index = 0;
total_tests = 0;
total_correct = 0;
}
}
//--- find no.1 (and maybe no.2) output nodes ---------------------------------------
// (restriction) assumes array values start at 0 (which is true for output nodes)
function Find_1_and_2 (a)
{
let no1 = 0;
let no2 = 0;
let no1value = 0;
let no2value = 0;
let i = 0;
while ( i < a.length)
{
if (a[i] > no1value) // new no1
{
// old no1 becomes no2
no2 = no1;
no2value = no1value;
// now put in the new no1
no1 = i;
no1value = a[i];
}
else if (a[i] > no2value) // new no2
{
no2 = i;
no2value = a[i];
i++;
}
}
var b = [ no1, no2 ];
return b;
}
function findMax (a)
{
let no1 = 0;
let no1value = 0;
for (let i = 0; i < a.length; i++)
{
if (a[i] > no1value)
{
no1 = i;
no1value = a[i];
}
}
return no1;
}
// --- the draw function ------------------------------------------------------------
function draw()
{
if ( typeof mnist == 'undefined' ) return;
background ('black');
if ( do_training )
{
let i = 0;
while (i < train_per_step)
{
if (i === 0) Train(true);
else Train(false);
i++;
}
for (let i = 0; i < test_per_step; i++)
Test();
}
if ( demo_exists )
{
drawDemo();
guessDemo();
}
if ( doodle_exists )
{
drawDoodle();
guessDoodle();
}
if ( mouseIsPressed )
{
var MAX = zoom_pixels + 20;
if ( (mouseX < MAX) && (mouseY < MAX) && (pmouseX < MAX) && (pmouseY < MAX) )
{
mousedrag = true;
doodle_exists = true;
doodle.stroke('white');
doodle.strokeWeight(thickness_of_doodle);
doodle.line(mouseX, mouseY, pmouseX, pmouseY);
}
}
else
{
if ( mousedrag )
{
mousedrag = false;
// console.log ("Exiting draw. Now blurring.");
doodle.filter (BLUR, blur_doodle); // just blur once
// console.log (doodle);
}
}
}
//--- demo -------------------------------------------------------------
function makeDemo()
{
demo_exists = true;
var i = AB.randomIntAtoB ( 0, NOTEST - 1 );
demo = mnist.test_images[i];
var label = mnist.test_labels[i];
thehtml = "Test image no: " + i + "<br>" +
"Classification: " + label + "<br>" ;
AB.msg ( thehtml, 8 );
// type "demo" in console to see raw data
}
function drawDemo()
{
var theimage = getImage ( demo );
// console.log (theimage);
image ( theimage, 0, canvas_H - zoom_pixels, zoom_pixels, zoom_pixels ); // magnified
image ( theimage, zoom_pixels+50, canvas_H - zoom_pixels, pix, pix ); // original
}
function guessDemo()
{
let inputs = getInputs ( demo );
Demo_ip = inputs; // can inspect in console
let prediction = nn.predict(inputs); // array of outputs
let guess = findMax(prediction); // the top output
thehtml = " We classify it as: " + greenspan + guess + "</span>" ;
AB.msg ( thehtml, 9 );
}
//--- doodle -------------------------------------------------------------
function drawDoodle()
{
// doodle is createGraphics not createImage
let theimage = doodle.get();
// console.log (theimage);
image ( theimage, 0, 0, zoom_pixels, zoom_pixels); // original
image ( theimage, zoom_pixels+50, 0, pix, pix); // shrunk
}
function guessDoodle()
{
let img = doodle.get();
img.resize ( pix, pix );
img.loadPixels();
let inputs = [];
for (let i = 0; i < pixel_squared ; i++)
{
inputs[i] = img.pixels[i * 4] / 255;
}
Doodle_ip = inputs; // can inspect in console
let prediction = nn.predict(inputs); // array of outputs
let b = find12(prediction); // get no.1 and no.2 guesses
thehtml = " We classify it as: " + greenspan + b[0] + "</span> <br>" +
" No.2 guess is: " + greenspan + b[1] + "</span>";
AB.msg ( thehtml, 2 );
}
function wipeDoodle()
{
doodle_exists = false;
doodle.background('black');
}
// --- debugging --------------------------------------------------
function showInputs ( inputs )
{
var str = "";
for (let i = 0; i < inputs.length; i++)
{
if ( i % pix === 0 ) str = str + "\n";
var value = inputs[i];
str = str + " " + value.toFixed(2) ;
}
console.log (str);
}