Code viewer for World: Character recognition neur...

// Cloned by Samaksh Chandra on 26 Jul 2022 from World "Character recognition neural network" by "Coding Train" project 
// Please leave this clone trail here.

//For everywhere I have edited and inserted my code, I have used the text 'my code here'
//and to indicate the end to it, I have used the text 'my code ends'
 

// 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 --------------------------------------------------

// no of nodes in network 
const noinput  = PIXELSSQUARED;
const nohidden = 64;
const nooutput = 10;

const learningrate = 0.1;   // default 0.1 

// should we train every timestep or not 
let do_training = true;

//my code here

// how many to train and test per timestep 
//const TRAINPERSTEP = 30;
//here I have changed the value of TRAINPERSTEP to 25
const TRAINPERSTEP = 25;
//const TESTPERSTEP  = 5;
//Similarly I have changed the value of TESTPERSTEP to 10;
const TESTPERSTEP = 10;

//my code ends

// 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 
// mnist.train_images
// mnist.train_labels
// mnist.test_images
// mnist.test_labels


let nn;

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?  


// 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" } );




//--- 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: ---------------------------------------------------------


//my code here
//We need to choose an appropriate activation function for our neural network to optimally decide on the weights
//for that, I am using the swish activation function, which is given by the formula below
//y = x.sigmoid(x)
//after having defined the sigmoid function, now writing the swish function becomes easy
function my_swish_function(x){
    return x*(1/(1+Math.exp(-x)))
    //where (1/(1+Math.exp(-x))) is the sigmoid function
}
//then again here I implement the softmax function
//because we have a multi-class classification problem
//and we use sigmoid for binary class classification
function softmax_for_nn(doodle_train_list){
    var iterable = 0;
    var add = 0;
    //since softmax calculates three probablities, we have to intialize them here for updating them later on
    var probabilities = [[0],[0],[0]];
    while(iterable<=doodle_train_list.length - 1){
        add += Math.exp(doodle_train_list[iterable])
        //we have used the iterable in doodle_train_list to calculate the exponent of each element in the training list of doodles
        iterable++;
    }
    //having defined the exponents, now we have to divide it by addition of all such doodles 
    //because softmax = e**y/sum(e**y) for all i values
    var local_iter = 0;
    while(local_iter<=doodle_train_list.length - 1){
        probabilities[local_iter] = Math.exp(doodle_train_list[local_iter])/add;
        local_iter++;
        //updated probabilities
    }
    //now we have to send it back to the calling function
    return probabilities;
}
//my code ends



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 

      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(  noinput, nohidden, nooutput );
            nn.setLearningRate ( learningrate );
            loadData();
        });
   });
 });
}


//my code here
//this is a function to perform matrix multiplication operations
class Define_nn_data{
    constructor(define_x_input, define_y_output){
        this.define_x_input = define_x_input;
        this.define_y_output = define_y_output;
        this.storage_list = [];
        
        iterable = 0;
        //first we will intiialize the matrix
         while(iterable<this.define_x_input){
             local_iter = 0;
             storage_list[iterable] = [];
             while(local_iter<=this.define_y_output - 1){
                 storage_list[iterable][local_iter] = [];
                 local_iter++;
             }
             iterable++;
             
         }
        //this array list will hold all the inputs that we will pass to our neural network model
    }
    
//     initialize_my_matrix(define_x_input,define_y_output){
//     iterable = 0;
//     //first we will intiialize the matrix
//     while(iterable<define_x_input){
//         local_iter = 0;
//         storage_list[iterable] = [];
//         while(local_iter<=define_y_output - 1){
//             storage_list[iterable][local_iter] = [];
//             local_iter++;
//         }
//         iterable++;
//     }
//     return storage_list;
//   }
  
  
  //here we define the multiplication of an array with a scalar value
  perform_scalar_multiply(value){
      iterable = 0;
      while(iterable<this.define_x_input){
          local_iter = 0;
          while(local_iter<this.define_y_output){
              this.storage_list[iterable][local_iter] *= value;
              local_iter++;
          }
          iterable++;
      }
  }
  
  output_from_matrix(my_mat){
      //this is a method to extract any element from the matrix
      var extract_content = new Define_nn_data(my_mat.length, 1);
      iterable = 0;
      while(iterable<my_mat.length){
          extract_content.storage_list[iterable][0] = my_mat[iterable];
          iterable++;
      }
      return extract_content;
  }
  
  
  perform_subtract(my_matrix_1, my_matrix_2){
      iterable = 0;
      out_mat = new Define_nn_data(my_matrix_1.define_x_input,my_matrix_1.define_y_output);
      while(iterable<out_mat.define_x_input){
          local_iter = 0;
          while(local_iter<out_mat[iterable].define_y_output){
              out_mat.storage_list[iterable][local_iter] = my_matrix_1.storage_list[iterable][local_iter] - my_matrix_2.storage_list[iterable][local_iter];
              local_iter++;
          }
          iterable++;
          
      }
      return out_mat;
  }
  
