Another project in Machine Learning that really got my interest was Image Classification. This project is actually one of the very first projects that someone comes along when first starting out. The famous Digit Recognition from MNIST. The task here is to train an algorithm to differentiate between 28×28 pixel images of handwritten numbers ranging from 0 to 9.
Step 1 Importing Libraries and loading Data
import tensorflow as tf import numpy as np mnist = tf.keras.datasets.mnist
Step 2 Defining Train and Test set as well as normalizing Data
(x_train, y_train) , (x_test, y_test) = mnist.load_data() x_train = tf.keras.utils.normalize(x_train, axis=1) x_test = tf.keras.utils.normalize(x_test, axis=1)
Step 3 Implement and train the Model
model = tf.keras.models.Sequential() model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(128, activation="relu")) model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax)) model.compile(optimizer="adam", loss="sparse_categorical_crossentropy",metrics=["accuracy"] ) model.fit(x_train, y_train, epochs=10) val_loss, val_acc = model.evaluate(x_test, y_test) print(val_acc) print(val_loss)
Using the above metrics, I was able to get an in-sample accuracy score of about 0.9952 (trained on 60.000 images in the train set) and an out-of-sample accuracy score on the test set of about 0.9754. Or in other words, given a random image of a handwritten number from 0 to 9, the model would be able to accurately predict the correct number in about 98 out of 100 cases.