备注
点击此处下载完整示例代码
训练分类器 ¶
创建时间:2025 年 4 月 1 日 | 最后更新时间:2025 年 4 月 1 日 | 最后验证:未验证
现在您已经看到了如何定义神经网络、计算损失以及更新网络的权重。
现在你可能正在想,
数据怎么办? ¶
通常情况下,当你需要处理图像、文本、音频或视频数据时,你可以使用标准的 Python 包将数据加载到 numpy 数组中。然后你可以将这个数组转换为 torch.*Tensor
。
对于图像,Pillow、OpenCV 等包很有用
对于音频,可以使用 scipy 和 librosa 等包
对于文本,可以使用原始 Python 或 Cython 基于的加载,或者 NLTK 和 SpaCy 等工具
尤其是在视觉方面,我们创建了一个名为 torchvision
的包,该包包含常见数据集(如 ImageNet、CIFAR10、MNIST 等)的数据加载器以及图像数据转换器 torchvision.datasets
和 torch.utils.data.DataLoader
。
这提供了极大的便利,避免了编写样板代码。
对于本教程,我们将使用 CIFAR10 数据集。它包含以下类别:‘飞机’,‘汽车’,‘鸟’,‘猫’,‘鹿’,‘狗’,‘青蛙’,‘马’,‘船’,‘卡车’。CIFAR-10 中的图像大小为 3x32x32,即 32x32 像素的 3 通道彩色图像。

cifar10¶
训练图像分类器
我们将按以下步骤进行:
使用
torchvision
加载并规范化 CIFAR10 训练和测试数据集定义卷积神经网络
定义损失函数
在训练数据上训练网络
在测试数据上测试网络
1. 加载并归一化 CIFAR10
使用 torchvision
,加载 CIFAR10 非常简单。
import torch
import torchvision
import torchvision.transforms as transforms
torchvision 数据集的输出是范围在 [0, 1] 的 PILImage 图像。我们将它们转换为范围在 [-1, 1] 的张量。
备注
如果在 Windows 上运行时遇到 BrokenPipeError,请尝试将 torch.utils.data.DataLoader()的 num_worker 设置为 0。
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
batch_size = 4
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
让我们来展示一些训练图像,仅供娱乐。
import matplotlib.pyplot as plt
import numpy as np
# functions to show an image
def imshow(img):
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# get some random training images
dataiter = iter(trainloader)
images, labels = next(dataiter)
# show images
imshow(torchvision.utils.make_grid(images))
# print labels
print(' '.join(f'{classes[labels[j]]:5s}' for j in range(batch_size)))
2. 定义卷积神经网络
将神经网络从之前的神经网络部分复制过来,并将其修改为接受 3 通道图像(而不是之前定义的 1 通道图像)。
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = torch.flatten(x, 1) # flatten all dimensions except batch
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
3. 定义损失函数和优化器
让我们使用分类交叉熵损失函数和带有动量的 SGD 优化器。
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
4. 训练网络 ¶
这时事情开始变得有趣。我们只需要遍历我们的数据迭代器,将输入喂给网络并优化即可。
for epoch in range(2): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
if i % 2000 == 1999: # print every 2000 mini-batches
print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')
running_loss = 0.0
print('Finished Training')
快速保存我们的训练模型:
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)
更多关于保存 PyTorch 模型的细节请见此处。
5. 在测试数据上测试网络 ¶
我们已经对训练数据集进行了 2 次遍历的训练。但我们需要检查网络是否真的学到了什么。
我们将通过预测神经网络输出的类别标签,并将其与真实标签进行比对来检查这一点。如果预测正确,我们将样本添加到正确预测列表中。
好的,第一步。让我们先显示测试集中的一个图像,以便熟悉。
dataiter = iter(testloader)
images, labels = next(dataiter)
# print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join(f'{classes[labels[j]]:5s}' for j in range(4)))
接下来,让我们重新加载我们保存的模型(注意:在这里保存和重新加载模型不是必要的,我们只是为了演示如何这样做):
net = Net()
net.load_state_dict(torch.load(PATH, weights_only=True))
好的,现在让我们看看神经网络认为上述示例是什么:
outputs = net(images)
输出是 10 个类别的能量。一个类别的能量越高,网络就越认为图像属于该类别。那么,让我们找到能量最高的索引:
_, predicted = torch.max(outputs, 1)
print('Predicted: ', ' '.join(f'{classes[predicted[j]]:5s}'
for j in range(4)))
结果看起来相当不错。
让我们看看网络在整个数据集上的表现。
correct = 0
total = 0
# since we're not training, we don't need to calculate the gradients for our outputs
with torch.no_grad():
for data in testloader:
images, labels = data
# calculate outputs by running images through the network
outputs = net(images)
# the class with the highest energy is what we choose as prediction
_, predicted = torch.max(outputs, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f'Accuracy of the network on the 10000 test images: {100 * correct // total} %')
这比随机选择一个类别(10 个类别中的 10%准确率)要好得多。看起来网络学到了一些东西。
嗯嗯,哪些类别表现得好,哪些类别表现不好:
# prepare to count predictions for each class
correct_pred = {classname: 0 for classname in classes}
total_pred = {classname: 0 for classname in classes}
# again no gradients needed
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predictions = torch.max(outputs, 1)
# collect the correct predictions for each class
for label, prediction in zip(labels, predictions):
if label == prediction:
correct_pred[classes[label]] += 1
total_pred[classes[label]] += 1
# print accuracy for each class
for classname, correct_count in correct_pred.items():
accuracy = 100 * float(correct_count) / total_pred[classname]
print(f'Accuracy for class: {classname:5s} is {accuracy:.1f} %')
好的,那么接下来呢?
我们如何将这些神经网络在 GPU 上运行?
在 GPU 上训练 ¶
就像您将张量传输到 GPU 上一样,您将神经网络传输到 GPU 上。
首先让我们定义我们的设备为如果有 CUDA 可用的话,第一个可见的 CUDA 设备:
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# Assuming that we are on a CUDA machine, this should print a CUDA device:
print(device)
本节剩余部分假设 device
是一个 CUDA 设备。
然后,这些方法将递归地遍历所有模块,并将它们的参数和缓冲区转换为 CUDA 张量:
net.to(device)
记住,你还需要在每一步将输入和目标发送到 GPU 上:
inputs, labels = data[0].to(device), data[1].to(device)
为什么我没有感觉到与 CPU 相比的巨大速度提升?因为你的网络真的很小。
练习:尝试增加你网络的宽度(第一个 nn.Conv2d
的第二个参数,以及第二个 nn.Conv2d
的第一个参数,它们需要是相同的数字),看看你能获得什么样的速度提升。
实现的目标:
高层次理解 PyTorch 的 Tensor 库和神经网络。
训练一个小型神经网络以进行图像分类。
在多个 GPU 上训练 ¶
如果你想使用所有 GPU 看到更大的加速,请查看可选:数据并行。
我接下来去哪里?
del dataiter
脚本总运行时间:(0 分钟 0.000 秒)