MNIST using LeNet
MNIST Convnet Tutorial
Modified: Y.-K Kim 2020-08-19
****Source code****
It is a simple feed-forward CNN network for MNIST. Lets use LeNet for MNIST handwritten recognition.
A typical training procedure for a neural network is as follows:
Prepare dataset of inputs
Define the neural network that has some learnable parameters
Compute the loss (how far is the output from being correct)
Propagate gradients back into the network’s parameters
Update the weights of the network, typically using a simple update rule:
weight = weight - learning_rate * gradient
MNIST Dataset
It is a collection of 70000 handwritten digits split into training and test set of 60000 and 10000 images respectively.
Note: expected input size of this net (LeNet) is 32x32. To use this net on the MNIST dataset, please resize the images from the dataset to 32x32.
%matplotlib inline
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
# a batch_size of 64, size 1000 for testing
# mean 0.1307, std 0.3081 used for the Normalize()
batch_size_train=64
batch_size_test=64
# transform = transforms.Compose(
# [transforms.ToTensor(),
# transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
transform = transforms.Compose(
[transforms.Resize((32, 32)),transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))])
# Train set
trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size_train,
shuffle=True, num_workers=2)
# Test set
testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size_test,
shuffle=True, num_workers=2)Let us check out the shape of the images and the labels.
Plot some train data

Define the network
Let’s define this network:
tensor.view(-1,n), Returns a new tensor with the same data as the self tensor but of a different shape. the size -1 is inferred from other dimensions
You just have to define the forward function, and the backward function (where gradients are computed) is automatically defined for you using autograd. You can use any of the Tensor operations in the forward function.
Loss Function and Optimization
A loss function takes the (output, target) pair of inputs, and computes a value that estimates how far away the output is from the target. Define loss function as loss=criterion(outputs, labels)
Zero the gradient buffers of all parameters and backprops with random gradients:
Train network
Save Model
Test the network on the test data
We have trained the network for 2 passes over the training dataset. But we need to check if the network has learnt anything at all.
We will check this by predicting the class label that the neural network outputs, and checking it against the ground-truth. If the prediction is correct, we add the sample to the list of correct predictions.
Okay, first step. Let us display an image from the test set to get familiar.
Visualize test results
You need to covert from GPU to Tensor.cpu() . e.g. images.cpu()

Continued Training from Checkpoints
see how we can continue training from the state_dicts we saved during our first training run.
Last updated
Was this helpful?