1 模型描述
- 卷积神经网络是用来处理图像识别的强大算法(之一)
- 模型针对的是MNIST手写数字的十分类问题
- 模型通过nn.Sequential构建两个卷积层
- 卷积层函数Conv2d的参数介绍参考https://zhuanlan.zhihu.com/p/218266092
- 主要步骤包括卷积计算、ReLU、Maxpool、Softmax
- 输出层是线性的softmax,得到最大概率的分类作为结果
2 具体代码
# convolutional neural network
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
# 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 dataset
train_dataset = torchvision.datasets.MNIST(
root = 'data',
train = True,
transform = transforms.ToTensor(),
download = True
)
test_dataset = torchvision.datasets.MNIST(
root = 'data',
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
)
# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
def __init__(self, num_classes=10):
super(ConvNet, self).__init__()
# set two conv layer
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)
out = self.layer2(out)
out = out.reshape(out.size(0), -1)
out = self.fc(out)
return out
model = ConvNet(num_classes).to(device)
# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Bachward and optimizer
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()))
# Test the model
model.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
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')
3 程序输出
程序训练速度较快,精度很好,测试精度达到99.1%,相当优秀的图像识别算法。
Epoch [1/5], Step [100/600],Loss:0.2283
Epoch [1/5], Step [200/600],Loss:0.1261
Epoch [1/5], Step [300/600],Loss:0.0269
Epoch [1/5], Step [400/600],Loss:0.1152
Epoch [1/5], Step [500/600],Loss:0.0703
Epoch [1/5], Step [600/600],Loss:0.1074
Epoch [2/5], Step [100/600],Loss:0.0654
Epoch [2/5], Step [200/600],Loss:0.0257
Epoch [2/5], Step [300/600],Loss:0.0075
Epoch [2/5], Step [400/600],Loss:0.0634
Epoch [2/5], Step [500/600],Loss:0.0597
Epoch [2/5], Step [600/600],Loss:0.0364
Epoch [3/5], Step [100/600],Loss:0.0147
Epoch [3/5], Step [200/600],Loss:0.0209
Epoch [3/5], Step [300/600],Loss:0.0162
Epoch [3/5], Step [400/600],Loss:0.0184
Epoch [3/5], Step [500/600],Loss:0.0231
Epoch [3/5], Step [600/600],Loss:0.0449
Epoch [4/5], Step [100/600],Loss:0.0116
Epoch [4/5], Step [200/600],Loss:0.0337
Epoch [4/5], Step [300/600],Loss:0.0036
Epoch [4/5], Step [400/600],Loss:0.0358
Epoch [4/5], Step [500/600],Loss:0.0068
Epoch [4/5], Step [600/600],Loss:0.0865
Epoch [5/5], Step [100/600],Loss:0.0023
Epoch [5/5], Step [200/600],Loss:0.0117
Epoch [5/5], Step [300/600],Loss:0.0021
Epoch [5/5], Step [400/600],Loss:0.0192
Epoch [5/5], Step [500/600],Loss:0.0219
Epoch [5/5], Step [600/600],Loss:0.0135
Test Accuracy of the model on the 10000 test images: 99.1 %