Code viewer for World: *FAILED - CNN

// Cloned by Laura Campbell on 25 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 = 60000;
const NOTEST  = 10000;



//--- can modify all these --------------------------------------------------
const alphabets=["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"];

// no of nodes in network 
const noinput  = PIXELSSQUARED;
const nohidden = 64;
const nooutput = 26; //altereed by Deborah Djon


const learningrate = 0.1;   // default 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 

const canvaswidth = ( PIXELS + ZOOMPIXELS ) + 50;
const canvasheight = ( ZOOMPIXELS * 3 ) + 100;


const DOODLE_THICK = 18;    // thickness of doodle lines 
const DOODLE_BLUR = 3;      // blur factor applied to doodles 


let mnist;    
// all data is loaded into this 



let nn;
let cnnTrain;
let cnnModel;

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 mousedrag =false;      // are we in the middle of a mouse drag drawing?  


// saveeto 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 ) );
        //return ( AB.randomFloatAtoB ( -1, 1 ) );
            // Coding Train default is -1 to 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 ( canvaswidth, canvasheight );

  doodle = createGraphics ( ZOOMPIXELS, ZOOMPIXELS );       // doodle on larger canvas 
  doodle.pixelDensity(1);
  
// JS load other JS 
// maybe have a loading screen while loading the JS and the data set 
    
    wipeDoodle();
    AB.loadingScreen();
  $.getScript("/uploads/codingtrain/matrix.js",function()
  { 
   $.getScript ( "/uploads/lauracampbell26/convnet.js", function()
   { 
        $.getScript ( "/uploads/lauracampbell26/mnist.js", function()
        { 
      
            
            console.log ("All JS loaded");
            let t=[];
              t.push({type:"input",out_sx:24,out_sy:24,out_depth:1});
              t.push({type:"conv",sx:5,filters:8,stride:1,pad:2,activation:"relu"});
              t.push({type:"pool",sx:2,stride:2});
              t.push({type:"conv",sx:5,filters:16,stride:1,pad:2,activation:"relu"});
              t.push({type:"pool",sx:3,stride:3});
              t.push({type:"softmax",num_classes:26});
              cnnModel=new convnetjs.Net().makeLayers(t);
              cnnTrain=new convnetjs.SGDTrainer(cnnModel,{method:"adadelta",momentum:.9,batch_size:20,l2_decay:.001});
                    loadData();
        });
   });
  });

}


// load data set from local file (on this server)

function loadData()    
{
  loadMNIST ( function(t)    
  {
    mnist = t;
    for (  e = 0 ; e < NOTRAIN; e++)
     rotateImage( mnist.train_images[e] );
    for ( e = 0; e < NOTEST; e++)
      rotateImage( mnist.test_images[e] );
     console.log ("All data loaded into mnist object:");
    console.log(mnist);
    AB.removeLoading();      // if no loading screen exists, this does nothing 
  });
}

function rotateImage(t)
{
    for(var e=0;e<PIXELS;e++)
        for(var n=e;n<PIXELS;n++)
        {
            var o = e * PIXELS + n;
            var s = n * PIXELS + e;
            var i = t[o];
            t[o] = t[s];
            t[s] = i;
        }
}



function getImage( t )      // make a P5 image object from a raw data array   
{
    let e  = createImage (PIXELS, PIXELS);    // make blank image, then populate it 
    e.loadPixels();        
    
    for (let n = 0; n < PIXELSSQUARED ; n++) 
    {
        let o = t[n];
        let s = n * 4;
        e.pixels[s + 0] = o;
        e.pixels[s + 1] = o;
        e.pixels[s + 2] = o;
        e.pixels[s + 3] = 255;
    }
    
    return e.updatePixels(),e;

}


function getInputs( t )      // convert t array into normalised input array 
{
    let e= [];
    for (let n = 0; n < PIXELSSQUARED ; n++)          
    {
        let o = t[n];
        e[n] = o / 255;       // normalise to 0 to 1
    } 
    return e;
}


function trainit (t)        // train the network with a single exemplar, from global var "train_index", show visual on or off 
{
  let e = mnist.train_images[train_index];
  let n = mnist.train_labels[train_index];
  
  // optional - show visual of the image 
  if (t)                
  {
    var o = getImage ( e );    // get image from data array 
    image ( o,   0,                ZOOMPIXELS+50,    ZOOMPIXELS,     ZOOMPIXELS  );      // magnified 
    image ( o,   ZOOMPIXELS+50,    ZOOMPIXELS+50,    PIXELS,         PIXELS      );      // original
  }

  // set up the inputs
  let s = getInputs( e );       // getefrom data array 
  train_inputs = s;
   {
        let t = getcnnInputs(s);
        cnnTrain.train(t, n)
    }
  thehtml = " trainrun: " + trainrun + "<br> no: " + train_index ;
  AB.msg ( thehtml, 4 );

    ++train_index == NOTRAIN && (
        train_index = 0, console.log("finished trainrun: " + trainrun), trainrun++);
}

function getcnnInputs(t)
{
  for (var e = new convnetjs.Vol(28,28,1,0),n=0;n<PIXELSSQUARED;n++)
    e.w[n]=t[n];
  return e;
}

