The mnist_digit_classifier.py script builds, trains, and evaluates a deep learning model for image classification. It's a foundational example for understanding CNNs with PyTorch.
This script performs the following key steps:
- Data Loading and Preprocessing:
- Downloads the MNIST dataset (training and test sets) from
torchvision.datasets. - Automatically transforms images into PyTorch tensors using
ToTensor(). - Creates
DataLoaderobjects for efficient batch processing, with shuffling for the training data. - Prints the shape of a sample batch to verify data dimensions.
- Downloads the MNIST dataset (training and test sets) from
- Device Configuration:
- Automatically detects and utilizes a GPU (CUDA) if available; otherwise, it defaults to CPU.
- Neural Network Definition:
- Defines a
NeuralNetworkclass inheriting fromnn.Module. - It consists of:
- A
conv_stack(convolutional layers) withnn.Conv2d,nn.ReLUactivations, andnn.MaxPool2dfor feature extraction and downsampling. This stack includes three convolutional blocks. - A
classifier(fully connected layers) withnn.Flatten,nn.Linearlayers,nn.ReLUactivations, andnn.Dropoutfor classification and regularization.
- A
- The
forwardmethod defines the pass through the network.
- Defines a
- Model Initialization:
- Instantiates the
NeuralNetworkmodel and moves it to the selected device (GPU/CPU).
- Instantiates the
- Loss Function and Optimizer:
- Uses
nn.CrossEntropyLoss()as the loss function, suitable for multi-class classification. - Employs the
Adamoptimizer with a learning rate of1e-3andweight_decayfor regularization.
- Uses
- Training and Testing Functions:
train(dataloader, model, loss_fn, optimizer): Iterates over the training data, performs forward and backward passes, updates model weights, and tracks training loss and accuracy per epoch.test(dataloader, model, loss_fn): Evaluates the model's performance on the test set (without gradient calculation), tracking test loss and accuracy.
- Model Training Loop:
- Trains the model for a specified number of
epochs(default 8), calling thetrainandtestfunctions for each epoch. - Prints progress including loss and accuracy for both training and testing.
- Trains the model for a specified number of
- Model Saving:
- Saves the trained model's state dictionary to
mnist_model.pth.
- Saves the trained model's state dictionary to
- Results Visualization:
- Plots the training and test loss over epochs.
- Plots the training and test accuracy over epochs.
- Displays 9 random test images along with their predicted and true labels to visually assess performance.
- Confusion Matrix:
- Generates and plots a confusion matrix using
sklearn.metrics.confusion_matrixto provide a detailed breakdown of correct and incorrect classifications for each digit.
- Generates and plots a confusion matrix using
This project uses the MNIST dataset, which is a large database of handwritten digits commonly used for training various image processing systems. It consists of:
- 60,000 training images.
- 10,000 test images.
- Each image is a 28x28 pixel grayscale image of a handwritten digit (0-9).