  //method to fill any data that is required for training or testing
  fill_data(){
      var out_mat = [];
      iterable = 0;
      while(iterable<this.define_x_input){
          local_iter = 0;
          while(local_iter<this.define_y_output){
              out_mat.push(this.storage_list[iterable][local_iter])
              local_iter++;
          }
          iterable++;
      }
      return out_mat
  }
  
  gen_values(){
      iterable = 0;
      while(iterable<this.define_x_input){
          local_iter = 0;
          while(local_iter<this.define_y_output){
              this.storage_list[iterable][local_iter] = Math.random() * 3 - 2;
              local_iter++;
          }
          iterable++;
      }
  }
  
  perform_add(my_matrix_data){
      iterable = 0;
      var sum_matrix = new Define_nn_data(this.define_x_input,this.define_y_output)
      if(my_matrix_data instanceof Define_nn_data){
          while(iterable<this.define_x_input){
              local_iter = 0;
              while(local_iter<this.define_y_output){
                  this.storage_list[iterable][local_iter] += my_matrix_shape.storage_list[iterable][local_iter];
                  local_iter++;
              }
              iterable++;
          }
      }
      else{
          iterable = 0;
          while(iterable<this.define_x_input){
              local_iter = 0;
              while(local_iter<this.define_y_output){
                  this.storage_list[iterable][local_iter] += my_matrix_data;
                  local_iter++;
              }
              iterable++;
          }
      }
  }
  
  switch_matrix_elements(my_matrix){
      switched_matrix = new Define_nn_data(my_matrix.define_y_output,my_matrix.define_x_input);
      iterable = 0;
      while(iterable<my_matrix.define_x_input){
          local_iter = 0;
          while(local_iter<my_matrix.define_y_output){
              switched_matrix.storage_list[local_iter][iterable] = my_matrix.storage_list[iterable][local_iter];
              local_iter++;
          }
          iterable++;
      }
      return switched_matrix;
  }
  
  perform_multiply(my_matrix1, my_matrix2){
      //here if the column shape of the second matrix is not equal to the column shape of first matrix
      //then we cannot multiply
      if(my_matrix2.define_y_output!= my_matrix1.define_x_input){
          console.log('cannot perfrom matrix multiplication');
          return 0;
      }
      else{
          //do the matrix multiplication
          var mat_mul = new Define_nn_data(my_matrix1.define_x_input, my_matrix2.define_y_output);
          //since row of first should match the column of second matrix
          iterable = 0;
          while(iterable<mat_mul.define_x_input){
              local_iter = 0;
              while(local_iter<mat_mul.define_y_output){
                  var add = 0;
                  sub_local_iter = 0;
                  while(sub_local_iter<my_matrix1.define_y_output){
                      add += my_matrix1.storage_list[iterable][sub_local_iter] * my_matrix2.storage_list[sub_local_iter][local_iter];
                      sub_local_iter++;
                  }
                  mat_mul.storage_list[iterable][local_iter] = add;
                  local_iter++;
              }
              iterable++;
          }
      }
      return mat_mul;
  }
  
  chart_out_function(f_value){
    //here f_value is the function value
    iterable = 0;
    while(iterable<this.define_x_input){
        local_iter = 0;
        while(local_iter<this.define_y_output){
            var data = this.storage_list[iterable][local_iter];
            this.storage_list[iterable][local_iter] = f_value(data);
            local_iter++;
        }
        iterable++;
    }
}
}
//after this class I will define my neural network solution
class my_nn_solution{
    //here i will first define the input layers, hidden layers, and the output layers
    //we can do that easily with the help of a constructor to initialize values
    constructor(layer_input,layer_hidden_layer_output){
        this.layer_input = layer_input;
        this.layer_hidden = layer_hidden;
        this.layer_output = layer_output;
        //after having defined these, our next step is to initialize the weights and biases of all the layers
        //this is done using the same constructor
        
        this.w_ih = new Define_nn_data(this.layer_hidden, this.layer_input);
        //w_ih refers to the weight of the hidden layer relative to the input layer
        this.w_ho = new Define_nn_data(this.layer_output, this.layer_hidden);
        //w_ho refers to the weight of the output layer relative to the hidden layer
        this.w_ih.gen_values();
        //initializing with generic values
        this.w_ho.gen_values();
        //initializing with generic values
        
        //now its time to add the biases
        this.b_layerhidden = new Define_nn_data(this.layer_hidden, 1);
        this.b_layeroutput = new Define_nn_data(this.layer_output, 1);
        //initializing with generic values
        this.b_layerhidden.gen_values();
        //intializing with generic values
        this.b_layeroutput.gen_values();
    }
    
