Now, we will see how we can perform MNIST handwritten digit classification, using TensorFlow 2.0. It requires only a few lines of code compared to TensorFlow 1.x. As we have learned, TensorFlow 2.0 uses Keras as its high-level API; we just need to add tf.keras to the Keras code.
Let's start by loading the dataset:
mnist = tf.keras.datasets.mnist
Create a train and test set with the following code:
(x_train,y_train), (x_test, y_test) = mnist.load_data()
Normalize the train and test sets by dividing the values of x by the maximum value of x; that is, 255.0:
x_train, x_test = tf.cast(x_train/255.0, tf.float32), tf.cast(x_test/255.0, tf.float32)
y_train, y_test = tf.cast(y_train,tf.int64),tf.cast(y_test,tf.int64)
Define the sequential model as follows:
model = tf.keras.models.Sequential()
Now, let's add layers to the model. We use a three-layer network with the relu function and softmax in the final layer:
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(256, activation="relu"))
model.add(tf.keras.layers.Dense(128, activation="relu"))
model.add(tf.keras.layers.Dense(10, activation="softmax"))
Compile the model by running the following line of code:
model.compile(optimizer='sgd', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
Train the model:
model.fit(x_train, y_train, batch_size=32, epochs=10)
Evaluate the model:
model.evaluate(x_test, y_test)
That's it! Writing code with the Keras API is that simple.