Neural Canvas: Retraining Seven Browser Models on What You Actually Draw

I came across Neural Canvas by Muhammad Essa: a web page where you draw a digit and watch seven small neural networks work on it, layer by layer, live in the browser. No server, no framework, just p5.js for drawing and Math.js for Z = W·A + b. I love that kind of project. So I drew a clean 7, and model 1 said 3.

That started a few weeks of work. This post shows what was wrong, what I changed, and what the numbers say now. Everything still runs in the browser. The training moved to a GPU machine, and only the weights come back as JSON files.

My fork is on GitHub: mraad/neural_canvas. The live demo is at mraad.github.io/neural_canvas.

Neural Canvas with model 1. A white 7 on a black drawing board on the left, two hidden layers of neuron boxes in the middle, ten output values and the prediction 7 on the right.
Model 1 with a drawn 7. The board is on the left, the hidden layers are in the middle, and the prediction is on the right.

Two problems, not one

The page has seven models: four digit classifiers (MNIST, Eastern Arabic-Indic, Persian), one Siamese network that compares two drawings, one convolutional network (CNN) and one sketch classifier trained on Google's Quick, Draw! data. All of them are small. The largest has 56,250 parameters.

I measured before I changed anything. I ran the shipped weights on the MNIST test set, then on the same images after the page's own crop-and-center step:

Test (first 2,000 MNIST test images)Model 1Model 2Model 6 (CNN)
MNIST as is90.0%78.8%97.5%
The page's crop and center68.7%72.5%88.8%
Shifted 3 pixels50.6%49.2%71.8%
Thinner strokes38.1%22.0%41.9%

Two things stand out. First, the shipped model 2 weights score about 80% on all 10,000 MNIST test images, and about 79% on the training set. The README of the original said 96%. Those weights look like an unfinished export. Second, every model loses a lot when the input moves or gets thinner, and a drawing on a board does both. A fully connected network has no idea that a 7 one pixel to the left is still a 7.

Make the board speak MNIST

MNIST digits were made in a known way: the digit is fit into a 20×20 box, then the box is placed in the 28×28 grid so that the center of mass is in the middle. The page did a simpler crop. Worse, its brush had a fixed width, so the bigger you drew, the thinner the stroke became after the shrink to 28×28. I measured the stroke width with a simple estimate (twice the ink area divided by the outline length). MNIST has a median of 1.95 pixels. The board gave 1.48.

The fix is to stop working on screen pixels. The board now records each stroke as a list of points. One pure function, strokesToInput(), builds the model input from those points:

  1. Find the box around all points.
  2. Scale the drawing so that the box and the stroke fit in 20×20 cells.
  3. Draw the strokes into the 28×28 grid with a round pen of width 2.4 cells.
  4. Calculate the center of mass.
  5. Draw again, moved so that the center of mass is at the center of the grid. The move stops where the drawing would leave the grid.

The measured stroke width is now 1.97 pixels, whatever size you draw at. On 90 scripted drawings in the real page, this change alone moved model 1 from 55 to 87 correct, with the old weights.

Two rows. Top: a large 7 on the board and its 28 by 28 model input. Bottom: a small 7 in the corner of the board and its 28 by 28 model input. The two inputs look almost the same.
A large 7 and a small 7 in the corner give almost the same 28×28 input.

Train on what the board sends

The next step was obvious: train the models on input that comes out of that same function. I wrote a line-for-line Python copy of strokesToInput(), in NumPy for single drawings and in JAX for batches on the GPU. A Node.js test feeds the same six drawings to both copies. They agree to 1e-14.

For the digits I used three datasets:

  • MNIST images, with random rotation, shear, scale and shift.
  • MNIST as pen strokes, from Edwin de Jong's stroke-sequence data, drawn with the board's function. Half of each training batch comes from here.
  • UCI pen-based digits: 10,992 real tablet digits from 44 writers. I never train on them. The 30 writers of the training file pick the best run. The 14 writers of the test file give the final score.

The last point matters. My first sweep picked runs by a validation set of de Jong strokes, and model 2 came out worse on real pen input than the shipped model. Those strokes are rebuilt from scanned images. Real tablet strokes are the closest thing I have to a person with a mouse.

Models 3 and 4 have no pen data at all (I found none for Arabic or Persian digits). For them, prep_images.py thins each image of MADBase and Hoda to a one-pixel skeleton and turns neighboring skeleton pixels into line segments. The board's function then draws those segments. Model 7 trains on 30,000 Quick, Draw! drawings per class, which are already strokes.

A grid of six rows and ten columns of small white drawings on black. Rows: MNIST digits, MNIST pen strokes, tablet digits, Quick Draw sketches, Arabic-Indic digits and Persian digits.
One sample for each label, as the model sees it. Rows: MNIST images, MNIST as strokes, UCI pen digits, Quick, Draw!, MADBase skeletons, Hoda skeletons.

Four GPUs, many small runs

The training machine has four NVIDIA RTX PRO 6000 Blackwell cards with 96 GB each. That is absurd for models of 16,000 parameters, and that is the point: a run of 40,000 steps takes about a minute, so I could run whole sweeps instead of guessing. Each run is one process on one GPU, in its own tmux window, with its own log. Several runs share a GPU without trouble.

G=~/neural_canvas_train/code/training/gpu_run.sh
tmux new-session -d -s train -n m6 \
  "$G 1 m6 train_jax.py --model 6 --stroke-frac 0.5 --elastic 0 --thickness 1 --seed 1 --out runs/m6"

One trap cost me a few minutes. The machine's LD_LIBRARY_PATH pointed at an older system CUDA, and JAX could not load cuDNN. The wrapper script clears that variable for each job.

A final check keeps me honest. summarize.py loads each exported JSON file and runs it through an independent NumPy forward pass, the same one that the Node.js test compares with the browser code. The NumPy score matched the JAX score for every run, to within 0.03 points.

Results

Over roughly 145 runs, I picked each model by its selection data only. The test data was used once, at the end.

ModelTest (unseen data, board-style input)Previous weightsNew weights
1 (784-20-20-10, MSE)Tablet handwriting, 14 writers77.4%80.6%
2 (784-40-40-10)Tablet handwriting, 14 writers90.5%91.1%
6 (CNN)Tablet handwriting, 14 writers89.8%92.9%
5 (Siamese)Same/different pair ROC AUC93.6%98.4%
7 (Quick, Draw!)60,000 test drawings, 20 classes71.7%96.5%
3 (Arabic-Indic)MADBase skeleton strokes90.0%95.3%
4 (Persian)Hoda skeleton strokes51.8%95.6%

Model 7 is the big jump. The old weights came from Quick, Draw!'s own 28×28 bitmaps, which are drawn differently from the board's input. Model 4 scored 55% on Hoda, so it was most likely trained on a different Persian set. For model 5, I now scale the 32-value embedding to length 1, in training and in the browser. Pairs of the same digit sit at a median distance of 0.02, and pairs of different digits at 0.96.

One late fix: the centering step could push the tail of a top-heavy 7 out of the 28×28 grid. The move now stops at the edge of the grid, in the browser and in the training code. I retrained all seven models with the fix. No model gained more than 0.06 points, and the current weights score the same on the new input, so I kept them.

Model 5 with two drawing boards, a 7 at the top and a 1 at the bottom, three hidden layers, two embeddings and a red distance bar with the value 0.969.
Model 5 compares a 7 and a 1. The distance is 0.97, so the bar is red.

What did not help

I expected two methods from the literature to help, and both made real pen accuracy worse:

  • Knowledge distillation. A larger teacher CNN reached 99.5% on MNIST and 95.3% on the tablet digits. Its soft targets lowered the small models' pen accuracy. I removed the code and kept the results in the repo.
  • Elastic distortion (random smooth warps of the images, from Simard et al. 2003). It lowered pen accuracy for models 2 and 6.

Training on MNIST images alone was also worse than mixing in the strokes. Your data may say something else. Mine said this.

The browser side

I also asked whether WebAssembly, workers, WebGL or WebGPU would help. I measured first. The forward pass of the largest model takes about 11 ms in Node.js and runs only when the drawing changes. The real cost was elsewhere: the canvas drop shadows under every neuron box added about 24 ms to each frame, even on a fast laptop GPU. They were decoration, so I removed them. A frame now takes 5 to 13 ms against a budget of 33 ms at 30 frames per second. None of those technologies is needed for models this size, and I did not add any.

Model 7 with a drawn sun. Under the board, a list of the 20 classes it can recognize. In the middle, 16 and 32 small feature maps. On the right, 20 output values and the prediction sun.
Model 7 predicts "sun". The H key shows the 20 classes that the model knows.

Limits

  • Models 3 and 4 have no real pen test. Skeleton strokes from scanned images are the best stand-in I have.
  • Model 1 is still the weakest at 80.6% on tablet handwriting. It has 20 neurons per layer and an MSE loss by design.
  • Hoda is licensed for research and non-commercial use only. The model 4 weights inherit that.

Try it

The fork has the code, the training scripts, the results of every run and a detailed README: github.com/mraad/neural_canvas. To run the test on your machine:

git clone https://github.com/mraad/neural_canvas.git
cd neural_canvas
node tests/forward.test.mjs

I opened an issue on the original project to tell Muhammad about the fork, and I offered small pull requests if he wants any of it. Next on my list: collect real browser drawings as a test set, and check the page on phones. More to come :-)

Comments

Popular posts from this blog

How to use Esri Flex API on Android and iPhone

Augmented Reality, iPhone and ArcGIS Server

Image Flare Symbol For Clustered Graphics