评价此页

训练分类器#

创建日期:2017年3月24日 | 最后更新:2026年5月8日 | 最后验证:未验证

就是这样。你已经了解了如何定义神经网络、计算损失以及更新网络权重。

现在你可能在想,

数据怎么办?#

通常,在处理图像、文本、音频或视频数据时,你可以使用标准的 Python 包将数据加载为 numpy 数组。然后,你可以将该数组转换为 torch.*Tensor

  • 对于图像,Pillow、OpenCV 等包非常有用

  • 对于音频,可以使用 scipy 和 librosa 等包

  • 对于文本,可以使用原生 Python 或基于 Cython 的加载方式,或者使用 NLTK 和 SpaCy

专门针对视觉任务,我们创建了一个名为 torchvision 的包,其中包含了常用数据集(如 ImageNet、CIFAR10、MNIST 等)的数据加载器,以及用于图像的转换工具,即 torchvision.datasetstorch.utils.data.DataLoader

这提供了极大的便利,避免了编写样板代码。

在本教程中,我们将使用 CIFAR10 数据集。它包含以下类别:‘飞机’(airplane)、‘汽车’(automobile)、‘鸟’(bird)、‘猫’(cat)、‘鹿’(deer)、‘狗’(dog)、‘青蛙’(frog)、‘马’(horse)、‘船’(ship)、‘卡车’(truck)。CIFAR-10 中的图像尺寸为 3x32x32,即 3 通道的 32x32 像素彩色图像。

cifar10

cifar10#

训练图像分类器#

我们将按顺序执行以下步骤

  1. 使用 torchvision 加载并归一化 CIFAR10 训练集和测试集

  2. 定义卷积神经网络

  3. 定义损失函数

  4. 在训练数据上训练网络

  5. 在测试数据上测试网络

1. 加载并归一化 CIFAR10#

使用 torchvision 加载 CIFAR10 非常简单。

import torch
import torchvision
from torchvision.transforms import v2

torchvision 数据集的输出是范围在 [0, 1] 之间的 PILImage 图像。我们将它们转换为归一化范围在 [-1, 1] 之间的张量(Tensor)。

注意

如果你在 Windows 或 MacOS 上运行本教程并遇到与多进程相关的 BrokenPipeError 或 RuntimeError,请尝试将 torch.utils.data.DataLoader() 的 num_worker 设置为 0。

transform = v2.Compose([
    v2.ToImage(),
    v2.ToDtype(torch.float32, scale=True),
    v2.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')
  0%|          | 0.00/170M [00:00<?, ?B/s]
  0%|          | 459k/170M [00:00<00:37, 4.55MB/s]
  2%|▏         | 3.77M/170M [00:00<00:07, 21.2MB/s]
  4%|▍         | 7.21M/170M [00:00<00:06, 27.1MB/s]
  6%|▌         | 10.2M/170M [00:00<00:05, 28.3MB/s]
  8%|▊         | 13.9M/170M [00:00<00:04, 31.4MB/s]
 11%|█         | 19.2M/170M [00:00<00:03, 38.5MB/s]
 15%|█▌        | 25.8M/170M [00:00<00:03, 47.5MB/s]
 20%|█▉        | 33.8M/170M [00:00<00:02, 57.9MB/s]
 26%|██▌       | 43.5M/170M [00:00<00:01, 70.1MB/s]
 31%|███▏      | 53.3M/170M [00:01<00:01, 78.6MB/s]
 36%|███▋      | 61.9M/170M [00:01<00:01, 80.5MB/s]
 42%|████▏     | 72.1M/170M [00:01<00:01, 87.2MB/s]
 48%|████▊     | 82.6M/170M [00:01<00:00, 92.4MB/s]
 54%|█████▍    | 92.1M/170M [00:01<00:00, 93.3MB/s]
 60%|█████▉    | 101M/170M [00:01<00:00, 92.8MB/s]
 65%|██████▌   | 111M/170M [00:01<00:00, 94.6MB/s]
 71%|███████   | 121M/170M [00:01<00:00, 94.7MB/s]
 77%|███████▋  | 131M/170M [00:01<00:00, 95.7MB/s]
 82%|████████▏ | 140M/170M [00:01<00:00, 95.1MB/s]
 88%|████████▊ | 150M/170M [00:02<00:00, 96.8MB/s]
 94%|█████████▍| 160M/170M [00:02<00:00, 95.4MB/s]
100%|█████████▉| 170M/170M [00:02<00:00, 95.4MB/s]
100%|██████████| 170M/170M [00:02<00:00, 76.6MB/s]

为了有趣,让我们展示一些训练图像。

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)))
cifar10 tutorial
deer  dog   truck truck

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')
[1,  2000] loss: 2.236
[1,  4000] loss: 1.968
[1,  6000] loss: 1.743
[1,  8000] loss: 1.652
[1, 10000] loss: 1.574
[1, 12000] loss: 1.529
[2,  2000] loss: 1.447
[2,  4000] loss: 1.456
[2,  6000] loss: 1.401
[2,  8000] loss: 1.383
[2, 10000] loss: 1.355
[2, 12000] loss: 1.323
Finished Training

