在这篇技术博客中,我们将使用 PyTorch 框架构建一个卷积神经网络(CNN),以识别 MNIST 数据集中的手写数字。我们将重点介绍如何在 GPU 上运行模型,以提高训练和推理的速度。
环境准备与库导入
确保您已经安装了 PyTorch 和 torchvision。如果您使用 Google Colab,可以直接在代码单元中运行以下命令:
pip install torch torchvision
接下来,导入必要的库:
import torch
import torchvision
import matplotlib.pyplot as plt
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
设备设置与超参数
检查是否有可用的 GPU,并相应地设置设备:
device = torch.device('cpu')
if torch.cuda.is_available():
device = torch.device('cuda')
print("Using CUDA!")
设置超参数,包括训练的轮数、批量大小、学习率等:
n_epochs = 3
batch_size_train = 64
batch_size_test = 1000
learning_rate = 0.01
momentum = 0.5
log_interval = 10
random_seed = 1
torch.manual_seed(random_seed)
数据加载与可视化
使用 torchvision
加载 MNIST 数据集,并进行归一化处理:
train_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST(root='./MNIST', train=True, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size_train, shuffle=True)
test_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST(root='./MNIST', train=False, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size_test, shuffle=True)
可视化一些测试数据,以便更好地理解数据集:
examples = enumerate(test_loader)
batch_idx, (example_data, example_targets) = next(examples)
fig = plt.figure()
for i in range(6):
plt.subplot(2, 3, i + 1)
plt.tight_layout()
plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
plt.title("Ground Truth: {}".format(example_targets[i]))
plt.xticks([])
plt.yticks([])
plt.show()
模型定义与训练
定义一个简单的卷积神经网络:
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.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return F.log_softmax(x)
设置优化器和损失函数,并定义训练和测试函数:
network = Net().to(device)
optimizer = optim.SGD(network.parameters(), lr=learning_rate, momentum=momentum)
train_losses = []
train_counter = []
test_losses = []
test_counter = [i * len(train_loader.dataset) for i in range(n_epochs + 1)]
def train(epoch):
network.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = network(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % log_interval == 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()))
train_losses.append(loss.item())
train_counter.append((batch_idx * 64) + ((epoch - 1) * len(train_loader.dataset)))
def test():
network.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 = network(data)
test_loss += F.nll_loss(output, target, reduction='sum').item()
pred = output.data.max(1, keepdim=True)[1]
correct += pred.eq(target.data.view_as(pred)).sum()
test_loss /= len(test_loader.dataset)
test_losses.append(test_loss)
print('\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
进行模型训练和测试:
for epoch in range(1, n_epochs + 1):
train(epoch)
test()
可视化训练过程与模型预测
可视化训练和测试损失:
fig = plt.figure()
plt.plot(train_counter, train_losses, color='blue')
plt.scatter(test_counter, test_losses, color='red')
plt.legend(['Train Loss', 'Test Loss'], loc='upper right')
plt.xlabel('number of training examples seen')
plt.ylabel('negative log likelihood loss')
plt.show()
使用训练好的模型进行预测:
with torch.no_grad():
example_data_device = example_data.to(device)
output = network(example_data_device)
output = output.cpu()
fig = plt.figure()
for i in range(6):
plt.subplot(2, 3, i + 1)
plt.tight_layout()
plt.imshow(example_data[i][0], cmap='gray', interpolation='none')
plt.title("Prediction: {}".format(output.data.max(1, keepdim=True)[1][i].item()))
plt.xticks([])
plt.yticks([])
plt.show()
继续训练模型
如果需要继续训练模型,可以加载之前保存的模型和优化器状态:
continued_network = Net().to(device)
continued_optimizer = optim.SGD(network.parameters(), lr=learning_rate, momentum=momentum)
network_state_dict = torch.load('./model.pth')
continued_network.load_state_dict(network_state_dict)
optimizer_state_dict = torch.load('./optimizer.pth')
continued_optimizer.load_state_dict(optimizer_state_dict)
for i in range(4, 6):
test_counter.append(i * len(train_loader.dataset))
train(i)
test()
总结
在本文中,我们介绍了如何使用 PyTorch 构建一个简单的卷积神经网络,以识别 MNIST 数据集中的手写数字,并在 GPU 上运行以提高性能。希望这篇博客能帮助您更好地理解深度学习的基本概念和实践。
如需进一步学习,请参考 PyTorch 官方文档。