    my_training_function(data_at_input_layer, result_from_output_layer){
        //this training function will take the input data and feed it to the model
        //and then collect the output data for the training data
        var data_input = Define_nn_data.output_from_matrix(data_at_input_layer);
        //next its important to define the data at the hidden layer
        //which is nothing but a dot product of the array list from the input layer and the data extracted from the activation function
        var data_hidden_layer = Define_nn_data.perform_multiply(this.w_ih,data_input);
        //we have to use the activation function now
        my_swish_function.chart_out_function(swish);
        //specifying the outputs here
        var data_at_output_layer = new Define_nn_data(this.w_ho, data_hidden_layer);
        data_at_output_layer.add(this.b_layeroutput);
        //now we will deliver the output to the softmax function as it is the final layer
        //swish was for input layer and hidden layer
        data_at_output_layer.storage_list = softmax_for_nn(data_at_output_layer.storage_list);
        
        //now get the data from the array list into the matrix 
        var final_training_data = Define_nn_data.output_from_matrix(result_from_output_layer);
        //the next step will be now to determine the errors
        var error_at_output_layer = Define_nn_data.perfrom_subtract(final_training_data, data_at_output_layer);
        //since errors are a difference between observed output and actual output
        //hence, our gradient can be defined here using errors and learning rate
        //learning rate has been fixed to 0.001
        var grad_lr = Define_nn_data.chart_out_function(my_swish_function);
        //this is important to get the total error at output layer
        grad_lr.perform_multiply(error_at_output_layer);
        grad_lr.perform_scalar_multiply(0.001);
        
        //now we will attempt to adjust the weights using back-propagation
        var backprop_quotient = Define_nn_data.switch_matrix_elements(data_hidden_layer);
        var weights_backprop = Define_nn_data.perform_scalar_multiply(grad_lr, backprop_quotient);
        
        //now we will change the weights of the layers
        this.w_ho.add(weights_backprop);
        this.b_layeroutput.add(grad_lr);
        //now we have adjusted the weights too
        //backtracking the process, now we need to do the same thing for the hidden layer
        var hidden_backprop_quotient = Define_nn_data.switch_matrix_elements(this.w_ho);
        var hidden_weight_backprop = Define_nn_data.perfor_scalar_multiply(hidden_backprop_quotient, error_at_output_layer);
        
    }
    
    //we have defined our training function
    //now we will define our test function
    my_testing_function(test_data){
        //again we have to define the data at input layer in the form of an array list for our neural network to correctly
        //classify it
        var data_from_input = Define_nn_data.output_from_matrix(data);
        //now we will define what test data is fed to our hidden layer
        var data_at_hidden = Define_nn_data.perform_scalar_multiply(this.w_ih, data_from_input);
        //note that I have used data_from_input at hidden layer and not test_data as 
        //test_data is fed to the input layer
        //however, our hidden layer receives data from the input_layer after passing through the activation function
        //and this is what we will do next, pass it through the activation function
        data_at_hidden.chart_out_function(my_swish_function);
        var data_at_output = Define_nn_data.perform_multiply(this.w_ho,data_at_hidden);
        //this is to get the correct data from the hidden layer
        data_at_output.add(this.b_layeroutput);
        data_at_output.storage_list = softmax_for_nn(data_at_output.storage_list);
        //this is the same what we did in the training function
        return data_at_output.fill_data();
    }
}




//now we will write several functions to perform various operations on our matrix which we just initialized

//now we will write a function for subtracting elements from the array

// function check_for_mat_mul(my_matrix_1, my_matrix_2){
//     iterable = 0;
//     if(my_matrix_2[0].length!=my_matrix_1.length){
//         console.log('Mat mul not possible')
//         var counter = 0;
//         return counter;
//     }
//     else{
//         counter = 1;
//         return counter;
//     }
// }

function perform_multiply(my_matrix_1, my_matrix_2){
    var check = check_for_mat_mul(my_matrix_1, my_matrix_2);
    if(check === 0){
        console.log('Matrix multiplication not allowed')
        return 0;
    }
    else{
        mul_matrix = initialize_my_matrix(x,y);
        iterable = 0;
        var sum = 0;
        while(iterable<mul_matrix.length){
            local_iter = 0;
            while(local_iter<mul_matrix[iterable].length){
                for(var i = 0;i<col_y1;i++){
                    sum += my_matrix_1[iterable][i] * my_matrix_2[i][local_iter];
                }
                mul_matrix[iterable][local_iter] = sum;
                local_iter++;
            }
            iterable++;
        }
    }
    return mul_matrix;
    //matrix multiplication code is complete now
}
//after intializing the matrix, this is a function to fill the matrix with values
// function fill_values(my_matrix,x,y){
//     iterable = 0;
//     local_const = 0;
//     temp_matrix = initialize_my_matrix(x,y);
//     while(iterable<my_matrix.length){
//         temp_matrix[iterable][local_const] = my_matrix[iterable];
//         iterable++;
//     }
// }

