Using the MNIST dataset with PyTorch involves similar steps as with other deep learning libraries, such as data loading, preprocessing, defining a model, training, and evaluation. Here's a step-by-step guide along with code to demonstrate how to handle MNIST in PyTorch.
Step-by-Step Guide
-
Install PyTorch: Ensure PyTorch is installed on your system. You can follow the instructions here to install it.
-
Import Libraries:
- Import necessary modules including PyTorch and torchvision.
-
Load and Preprocess the Data:
- Use
torchvision.datasets to load MNIST.
- Apply transformations to normalize the data and convert images to tensors.
-
Define the Neural Network Model:
- Use
torch.nn to define a simple 2D CNN.
- Implement a forward method to describe how data flows through the network.
-
Set Up the Loss Function and Optimizer:
- Use cross-entropy loss, which is common for classification tasks.
- Choose an optimizer like Adam.
-
Train the Model:
- Implement a training loop to optimize the model's weights.
-
Evaluate the Model:
- Test the model on unseen data to evaluate its performance.
Here’s a PyTorch example that implements these steps:
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# Step 1: Load and preprocess the data
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='mnist_data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='mnist_data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=1000, shuffle=False)
# Step 2 and 3: Define the neural network
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(64 * 7 * 7, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.pool(nn.ReLU()(self.conv1(x)))
x = self.pool(nn.ReLU()(self.conv2(x)))
x = x.view(-1, 64 * 7 * 7)
x = nn.ReLU()(self.fc1(x))
x = self.fc2(x)
return nn.Softmax(dim=1)(x)
# Step 4: Instantiate model, define loss function and optimizer
model = CNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Step 5: Train the model
def train(model, train_loader, criterion, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
if batch_idx % 100 == 0:
print(f'Train Epoch: {epoch} [{batch_idx * len(data)}/{len(train_loader.dataset)} '
f'({100. * batch_idx / len(train_loader):.0f}%)]\tLoss: {loss.item():.6f}')
# Step 6: Evaluate the model
def test(model, test_loader, criterion):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
output = model(data)
test_loss += criterion(output, target).item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
accuracy = 100. * correct / len(test_loader.dataset)
print(f'\nTest set: Average loss: {test_loss:.4f}, Accuracy: {correct}/{len(test_loader.dataset)} '
f'({accuracy:.0f}%)\n')
# Running training and testing
for epoch in range(1, 6):
train(model, train_loader, criterion, optimizer, epoch)
test(model, test_loader, criterion)
Explanation
-
Data Transformations: We use transforms.ToTensor() to convert images to tensors and transforms.Normalize() to standardize the pixel values.
-
Model Architecture: This CNN has two convolutional layers with ReLU activations, followed by max pooling. Two fully connected layers produce the final 10-class output.
-
Training Loop: The model is trained over 5 epochs, updating weights with the optimizer based on the computed gradient of the loss function.
-
Evaluation: The performance, reported in terms of average loss and accuracy, is evaluated on the test set.
This example provides a complete yet straightforward pipeline to get started with the MNIST dataset and a simple CNN in PyTorch.