让我们快速保存训练好的模型

PATH = './cifar_net.pt'
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)))
cifar10 tutorial
GroundTruth:  cat   ship  ship  plane

接下来,让我们重新加载我们保存的模型(注意:此处保存并重新加载模型并非必要,我们这样做只是为了演示如何操作)

net = Net()
net.load_state_dict(torch.load(PATH, weights_only=True))
<All keys matched successfully>

好了,现在让我们看看神经网络认为上面的这些示例是什么

outputs = net(images)

输出是 10 个类别的能量值。某个类别的能量越高,网络就越认为图像属于该类别。因此,让我们获取最高能量值的索引。

_, predicted = torch.max(outputs, 1)

print('Predicted: ', ' '.join(f'{classes[predicted[j]]:5s}'
                              for j in range(4)))
Predicted:  cat   ship  ship  ship

结果看起来相当不错。

让我们看看网络在整个数据集上的表现。

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} %')
Accuracy of the network on the 10000 test images: 52 %

这看起来比随机猜测(从 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} %')
Accuracy for class: plane is 46.1 %
Accuracy for class: car   is 61.2 %
Accuracy for class: bird  is 28.6 %
Accuracy for class: cat   is 32.6 %
Accuracy for class: deer  is 41.3 %
Accuracy for class: dog   is 39.5 %
Accuracy for class: frog  is 57.8 %
Accuracy for class: horse is 74.7 %
Accuracy for class: ship  is 77.6 %
Accuracy for class: truck is 68.4 %

好的,接下来做什么?

我们如何在 GPU 上运行这些神经网络?

在 GPU 上训练#

就像你将张量转移到 GPU 上一样,你也可以将神经网络转移到 GPU 上。

如果 CUDA 可用,我们首先将设备定义为第一个可见的 cuda 设备

device = torch.device(torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else 'cpu')

# Assuming that we are on a CUDA machine, this should print a CUDA device:

print(device)
cuda

本节的其余部分假设 device 是一个 CUDA 设备。

然后,这些方法将递归遍历所有模块,并将它们的参数和缓冲区转换为 CUDA 张量

net.to(device)

请记住,你还需要在每一步将输入和目标数据发送到 GPU

inputs, labels = data[0].to(device), data[1].to(device)

为什么我没有感觉到相比 CPU 的巨大加速?因为你的网络太小了。

练习:尝试增加网络的宽度(第一个 nn.Conv2d 的第 2 个参数,以及第二个 nn.Conv2d 的第 1 个参数 —— 它们必须是相同的数字),看看你会得到什么样的加速效果。

目标达成:

  • 了解 PyTorch 的张量库和神经网络的高级概念。

  • 训练一个小型的神经网络来分类图像

在多个 GPU 上训练#

如果你想看到使用所有 GPU 带来的更巨大的加速,请查看 可选:数据并行

接下来去哪里?#

del dataiter

脚本总运行时间:(1 分 28.251 秒)