使用 PyTorch 实现一个简单的卷积神经网络(CNN)来对 MNIST 数据集进行分类
首先,
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
然后,
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = nn.functional.relu(nn.functional.max_pool2d(self.conv1(x), 2))
x = nn.functional.relu(nn.functional.max_pool2d(self.conv2(x), 2))
x = x.view(-1, 320)
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return nn.functional.log_softmax(x, dim=1)
接下来,
def train(model, device, train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = nn.functional.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % 100 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += nn.functional.nll_loss(output, target, reduction='sum').item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
batch_size = 64
epochs = 10
learning_rate = 0.01
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=False, transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True)
model = Net().to(device)
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
for epoch in range(1, epochs + 1):
train(model, device, train_loader, optimizer, epoch)
test(model, device, test_loader)
===>
运行上述代码后,将得到类似如下的输出:
Train Epoch: 1 [0/60000 (0%)] Loss: 2.296307
Train Epoch: 1 [6400/60000 (11%)] Loss: 1.171701
Train Epoch: 1 [12800/60000 (21%)] Loss: 0.572528
...
Test set: Average loss: 0.0792, Accuracy: 9754/10000 (98%)
Train Epoch: 10 [0/60000 (0%)] Loss: 0.042292
Train Epoch: 10 [6400/60000 (11%)] Loss: 0.106183
Train Epoch: 10 [12800/60000 (21%)] Loss: 0.017702
...
Test set: Average loss: 0.0426, Accuracy: 9867/10000 (99%)
这表明在训练过程中,损失逐渐减小,测试集的准确率逐渐提高。
在最后一个 epoch 上,测试集的准确率为 98%。
可以根据自己的需要修改模型、参数、超参数等方式来进行变化,并进行训练和测试,以达到更好的性能。
例如: