AI Fundamentals
Chapter 9 · Your First Neural Network

Train a digit reader in Keras

The same digits as Train a digit reader, now in Keras terms: build the model layer by layer, compile it, fit it, then read what predict gives back. Everything runs here in your browser with TensorFlow.js; nothing is uploaded.

1 Build, compile, fit

model = keras.Sequential()
model.compile(…)
loss = 'sparse_categorical_crossentropy'
labels are integers 0–9 (a 3 is just 3). With one-hot labels (a 3 is [0,0,0,1,0,0,0,0,0,0]) you'd use 'categorical_crossentropy'. Same number either way.
metrics = ['accuracy']
model.fit(…)

2 Train and test

Epoch–
val_loss–
Test accuracy–
Loading 14,000 MNIST digits…
The training log appears here, the way Keras prints it.
lossval_loss
accuracyval_accuracy

After training: the confusion matrix for the test digits, from np.argmax(model.predict(X_test), axis=1).

Some test digits it got wrong appear here after training.

3 model.predict on your digit

?
Train the model, then draw a digit.

The 10 bars are the 10 softmax outputs: probabilities that add up to 1. The prediction is argmax, the position of the largest. The cross-entropy loss for this one digit is −log(probability given to the true digit): small when the model is confident and right, large when it is confident and wrong.

The Keras code for these settings


  

The code changes as you change the settings. This page trains the same model with TensorFlow.js, the browser version of TensorFlow (internally with one-hot labels and categorical cross-entropy, which gives the same loss as the sparse version). Your numbers will differ a little from Colab's: a different random start, and the quick sample is a fifth of MNIST.