Sure! Below is a Python script that uses PyTorch to train a Convolutional Neural Network (CNN) on the Fashion MNIST dataset. The script leverages CUDA for GPU acceleration and is designed to achieve over 94% validation accuracy within 20 epochs.
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# Check if CUDA is available and set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Transformations for the training and validation sets
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
# Load the Fashion MNIST dataset
train_dataset = datasets.FashionMNIST(
root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.FashionMNIST(
root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(
dataset=train_dataset, batch_size=64, shuffle=True, num_workers=2)
test_loader = DataLoader(
dataset=test_dataset, batch_size=1000, shuffle=False, num_workers=2)
# Define the CNN architecture
class CNNModel(nn.Module):
def __init__(self):
super(CNNModel, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 64, kernel_size=3, padding=1), # Output: 64 x 28 x 28
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.MaxPool2d(2), # Output: 64 x 14 x 14
nn.Conv2d(64, 128, kernel_size=3, padding=1), # Output: 128 x 14 x 14
nn.BatchNorm2d(128),
nn.ReLU(inplace=True),
nn.MaxPool2d(2), # Output: 128 x 7 x 7
nn.Conv2d(128, 256, kernel_size=3, padding=1), # Output: 256 x 7 x 7
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
nn.MaxPool2d(2), # Output: 256 x 3 x 3
)
self.classifier = nn.Sequential(
nn.Dropout(0.5),
nn.Linear(256 * 3 * 3, 512),
nn.ReLU(inplace=True),
nn.Dropout(0.5),
nn.Linear(512, 256),
nn.ReLU(inplace=True),
nn.Linear(256, 10)
)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
model = CNNModel().to(device)
# Define loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# Training and validation loop
num_epochs = 20
best_acc = 0.0
for epoch in range(num_epochs):
# Training phase
model.train()
running_loss = 0.0
for images, labels in train_loader:
images = images.to(device)
labels = labels.to(device)
# Zero gradients
optimizer.zero_grad()
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Backward pass and optimization
loss.backward()
optimizer.step()
running_loss += loss.item() * images.size(0)
epoch_loss = running_loss / len(train_loader.dataset)
# Validation phase
model.eval()
correct = 0
total = 0
with torch.no_grad():
for images, labels in test_loader:
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
epoch_acc = 100 * correct / total
# Save the best model
if epoch_acc > best_acc:
best_acc = epoch_acc
torch.save(model.state_dict(), 'best_model.pth')
print(f'Epoch [{epoch+1}/{num_epochs}], '
f'Loss: {epoch_loss:.4f}, '
f'Validation Accuracy: {epoch_acc:.2f}%')
print(f'Best Validation Accuracy: {best_acc:.2f}%')
Explanation:
Note:
- Make sure you have a CUDA-enabled GPU and the necessary drivers installed to leverage GPU acceleration.
- You may need to install PyTorch with CUDA support. You can find the installation instructions on the PyTorch website.
- Adjust the
batch_size and other hyperparameters according to your GPU's memory capacity.
- This script should achieve over 94% validation accuracy within 20 epochs, but results might vary slightly due to randomness in weight initialization and data shuffling.
Running the Script:
- Save the script in a file, e.g.,
fashion_mnist_train.py.
- Run the script using the command:
python fashion_mnist_train.py
- Monitor the output to see the training loss and validation accuracy after each epoch.
Let me know if you have any questions or need further assistance!