Practical Exercises Chapter 5
Exercise 1: Implementing a Basic CNN for Image Classification
Task: Implement a simple CNN from scratch to classify images from the MNIST dataset. Train the model for a few epochs and evaluate its accuracy.
Solution:
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
class SimpleCNN(nn.Module):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=3)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
self.fc1 = nn.Linear(64 * 5 * 5, 128)
self.fc2 = nn.Linear(128, 10)
x = self.pool(torch.relu(self.conv1(x)))