Pytorch学习(四):训练分类器

以下内容为Pytorch官网教程的翻译简化和一些自己的总结:

数据加载

一般而言,处理如图片,文本,音频,视频等数据时,可使用标准Python库加载数据成numpy数组形式,然后转换为张量。
特别地:

  • 对于图像数据,Pillow,OpenCV很有用
  • 对于音频数据,scipy和librosa
  • 对于文本数据,纯Python加载,或NLTK和SpaCy

对于视觉数据,有torchvision库提供了基本的数据加载和转换工具,见torchvision.datasets和torch.utils.data.DataLoader

分类器模型示例

加载CIFAR10数据集,并标准化:

import torch
import torchvision
import torchvision.transforms as transforms

# 加载数据集时的处理函数,此处为复合操作,标准化和转换张量
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 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()

定义优化器和损失函数:

import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

训练模型:

for epoch in range(2):  # 在数据集上循环多轮(此处为两轮)
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0): 
        # 数据为样本,标签列表
        inputs, labels = data

        # 每一步梯度置零
        optimizer.zero_grad()

        # 前向传播,反向传播,优化
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        # 损失张量转实数,损失累加
        running_loss += loss.item()
        if i % 2000 == 1999:    # 每两千轮打印一次
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)  # 模型保存

在测试集上检验模型:

net = Net()
net.load_state_dict(torch.load(PATH))  # 模型加载

correct = 0
total = 0
# 测试时不需要计算梯度
with torch.no_grad():
    for data in testloader:  # 注意数据是分批的
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)  # 预测结果为张量
        total += labels.size(0)  # 每批数据的样本数
        correct += (predicted == labels).sum().item()  # 预测正确的样本统计

print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))

除了测试模型的整体性能,还可以深入模型的具体表现,检验模型在哪些类别上表现良好,哪些类别上表现不佳:

# 分类别统计
correct_pred = {classname: 0 for classname in classes}
total_pred = {classname: 0 for classname in classes}

with torch.no_grad():
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predictions = torch.max(outputs, 1)
        for label, prediction in zip(labels, predictions):
            if label == prediction:
                correct_pred[classes[label]] += 1
            total_pred[classes[label]] += 1

for classname, correct_count in correct_pred.items():
    accuracy = 100 * float(correct_count) / total_pred[classname]
    print("Accuracy for class {:5s} is: {:.1f} %".format(classname,
                                                   accuracy))

可将模型迁移至GPU训练:

# 定义设备,第一台可见的cuda设备
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# 模型迁移至GPU
net.to(device)  # 将递归地遍历所有方法并将参数和缓存转换为CUDA张量
# 注意每一步的样本和标签也要迁移至GPU
inputs, labels = data[0].to(device), data[1].to(device)

你可能感兴趣的:(pytorch,python,深度学习)