//function to get the rows of a matrix
// function get_row(my_mat){
//     return my_mat.length
// }


// //function to get the columns of a matrix
// function get_col(my_mat, col){
//     var columns_in_mat = [];
//     for(var i = 0;i<my_mat.length;i++){
//         columns_in_mat.push(my_mat[i][col])
//     }
//     return columns_in_mat;
// }

function generalize_values(my_mat){
    iterable = 0;
    var row_my_mat = get_row(my_mat);
    var col_my_mat = get_col(my_mat,0);
    while(iterable<row_my_mat){
        local_iter = 0;
        while(local_iter<col_my_mat){
            my_mat[iterable][local_iter] = Math.random()*2 - 1;
    }
}
return my_mat;
}

//now I will define a neural network solution for the MNIST dataset
// class my_nn{
//     constructor(i,h,o, lr){
//         //x is my input nodes 
//         //y is my hidden nodes (hidden layer)
//         //z is my output nodes
//         this.i = x;
//         this.h = y;
//         this.z = z;
        
//         //this is the weight of the network from the input layer to the hidden layer
//         this.w_ih = initialize_my_matrix(this.h, this.i);
//         //this is the weight of the network from the hidden layer to the output layer
//         this.w_ho = initialize_my_matrix(this.o, this.h);
        
//         this.w_ih = generalize_values(this.w_ih);
//         this.w_ho = generalize_values(this.ho);
        
//         this.b_hidden_layer = initialize_my_matrix(this.h, 1);
//         this.b_output_layer = initialize_my_matrix(this.o, 1);
        
//         this.b_hidden_layer = generalize_values(this.b_hidden_layer);
//         this.b_output_layer = generalize_values(this.b_output_layer);
        
        
        
//     }
// }


// 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();        
    
    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 = [];
    for (let i = 0; i < PIXELSSQUARED ; i++)          
    {
        let bright = img[i];
        inputs[i] = bright / 255;       // normalise to 0 to 1
    } 
    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];
  
  //my code here
  //I have written the function which will be prepared for training
  //and after that I have written the epochs function

  // optional - show visual of the image 
  if (show)                
  {
    var theimage = getImage ( img );    // get image from data array 
    image ( theimage,   0,                ZOOMPIXELS+50,    ZOOMPIXELS,     ZOOMPIXELS  );      // magnified 
    image ( theimage,   ZOOMPIXELS+50,    ZOOMPIXELS+50,    PIXELS,         PIXELS      );      // original
  }

  // 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];
  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 
  //my_nn_solution.my_training_function ( inputs, targets );
  //my code here
  var i = 0;
  for(i = 0;i<train_inputs.length;i++){
      my_nn_solution.my_training_function(inputs,targets)
  }
  //my code ends
  

  thehtml = " trainrun: " + trainrun + "<br> 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];

  // set up the inputs
  let inputs = getInputs ( img ); 
  
  test_inputs = inputs;        // can inspect in console
  var i = 0;
  for(i = 0;i<train_inputs.length;i++){
      my_nn_solution.my_testing_function(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 + "<br> no: " + total_tests + " <br> " +
        " correct: " + total_correct + "<br>" +
        "  score: " + greenspan + percent.toFixed(2) + "</span>";
  AB.msg ( thehtml, 6 );

  test_index++;
  if ( test_index == NOTEST ) 
  {
    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 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 ('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();
  }
  if ( doodle_exists ) 
  {
    drawDoodle();
    guessDoodle();
  }


// 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];
    
   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,                canvasheight - ZOOMPIXELS,    ZOOMPIXELS,     ZOOMPIXELS  );      // magnified 
    image ( theimage,   ZOOMPIXELS+50,    canvasheight - ZOOMPIXELS,    PIXELS,         PIXELS      );      // original
}


function guessDemo()
{
   let inputs = getInputs ( demo ); 
   
  demo_inputs = 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,    ZOOMPIXELS,     ZOOMPIXELS  );      // original 
    image ( theimage,   ZOOMPIXELS+50,    0,    PIXELS,         PIXELS      );      // shrunk
}
      
      
function guessDoodle() 
{
   // doodle is createGraphics not createImage
   let img = doodle.get();
  
  img.resize ( PIXELS, PIXELS );     
  img.loadPixels();

  // set up inputs   
  let inputs = [];
  for (let i = 0; i < PIXELSSQUARED ; i++) 
  {
     inputs[i] = img.pixels[i * 4] / 255;
  }
  
  doodle_inputs = inputs;     // can inspect in console 

  // feed forward to make prediction 
  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 --------------------------------------------------
// 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);
}