How to Classify Handwritten Digits Using Deep Learning with Keras in Python?
Share
Condition for Classifying Handwritten Digits Using Deep Learning with Keras in Python
Description: This code implements a Convolutional Neural Network (CNN) for classifying handwritten digits from the MNIST dataset. It visualizes sample images, preprocesses data, builds a CNN model, trains it, and evaluates the model's performance using metrics like accuracy, precision, recall, F1 score, and a confusion matrix.
Step-by-Step Process
Step1: Import necessary libraries such as TensorFlow, Matplotlib, Scikit-learn, and Seaborn for model building, evaluation, and visualization.
Step2: The MNIST dataset is loaded using TensorFlow's built-in function, providing the training and testing data for digits 0-9.
Step3: A function plot_sample_images is defined to visualize the first 15 images from the training set along with their corresponding labels.
Step4: The pixel values of the images are normalized by dividing by 255 to scale them to a range between 0 and 1.
Step5: The image data is reshaped from a 2D array (28x28) to a 3D array (28x28x1) to match the input requirements of the CNN model.
Step6: A Convolutional Neural Network is defined with two convolutional layers, max-pooling layers, flattening, and dense layers, followed by a softmax output layer for multi-class classification.
Step7: The model is compiled with the Adam optimizer and sparse categorical cross-entropy loss function, with accuracy as the evaluation metric.
Step8: The CNN model is trained using the training set for 10 epochs with a batch size of 16, using the test set for validation.
Step9: Predictions are made on the test set using the trained model, and the predicted class labels are extracted by applying the argmax function on the model's output.
Step10: The model's performance is evaluated using classification metrics such as accuracy, precision, recall, and F1 score, and a confusion matrix is visualized using Seaborn.
Sample Code
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.models import Model
from sklearn.metrics import (classification_report,confusion_matrix,accuracy_score,
f1_score,recall_score,precision_score)