Classifying handwritten digits with just 8 lines of code

Learn to classify handwritten digits with simple neural networking with TensorFlow. We will use Keras as a high-level API of TensorFlow to build it.
Cinque Terre
Emroj Hossain
4 min read
10th Sept, 19

Let's first import the Tensorflow package and give it a short name 'tf'

import tensorflow as tf

The handwritten images cal be loaded in a variable by following code

mnist = tf.keras.datasets.mnist

The data can be divided into two parts- training and test and can be normalized

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

Now we can build a sequential model that will be used to train the network. Also a dropout can be added so that the network doesn't remember the data bilndly

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

No the model can be compiled and define the loss function

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

Now the model can be trained using the trained data and the prediction accuracy can be computed on the test data.

model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)