function testit()    // test the network with a single exemplar, from global var "test_s"
{ 
  let t = mnist.test_images[test_index];
  let e = mnist.test_labels[test_index];
  
  test_inputs = n;
  
  let s = findMax(cnnModel.forward(o).w);
  var i = getImage(t);
   image(i, 0, ZOOMPIXELS + 50, ZOOMPIXELS, ZOOMPIXELS),
   image(i, ZOOMPIXELS + 50, ZOOMPIXELS + 50, PIXELS, PIXELS),
  total_tests++;
  
  s == e && total_correct++;
  

  let a=total_correct/total_tests*100;
  
  thehtml =  " testrun: " + testrun + "<br> no: " + total_tests + " <br> " +
        " correct: " + total_correct + "<br>  score: " + greenspan + s.toFixed(2) + "</span>";
  AB.msg ( thehtml, 6 );

    ++test_index == NOTEST && (
    console.log( "finished testrun: " + testrun + " score: " + s.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 find12 (t)         // return array showing ses of no.1 and no.2 values in array 
{

  let e=0;
  let n=0;
  let o=0;
  let s=0;
  
  for (let i = 0; i < t.length; i++) 
  {
  
    t[i] >= o ? (n = e, s = o,e = i, o = t[i]): t[i] >= s && (n = i, s = t[i]);
    
    return[e,n];
  }
  

}



// just get the maximum - separate function for speed - done many times 
// find our guess - the max of the output nodes array

function findMax (t)        
{
  let e = 0;
  let n = 0;     
  
  for (let o = 0; o < t.length; o++) 
  {
    t[o] > n && (e = o, n = t[o]);
  }
  
  return e;
}




// --- the draw function -------------------------------------------------------------
// every step:
 
function draw() 
{
  // check if libraries and data loaded yet:
    if(void false==mnist) {
// how can we get white doodle on black background on yellow canvas?
//        background('#ffffcc');    doodle.background('black');
      if (background("black"),
      strokeWeight(1),
      stroke("blue"),
      rect( 0,  0,  ZOOMPIXELS, ZOOMPIXELS  ),
      textSize(8),
      textAlign(CENTER),
      text("Draw letter here!",ZOOMPIXELS/2,ZOOMPIXELS/2),
       do_training ) {
  // do some training per step 
        for (let t = 0; t < TRAINPERSTEP; t++) 
            trainit(0===t);
  // do some testing per step 
            for (let t = 0; t < TESTPERSTEP; t++) 
             testit();
        }
        if (demo_exists && (drawDemo(),
        guessDemo()),
        doodle_exists && (drawDoodle(),
        guessDoodle()),
        mouseIsPressed) {
            var t = ZOOMPIXELS + 20;
            mouseX < t && mouseY < t && pmouseX < t && pmouseY < t && (mousedrag = !0,
            doodle_exists = !0,
            doodle.stroke("red"),
            strokeJoin(ROUND),
            doodle.strokeWeight(DOODLE_THICK),
            doodle.line(mouseX, mouseY, pmouseX, pmouseY));
        } else
            mousedrag && (mousedrag = !1,
            doodle.filter(BLUR, DOODLE_BLUR));
    }
}



//--- demo -------------------------------------------------------------
// demo some test image and predict it
// get it from test set so have not used it in training


function makeDemo()
{
    demo_exists =false;
    var  t = AB.randomIntAtoB ( 0, NOTEST - 1 );  
    demo    = mnist.test_images[t];     
    var e   = mnist.test_labels[t];
    
   thehtml="Test image no: "+t+"<br>Classification: "+alphabets[e-1]+"<br>";

   AB.msg ( thehtml, 8 );
   
   // type "demo" in console to see raw data 
}


function drawDemo()
{
    var t = getImage( demo );
     //  console.log (e);
     
    image ( t,   0,                canvasheight - ZOOMPIXELS,    ZOOMPIXELS,     ZOOMPIXELS  );      // magnified 
    image ( t,   ZOOMPIXELS+50,    canvasheight - ZOOMPIXELS,    PIXELS,         PIXELS      );      // original
}


function guessDemo()
{
   let t= getInputs( demo ); 
   
  demo_inputs = t;  // can inspect in console 
  
  let e = getcnnInputs(t)
  let n = findMax(cnnModel.forward(e).w);

   thehtml =   " We classify it as: " + greenspan + alphabets[n-1] + "</span>" ;
   AB.msg ( thehtml, 9 );
}




//--- doodle -------------------------------------------------------------

function drawDoodle()
{
    // doodle is createGraphics not createImage
    let t = doodle.get();
    // console.log (e);
    
    image ( t,   0,                0,    ZOOMPIXELS,     ZOOMPIXELS  );      // original 
    image ( t,   ZOOMPIXELS+50,    0,    PIXELS,         PIXELS      );      // shrunk
}
      
      
function guessDoodle() 
{
   // doodle is createGraphics not createImage
   let t = doodle.get();
  
  t.resize ( PIXELS, PIXELS );     
  t.loadPixels();

  // set upe  
  let e= [];
  for (let n = 0; n < PIXELSSQUARED ; n++) 
  {
     e[n] = t.pixels[n * 4] / 255;
  }
  
  doodle_inputs = e;     // can inspect in console 

  // feed forward to make prediction 
  let n = getcnnInputs(e)
  let o = find12(cnnModel.forward(n).w);

  thehtml =   " We classify it as: " + greenspan +alphabets[o[0]-1]+ "</span> <br>" +
            " No.2 guess is: " + greenspan +alphabets[o[1]-1]+ "</span>";
  AB.msg ( thehtml, 2 );
}


function wipeDoodle()    
{
    doodle_exists =true;
    doodle.background('black');
}


function showInputs(t) {
    var e = "";
    for (let n = 0; n < t.length; n++) {
        n % PIXELS === 0 && (e += "\n");
        e = e + " " + t[n].toFixed(2);
    }
    console.log(e);
}