// Cloned by Colin McCabe on 20 Nov 2022 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 PIXELS = 28; // images in data set are tiny
const PIXELSSQUARED = PIXELS * PIXELS;
// number of training and test exemplars in the data set:
const NOTRAIN = 124800; // CMC Old value was 60000 need to increase for EMNIST training data images
const NOTEST = 20800; // CMC Old value was 10000 need to increase for EMNIST training data labels
//--- can modify all these --------------------------------------------------
// no of nodes in network
const noinput = PIXELSSQUARED;
const nohidden = 200; // CMC changed to 200 for CNN test
const nooutput = 26; // CMC need to accoutn for the 26 letters in the alphabet
const learningrate = 0.1; // default is 0.1
// should we train every timestep or not
let do_training = true;
// how many to train and test per timestep
const TRAINPERSTEP = 30;
const TESTPERSTEP = 5;
// multiply it by this to magnify for display
const ZOOMFACTOR = 7;
const ZOOMPIXELS = ZOOMFACTOR * PIXELS;
// 3 rows of
// large image + 50 gap + small image
// 50 gap between rows
// CMC Additional constants and variables for CNN changes
let modelImage; // CMC Holds a screen shot of the CNN model
const imagePadding = 40; // CMC need these extra flags to not duplicate the CNN classify function & to deal with scenario when both doodle & demo exist at the same time
const imagePad = imagePadding/4; // CMC Represents the aount of space between the Doodle, training and Demo images
const canvaswidth = ( PIXELS + ZOOMPIXELS ) + imagePadding; // CMC I added some padding to help make the images stand out and make it easier to see the boundaries of the doodle for drawing
const modelImageSize = canvaswidth; // CMC I may as well make the CNN model image graphic as big as possible
const canvasheight = ( ZOOMPIXELS * 3 ) + imagePadding + modelImageSize; // CMC changed to 200 for CNN test
const trainingImageLocation = ZOOMPIXELS + ( imagePad * 2 ); // CMC I wanted to have all the image placement calculations in one place here - this one is to place the training image on the canvas in the middle
const demoImageLocation = canvasheight - ZOOMPIXELS - modelImageSize - imagePad; // CMC I wanted to have all the image placement calculations in one place here - this one is to place the demo image on the canvas at the bottom
const modelImageLocation = canvasheight - modelImageSize; // CMC I wanted to have all the image placement calculations in one place here - this one is to place the CNN graphic image on the canvas at the very bottom
const DOODLE_THICK = 18; // thickness of doodle lines CMC changed from 18 for test purposes
const DOODLE_BLUR = 2; // blur factor applied to doodles CMC changed from 3 for testing purposes
let mnist;
// all data is loaded into this
// mnist.train_images
// mnist.train_labels
// mnist.test_images
// mnist.test_labels
let nn;
let ml5nn; // CMC to store the ML5 CNN model
let trainrun = 1;
let train_index = 0;
let testrun = 1;
let test_index = 0;
let total_tests = 0;
let total_correct = 0;
// images in LHS:
let doodle, demo;
let doodle_exists = false;
let demo_exists = false;
let demoInputs = [];
let mousedrag = false; // are we in the middle of a mouse drag drawing?
// save inputs to global var to inspect
// type these names in console
var train_inputs, test_inputs, demo_inputs, doodle_inputs;
// Matrix.randomize() is changed to point to this. Must be defined by user of Matrix.
function randomWeight()
{
return ( AB.randomFloatAtoB ( -0.5, 0.5 ) );
// Coding Train default is -1 to 1
}
// make run header bigger
AB.headerCSS ( { "max-height": "95vh" } ); // CMC 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> <h2> 1. Doodle (Upper or Lower case)</h2> Top row: Doodle (left) and shrunk (right)." +
" Draw your doodle in top LHS.  <button onclick='wipeDoodle();' class='normbutton' >Clear doodle</button> <br> "; // CMC Modified to create more space e.g. heading from h1 to h2, I think it looks bettter with h3
AB.msg ( thehtml, 1 );
// 2 Doodle variable data (guess)
// 3 Training header
thehtml = "<hr> <h2> 2. Neural Network Training Performance</h2> Middle row: Training image magnified (left) and original (right).   " +// CMC Modified to create more space e.g. heading from h1 to h2, I think it looks bettter with h3
" <button onclick='do_training = false;' class='normbutton' >Stop training</button> <br> ";
AB.msg ( thehtml, 3 );
// 4 variable training data
// 5 Testing header
thehtml = "<h4> Hidden tests </h4> " ;
AB.msg ( thehtml, 5 );
// 6 variable testing data
// 7 Demo header
thehtml = "<hr> <h2> 3. Neural Network Demo Performance</h2> Bottom row: Test image magnified(left) & original(right).  " +// CMC Modified to create more space e.g. heading from h1 to h2, I think it looks bettter with h3
" <button onclick='makeDemo();' class='normbutton' >Demo test image</button> <br> " +
" The network is <i>not</i> trained on any of these images. <br> ";
AB.msg ( thehtml, 7 );
// 8 Demo variable data (random demo ID)
// 9 Demo variable data (changing guess)
// 10 CNN header
thehtml = "<hr> <h2> 4. Convolutional Neural Network(CNN) Performance</h2> Please enter a doodle or select the Demo test image button to see how the CNN performs.<br> " + // CMC Added this extra heading to provide informaiton on CNN performance
"The network has been trained only on the training images, <i><b>not</b></i> the demo/test images.<br> ";
AB.msg ( thehtml, 10 );
const greenspan = "<span style='font-weight:bold; font-size:x-large; color:darkgreen'> " ;
const bluespan = "<span style='font-weight:bold; font-size:x-large; color:blue'> " ; // CMC used to highlight CNN data in blue instead of green
//--- end of AB.msgs structure: ---------------------------------------------------------
// CMC I added the preload function to ensure the CNN graphic was loaded and ready for setup to place it on the canvas
function preload() {
modelImage = loadImage('/uploads/tesla/ModelSummarybeter.png');
}
// CMC I created this function merely to take out some of the clutter I added to the setup function
function initialCanvasSetup(){
createCanvas ( canvaswidth, canvasheight );
background(128); // CMC set the canvas background to grey to help highlight the Doodle, Training and Demo panels better
fill(0); // CMC Create the black background for Doodle and Demo images by using a black square painted on the canvas
rect(10, 10, ZOOMPIXELS, ZOOMPIXELS); // CMC Create the black background for Doodle and Demo images by using a black square painted on the canvas
rect(10, demoImageLocation,ZOOMPIXELS, ZOOMPIXELS); // CMC place the Demo image in its new slightly adjusted location
doodle = createGraphics ( ZOOMPIXELS, ZOOMPIXELS ); // doodle on larger canvas
doodle.pixelDensity(1);
doodle.background(0);
image(modelImage, 0, modelImageLocation, modelImageSize,modelImageSize); // CMC put the CNN graphic on the canvas
}
function setup()
{
initialCanvasSetup(); // CMC created to clean the code up a bit
// 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/tesla/emnist.js", function() // CMC now loading the EMNIST data so pointing to a different set of files
{
console.log ("All JS loaded");
nn = new NeuralNetwork( noinput, nohidden, nooutput );
nn.setLearningRate ( learningrate );
loadData();
});
});
});
let options = { // CMC Start of code to setup the CNN ML5 model
inputs: [PIXELS , PIXELS , 1], // CMC define the options i.e. the size of the image of PIXELS * PIXELS and only a single channel of greyscale
task: 'imageClassification', // CMC I only need the neural net to perform image classification
};
ml5nn = ml5.neuralNetwork(options); // CMC provide the setup configuraiton to the model
let modelDetails = { // CMC Now load the preconfigured CNN model
model: '/uploads/tesla/model.json', // CMC specify the location of each model configuration file in my uploads directory
metadata: '/uploads/tesla/model_meta.json', // CMC specify the location of each model configuration file in my uploads directory
weights: '/uploads/tesla/model.weights.bin' // CMC specify the location of each model configuration file in my uploads directory
}
resultsDiv = createDiv('Loading model.....'); // CMC print the loading model message on the page below the canvas it all happens so fast no one will ever see it
resultsDiv.style('font-size', '14px'); // CMC set the size of teh font below the CNN graphic for printing the messages
resultsDiv.position(10,900); // CMC set the location where messages witll be printed (i.e. just below the CNN graphic)
ml5nn.load(modelDetails, modelLoaded); // CMC now load the full model with all the configuration data
}
// CMC mode CNN Parts
// CMC simpel callback function to let us know that the model has actually loaded successfully
function modelLoaded() {
console.log('CNN model ready.');
resultsDiv.html('');
resultsDiv.html('CNN Model Loaded Successfully!'); // CMC print the successfully loaded message on the page below the canvas
}
// CMC this function kicks off the classificaiton prcess for only the Demo image data
function classifyDemoImage() {
// console.log('In classify image!');
ml5nn.classify( { image: demoInputs },gotDemoResults); // CMC pass the Demo image data to the ML5 classifier
}
// CMC this function kicks off the classificaiton prcess for only the Doodle image data
function classifyDoodleImage() {
// console.log('In classify image!');
ml5nn.classify( { image: doodle_inputs },gotDoodleResults); // CMC pass the doodle image data to the ML5 classifier
}
// CMC This is the callback function to capture errors and display the results of the CNN model for the Demo image
function gotDemoResults(err, results) {
if (err)
{
console.error(err);
return;
}
let label = results[0].label; // CMC capture the image prediction result
let confidence = nf(100 * results[0].confidence, 2, 1); // CMC capture the confidence level of the image prediction result
thehtml = "Classifies Demo as: " + bluespan + label +"</span>" +" with a confidence of: " + bluespan +confidence +" % </span> <br>" ; // CMC Display the CNN prediciton results - Demo image
AB.msg ( thehtml, 12 ); // CMC place it below the Doodle message
}
// CMC This is the callback function to capture errors and display the results of the CNN model for the Doodle image
function gotDoodleResults(err, results) {
if (err)
{
console.error(err);
return;
}
let label = results[0].label; // CMC capture the image prediction result
let confidence = nf(100 * results[0].confidence, 2, 1); // CMC capture the confidence level of the image prediction result
thehtml = "Classifies Doodle as: " + bluespan + label +"</span>" +" with a confidence of: " + bluespan +confidence +" % </span><br> " ; // CMC Display the CNN prediciton results - Doodle image
AB.msg ( thehtml, 11 ); // CMC place it above the Demo message
}
// Core CNN Parts END here --- however there are more minor modifications below
// 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(); // if no loading screen exists, this does nothing
});
}
function getImage ( img ) // make a P5 image object from a raw data array
{
let theimage = createImage (PIXELS, PIXELS); // make blank image, then populate it
theimage.loadPixels();
let test=0; // CMC I didn't need to use test but didn't have a lot of time to clean up/optimize the code
for (let i = 0; i < PIXELS ; i++)
{
for (let j = 0; j < PIXELS ; j++)
{
let bright = img[( i + (j*PIXELS))]; // CMC modified to present on the canvas in the correct orientation (i.e. not twisted 90 degrees and flipped)
let index = test*4;
theimage.pixels[index + 0] = bright;
theimage.pixels[index + 1] = bright;
theimage.pixels[index + 2] = bright;
theimage.pixels[index + 3] = 255; // CMC
// console.log('Count = '+test+' ij = '+( i + (j*PIXELS)));
test++;
}
}
/* CMC I commented out the original code but left it for comparison
for (let i = 0; i < PIXELSSQUARED ; i++)
{
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;
}
*/
theimage.updatePixels();
return theimage;
}
function getInputs ( img ) // convert img array into normalised input array
{
let inputs = [];
demoInputs = [];
for (let i = 0; i < PIXELSSQUARED ; i++)
{
let bright = img[i];
demoInputs.push(img[i]);
inputs[i] = bright / 255; // normalise to 0 to 1
}
return ( inputs );
}
/* CMC Not needed any more - too a different path
function getInputsTransform ( img ) // convert img array into normalised input array
{
let inputs = [];
let test = 0;
for (let i = 0; i < 28; i++)
{
for (let j = 0; j < 28; j++)
{
let bright = img[(i+(j*28))] ;
inputs[test] = bright / 255;
test++;
}
}
return ( inputs );
}
*/
function trainit (show) // train the network with a single exemplar, from global var "train_index", show visual on or off
{
let img = mnist.train_images[train_index];
let label = mnist.train_labels[train_index];
label--; // CMC as the EMNIST alphabet label data starts at 1 not 0 I need to reindex to zero for it to be used correctly
// optional - show visual of the image
if (show)
{
var theimage = getImage ( img ); // get image from data array
image ( theimage, 10, trainingImageLocation, ZOOMPIXELS, ZOOMPIXELS ); // magnified CMC updated for its new location
image ( theimage, ZOOMPIXELS+25, trainingImageLocation, PIXELS, PIXELS ); // original CMC updated for its new location
}
// set up the inputs
let inputs = getInputs ( img ); // get inputs from data array
// set up the outputs
let targets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; // CMC updated to account for 26 letters in the alphabet
targets[label] = 1; // change one output location to 1, the rest stay at 0
// console.log(train_index);
// console.log(inputs);
// console.log(targets);
train_inputs = inputs; // can inspect in console
nn.train ( inputs, targets );
thehtml = " trainrun: " + trainrun + "  no: " + train_index ;
AB.msg ( thehtml, 4 );
train_index++;
if ( train_index == NOTRAIN )
{
train_index = 0;
console.log( "finished trainrun: " + trainrun );
trainrun++;
}
}
function testit() // test the network with a single exemplar, from global var "test_index"
{
let img = mnist.test_images[test_index];
let label = mnist.test_labels[test_index];
label--; // CMC as the EMNIST alphabet label data starts at 1 not 0 I need to reindex to zero for it to be used correctly
// set up the inputs
let inputs = getInputs ( img ); // CMC I modifed getinputs to correct the image orientation
test_inputs = inputs; // can inspect in console
// console.log('Deomo data = '+test_inputs);
let prediction = nn.predict(inputs); // array of outputs
let guess = findMax(prediction); // the top output
total_tests++;
if (guess == label) total_correct++;
let percent = (total_correct / total_tests) * 100 ;
thehtml = " testrun: " + testrun + "  no: " + total_tests + "  " +
" correct: " + total_correct + "  " +
" score: " + greenspan + percent.toFixed(1) + "%</span>";
AB.msg ( thehtml, 6 );
test_index++;
if ( test_index == NOTEST )
{
console.log( "finished testrun: " + testrun + " score: " + percent.toFixed(1)+"%" );
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 find12 (a) // return array showing indexes of no.1 and no.2 values in array
{
let no1 = 0;
let no2 = 0;
let no1value = 0;
let no2value = 0;
for (let i = 0; i < a.length; i++)
{
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];
}
}
var b = [ no1, no2 ];
return b;
}
// just get the maximum - separate function for speed - done many times
// find our guess - the max of the output nodes array
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 -------------------------------------------------------------
// every step:
function draw()
{
// check if libraries and data loaded yet:
if ( typeof mnist == 'undefined' ) return;
// how can we get white doodle on black background on yellow canvas?
// background('#ffffcc'); doodle.background('black');
// background (210); // CMC background ('black');
if ( do_training )
{
// do some training per step
for (let i = 0; i < TRAINPERSTEP; i++)
{
if (i == 0) trainit(true); // show only one per step - still flashes by
else trainit(false);
}
// do some testing per step
for (let i = 0; i < TESTPERSTEP; i++)
testit();
}
// keep drawing demo and doodle images
// and keep guessing - we will update our guess as time goes on
if ( demo_exists )
{
drawDemo();
guessDemo();
classifyDemoImage(); // Add the CNN classificaiton step for the Demo image
}
if ( doodle_exists )
{
drawDoodle();
guessDoodle();
classifyDoodleImage(); // Add the CNN classificaiton step for the Doodle image
}
// detect doodle drawing
// (restriction) the following assumes doodle starts at 0,0
if ( mouseIsPressed ) // gets called when we click buttons, as well as if in doodle corner
{
// console.log ( mouseX + " " + mouseY + " " + pmouseX + " " + pmouseY );
var MAX = ZOOMPIXELS + 20; // can draw up to this pixels in corner
if ( (mouseX < MAX) && (mouseY < MAX) && (pmouseX < MAX) && (pmouseY < MAX) )
{
mousedrag = true; // start a mouse drag
doodle_exists = true;
doodle.stroke('white');
doodle.strokeWeight( DOODLE_THICK );
doodle.line(mouseX, mouseY, pmouseX, pmouseY);
}
}
else
{
// are we exiting a drawing
if ( mousedrag )
{
mousedrag = false;
// console.log ("Exiting draw. Now blurring.");
doodle.filter (BLUR, DOODLE_BLUR); // just blur once
// console.log (doodle);
}
}
}
//--- demo -------------------------------------------------------------
// demo some test image and predict it
// get it from test set so have not used it in training
function makeDemo()
{
demo_exists = true;
var i = AB.randomIntAtoB ( 0, NOTEST - 1 );
demo = mnist.test_images[i];
var label = mnist.test_labels[i];
let guessChar = convlab(label); // CMC
thehtml = "Test image no: " + i + "  " +
"Classification: " +"<span style= 'font-weight:bold; font-size:x-large'>" +guessChar + "</span>  " ; // CMC added more spaces
AB.msg ( thehtml, 8 );
// type "demo" in console to see raw data
}
function drawDemo()
{
var theimage = getImage ( demo ); // CMC Only transform for Displaying
// console.log (theimage);
image ( theimage, 10, demoImageLocation, ZOOMPIXELS, ZOOMPIXELS ); // magnified CMC updated for its new location
image ( theimage, ZOOMPIXELS+25, demoImageLocation, PIXELS, PIXELS ); // original CMC updated for its new location
}
function guessDemo()
{
let inputs = getInputs ( demo ); // CMC
demo_inputs = inputs; // CMC Using demoInputs instead for the CNN inputs as the CNN does not need the normalization
let prediction = nn.predict(inputs); // array of outputs
let guess = findMax(prediction); // the top output
let guessChar = convlab(guess + 1); // CMC
thehtml = " We classify it as: " + greenspan + guessChar + "</span>" ; // CMC
AB.msg ( thehtml, 9 );
}
//--- doodle -------------------------------------------------------------
function drawDoodle()
{
// doodle is createGraphics not createImage
let theimage = doodle.get();
// console.log (theimage);
image ( theimage, 10, 10, ZOOMPIXELS, ZOOMPIXELS ); // original CMC updated for its new location
image ( theimage, ZOOMPIXELS+25, 10, PIXELS, PIXELS ); // shrunk CMC updated for its new location
}
function guessDoodle()
{
// doodle is createGraphics not createImage
let img = doodle.get();
img.resize ( PIXELS, PIXELS );
img.loadPixels();
// set up inputs CMC I left teh original code commented out
let inputs = [];
/*
for (let i = 0; i < PIXELSSQUARED ; i++)
{
inputs[i] = img.pixels[i * 4] / 255;
}
*/
let cnnInputs = []; // CMC needed as the CNN is okay with un-normalized data
let test = 0;
for (let i = 0; i < 28; i++) { // CMC setup the new loop to capture the doodle data in the non-twisted and flipped format
for (let j = 0; j < 28; j++)
{
inputs[test] = img.pixels[(i + (j * 28)) * 4] / 255; // CMC transform into the correct orientaiton for the 1HNN model
cnnInputs[test] = img.pixels[(i + (j * 28)) * 4]; // CMC transform into the correct orientaiton for the CNN model
test++;
}
}
doodle_inputs = cnnInputs; // CMC Repurposing for use as input to CNN
// feed forward to make prediction
let prediction = nn.predict(inputs); // array of outputs
let b = find12(prediction); // get no.1 and no.2 guesses
let guessChar0 = convlab(b[0] + 1); // CMC I just thought this was easier
let guessChar1 = convlab(b[1] + 1); // CMC I just thought this was easier
thehtml = " We classify it as: " + greenspan + guessChar0 + "</span> <br>" + // CMC update with guessChar0
" No.2 guess is: " + greenspan + guessChar1 + "</span>"; // CMC update with guessChar1
AB.msg ( thehtml, 2 );
}
function wipeDoodle()
{
doodle_exists = false;
doodle.background(0);
fill(0);
rect(10, 10, ZOOMPIXELS, ZOOMPIXELS);
}
// --- debugging --------------------------------------------------
// in console
// showInputs(demo_inputs);
// showInputs(doodle_inputs);
function showInputs ( inputs )
// display inputs row by row, corresponding to square of pixels
{
var str = "";
for (let i = 0; i < inputs.length; i++)
{
if ( i % PIXELS == 0 ) str = str + "\n"; // new line for each row of pixels
var value = inputs[i];
str = str + " " + value.toFixed(2) ;
}
console.log (str);
}
// CMC function used to display the label data in its alphabetic form I left the dummy at 0 as it worked for 95% of the scenarios and when it didn't it reminded me of me when it was displayed (& helped me fix the other 5%) ...
function convlab(num){
var alphabet = ["Dummy","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
return alphabet[num];
}