Code viewer for World: Doodle recognition Neural ...

// Cloned by Rashmi Das on 3 Dec 2022 from World "Doodle recognition Neural Network" by Thomas Mc Cann 
// Please leave this clone trail here.
 
const PIXELS=28,PIXELSSQUARED=PIXELS*PIXELS,NOTRAIN=6e4,NOTEST=1e4,noinput=PIXELSSQUARED,nohidden=32,nooutput=10;let learningrate=.1,do_training=!0;const TRAINPERSTEP=30,TESTPERSTEP=5,ZOOMFACTOR=7,ZOOMPIXELS=7*PIXELS,canvaswidth=PIXELS+ZOOMPIXELS+50,canvasheight=3*ZOOMPIXELS+100,DOODLE_THICK=17,DOODLE_BLUR=3;let mnist,nn,doodle,demo,trainrun=1,train_index=0,trainingOrder=[],testrun=1,test_index=0,total_tests=0,total_correct=0,overallPerformance=0,correctOnThisRun=0,totalTestsOnthisRun=0,doodle_exists=!1,demo_exists=!1,mousedrag=!1;var train_inputs,test_inputs,demo_inputs,doodle_inputs,thehtml;function randomWeight(){return AB.randomFloatAtoB(-.5,.5)}$("#runheaderbox").css({"max-height":"95vh"}),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),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),thehtml="<h3> Hidden tests </h3> ",AB.msg(thehtml,5),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);const greenspan="<span style='font-weight:bold; font-size:x-large; color:darkgreen'> ";function initialiseTrainingOrder(e){for(let t=0;t<e;t++)trainingOrder[t]=t}function getNextTrainingIndex(e){return trainingOrder[e]}function shuffleTrainingOrder(){shuffle(trainingOrder,!0)}function currentRunPerformance(){return correctOnThisRun/totalTestsOnthisRun*100}function calcOverallPerfromance(){return total_correct/total_tests*100}function adjustLearningRate(e,t){var n=e,o=t;n>o?(learningrate+=(o-n)/o,Number.isNaN(learningrate)&&(learningrate=1.0001)):(learningrate-=(n-o)/o,Number.isNaN(learningrate)&&(learningrate=.99999))}function softmax(e){return e.map(function(t,n){return Math.exp(t)/e.map(function(e){return Math.exp(e)}).reduce(function(e,t){return e+t})})}function setup(){initialiseTrainingOrder(NOTRAIN),createCanvas(canvaswidth,canvasheight),(doodle=createGraphics(ZOOMPIXELS,ZOOMPIXELS)).pixelDensity(1),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)).setLearningRate(learningrate),loadData()})})})}function loadData(){loadMNIST(function(e){mnist=e,console.log("All data loaded into mnist object:"),console.log(mnist),console.log(mnist.train_images),AB.removeLoading()})}function getImage(e){let t=createImage(PIXELS,PIXELS);t.loadPixels();for(let n=0;n<PIXELSSQUARED;n++){let o=e[n],r=4*n;t.pixels[r+0]=o,t.pixels[r+1]=o,t.pixels[r+2]=o,t.pixels[r+3]=255}return t.updatePixels(),t}function getInputs(e){let t=[];for(let n=0;n<PIXELSSQUARED;n++){let o=e[n];t[n]=o/255}return t}function trainit(e){let t=mnist.train_images[getNextTrainingIndex(train_index)],n=mnist.train_labels[getNextTrainingIndex(train_index)];if(e){var o=getImage(t);image(o,0,ZOOMPIXELS+50,ZOOMPIXELS,ZOOMPIXELS),image(o,ZOOMPIXELS+50,ZOOMPIXELS+50,PIXELS,PIXELS)}let r=getInputs(t),i=[0,0,0,0,0,0,0,0,0,0];i[n]=1,train_inputs=r,nn.train(r,i),thehtml=" trainrun: "+trainrun+"<br> no: "+train_index,AB.msg(thehtml,4),++train_index==NOTRAIN&&(train_index=0,console.log("finished trainrun: "+trainrun),shuffleTrainingOrder(),console.log("Training order has been shuffled to prevent over training."),trainrun++)}let bestPerformanceOnRun=0;function testit(){let e=mnist.test_images[test_index],t=mnist.test_labels[test_index],n=getInputs(e);test_inputs=n;let o=findMax(nn.predict(n));total_tests++,totalTestsOnthisRun++,o==t&&(total_correct++,correctOnThisRun++),currentRunPerformance()>bestPerformanceOnRun&&(bestPerformanceOnRun=currentRunPerformance()),thehtml=" Testrun: "+testrun+"<br> no: "+total_tests+" <br>  Correct: "+total_correct+"<br>  Score: "+greenspan+currentRunPerformance().toFixed(2)+"</span><br>Best of run : "+bestPerformanceOnRun.toFixed(2)+"%<br>Overall Performance : "+calcOverallPerfromance().toFixed(2)+"%<br>Learning Rate : "+learningrate.toFixed(10),AB.msg(thehtml,6),++test_index==NOTEST&&(console.log("finished testrun: "+testrun+" score: "+currentRunPerformance()),testrun++,test_index=0,correctOnThisRun=0,totalTestsOnthisRun=0,bestPerformanceOnRun=0),adjustLearningRate(currentRunPerformance(),calcOverallPerfromance())}function find12(e){let t=0,n=0,o=0,r=0;for(let i=0;i<e.length;i++)e[i]>o?(t=i,o=e[i]):e[i]>r&&(n=i,r=e[i]);return[t,n]}function findMax(e){let t=0,n=0;for(let o=0;o<e.length;o++)e[o]>n&&(t=o,n=e[o]);return t}function draw(){if(void 0!==mnist){if(background("black"),do_training){for(let e=0;e<TRAINPERSTEP;e++)trainit(0==e);for(let e=0;e<TESTPERSTEP;e++)testit()}if(demo_exists&&(drawDemo(),guessDemo()),doodle_exists&&(drawDoodle(),guessDoodle()),mouseIsPressed){var e=ZOOMPIXELS+20;mouseX<e&&mouseY<e&&pmouseX<e&&pmouseY<e&&(mousedrag=!0,doodle_exists=!0,doodle.stroke("white"),doodle.strokeWeight(DOODLE_THICK),doodle.line(mouseX,mouseY,pmouseX,pmouseY))}else mousedrag&&(mousedrag=!1,doodle.filter(BLUR,DOODLE_BLUR))}}function makeDemo(){demo_exists=!0;var e=AB.randomIntAtoB(0,NOTEST-1);demo=mnist.test_images[e];var t=mnist.test_labels[e];thehtml="Test image no: "+e+"<br>Classification: "+t+"<br>",AB.msg(thehtml,8)}function drawDemo(){var e=getImage(demo);image(e,0,canvasheight-ZOOMPIXELS,ZOOMPIXELS,ZOOMPIXELS),image(e,ZOOMPIXELS+50,canvasheight-ZOOMPIXELS,PIXELS,PIXELS)}function guessDemo(){let e=getInputs(demo);demo_inputs=e;let t=findMax(nn.predict(e));thehtml=" We classify it as: "+greenspan+t+"</span>",AB.msg(thehtml,9)}function drawDoodle(){let e=doodle.get();image(e,0,0,ZOOMPIXELS,ZOOMPIXELS),image(e,ZOOMPIXELS+50,0,PIXELS,PIXELS)}function guessDoodle(){let e=doodle.get();createImage(PIXELS,PIXELS);e.resize(PIXELS,PIXELS),getDoodleImageBoundaries(e),e.loadPixels();let t=[];for(let n=0;n<PIXELSSQUARED;n++)t[n]=e.pixels[4*n]/255;doodle_inputs=t;let n=find12(nn.predict(t));thehtml=" We classify it as: "+greenspan+n[0]+"</span> <br> No.2 guess is: "+greenspan+n[1]+"</span>",AB.msg(thehtml,2)}function wipeDoodle(){doodle_exists=!1,doodle.background("black")}function showInputs(e){var t="";for(let n=0;n<e.length;n++){n%PIXELS==0&&(t+="\n"),t=t+" "+e[n].toFixed(2)}console.log(t)}function getDoodleImageBoundaries(e){let t=e.get();t.loadPixels();let n=27,o=0,r=27,i=27;for(let e=0;e<PIXELS;e++)for(let r=0;r<PIXELS;r++){if(pixelIndex=4*(e+r*PIXELS),t.pixels[pixelIndex]+t.pixels[pixelIndex+1]+t.pixels[pixelIndex+2]>0&&(o=e)<n){n=o;break}}for(let e=PIXELS-1;e>0;e--)for(let n=0;n<PIXELS;n++){if(pixelIndex=4*(e+n*PIXELS),t.pixels[pixelIndex]+t.pixels[pixelIndex+1]+t.pixels[pixelIndex+2]>0&&(r=e)<i){i=r;break}}console.log("Row left most non blank pixel: "+n),console.log("Row right most non blank pixel: "+i),t.updatePixels()}function centerScaleResizeImage(e){return e}