pytorch搭建CNN网络识别MNIST数据集

导包

1
2
3
4
5
6
import torch 
import torchvision
import torch.nn as nn
import numpy as np
import torchvision.transforms as transforms
import matplotlib.pyplot as plt

定义参数

1
2
3
4
5
6
7
8
# Device configuration
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

# Hyper parameters
num_epochs = 5
num_classes = 10
batch_size = 100
learning_rate = 0.001

导入MNIST数据集,定义数据加载器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# MNIST dataset 
train_dataset = torchvision.datasets.MNIST(root='data/mnist/',
train=True,
transform=transforms.ToTensor(),
download=False)

test_dataset = torchvision.datasets.MNIST(root='data/mnist/',
train=False,
transform=transforms.ToTensor())

# Data loader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size,
shuffle=False)

定义网络

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
def __init__(self, num_classes=10):
super(ConvNet, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.layer2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.fc = nn.Linear(7*7*32, num_classes)

def forward(self, x):
out = self.layer1(x) # N*14*14*16
out = self.layer2(out) # N*7*7*32
out = out.reshape(out.size(0), -1) # (N, 7*7*32)
out = self.fc(out)
return out

model = ConvNet(num_classes).to(device)

定义损失函数和优化器

1
2
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

训练模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# Move tensors to the configured device
images = images.to(device)
labels = labels.to(device)

# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)

# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()

if (i+1) % 100 == 0:
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
Epoch [1/5], Step [100/600], Loss: 0.1660
Epoch [1/5], Step [200/600], Loss: 0.1084
Epoch [1/5], Step [300/600], Loss: 0.1126
Epoch [1/5], Step [400/600], Loss: 0.1015
Epoch [1/5], Step [500/600], Loss: 0.0653
Epoch [1/5], Step [600/600], Loss: 0.0254
Epoch [2/5], Step [100/600], Loss: 0.0603
Epoch [2/5], Step [200/600], Loss: 0.0961
Epoch [2/5], Step [300/600], Loss: 0.0400
Epoch [2/5], Step [400/600], Loss: 0.0505
Epoch [2/5], Step [500/600], Loss: 0.0174
Epoch [2/5], Step [600/600], Loss: 0.0152
Epoch [3/5], Step [100/600], Loss: 0.0507
Epoch [3/5], Step [200/600], Loss: 0.0348
Epoch [3/5], Step [300/600], Loss: 0.0123
Epoch [3/5], Step [400/600], Loss: 0.0862
Epoch [3/5], Step [500/600], Loss: 0.0125
Epoch [3/5], Step [600/600], Loss: 0.0577
Epoch [4/5], Step [100/600], Loss: 0.0247
Epoch [4/5], Step [200/600], Loss: 0.0079
Epoch [4/5], Step [300/600], Loss: 0.0147
Epoch [4/5], Step [400/600], Loss: 0.0494
Epoch [4/5], Step [500/600], Loss: 0.0648
Epoch [4/5], Step [600/600], Loss: 0.0337
Epoch [5/5], Step [100/600], Loss: 0.0128
Epoch [5/5], Step [200/600], Loss: 0.0083
Epoch [5/5], Step [300/600], Loss: 0.0158
Epoch [5/5], Step [400/600], Loss: 0.0212
Epoch [5/5], Step [500/600], Loss: 0.0166
Epoch [5/5], Step [600/600], Loss: 0.0016

测试模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
model.eval()
with torch.no_grad():
correct = 0
total = 0
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()

print('Test Accuracy of the model on the 10000 test images: {} %'.
format(100 * correct / total))

# Save the model checkpoint
# torch.save(model.state_dict(), 'model.ckpt')
Test Accuracy of the model on the 10000 test images: 98.94 %