【Pytorch 学习笔记(四)】:训练分类器

文章目录

  • 训练分类器
    • data
    • training an image classifier
      • 1. Loading and normalizing CIFAR10
      • 2. Define a Convolutional Neural Network
      • 3. Define a Loss function and optimizer
      • 4. Train the network
      • 5. Test the network on the test data
    • GPU 相关
    • REF

训练分类器

到目前为止,我们已经了解了如何定义NN,计算loss以及更新网络的权重。那我们接下来再来看一下数据的处理

data

当我们需要处理图像、文本、或音/视频文件时,通常可以找到一些python包来载入数据到numpy数组中。然后我们可以将这个数组再转化为torch.*Tensor

  • 对图片来说,可以用Pillow,OpenCV
  • 对音频来说,可以用scipy,librosa
  • 对文本来说,可以用python或Cython自带的载入,或者是NLTKSpaCy

特别地,对于视觉方面,可以使用torchvision,其中包括了对Imagenet、CIFAR10、MNIST等常用数据集的数据加载器(data loaders),包括对图片数据变形的操作。即torchvision.datasetstorch.utils.data.DataLoader

在这个教程中,我们将使用CIFAR10数据集。它有如下的分类:airplane、automobile、bird、 cat、 deer、 dog、 frog、horse、 ship、 truck 等。在CIFAR-10里面的图片数据大小是3x32x32,即三通道彩色图,图片大小是32x32像素。

training an image classifier

接下来会逐步做如下操作,其实也就是训练分类器的步骤:

  • 通过torchvision加载CIFAR10里面的训练和测试数据集,并对数据进行标准化处理
  • 定义卷积神经网络
  • 定义损失函数
  • 利用训练数据训练网络
  • 利用测试数据测试网络

1. Loading and normalizing CIFAR10

使用torchvision可以很方便地加载CIFAR10

import torch
import torchvision 
import torchvision.transforms as transforms

torchvision数据集加载完的输出为范围在[0,1]之间的PILImage图片。我们需要将其标准化为范围为[-1,1]之间的张量。下面的Normalize,param第一项是mean序列,此处为3项,因为有三个channel。第二项是std序列,同样有3项。同时注意此处的转换是out-of-place,它不会改变原有输出。

transform = transforms.Compose(
    [transforms.ToTensor(),
     transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                        download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
                                          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=4,
                                         shuffle=False, num_workers=2)

classes = ('plane', 'car', 'bird', 'cat',
           'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

输出:

Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gz
Extracting ./data/cifar-10-python.tar.gz to ./data
Files already downloaded and verified

我们可以先通过下面的方法看一下训练的数据

import matplotlib.pyplot as plt
import numpy as np

# functions to show an image

def imshow(img):
	# 让照片再回到[0,1]的范围中
    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 = dataiter.next()

# show images
imshow(torchvision.utils.make_grid(images))
# print labels
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))

输出:

deer truck  frog   dog

2. Define a Convolutional Neural Network

此处可以把上一篇中的NN拿来用,但需要把它换成3通道的图片。(之前是单通道)

import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__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 = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

net = Net()

3. Define a Loss function and optimizer

此处我们可以用Cross-Entropy作为损失函数和SGD with momentum作为优化器

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

4. Train the network

然后就是关键的步骤了。现在我们需要把遍历数据迭代器,把数据输入到网络和优化函数中。

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('[%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)

关于保存的其他操作

5. Test the network on the test data

我们在训练集上训练了两遍网络,现在我们需要检查网络是否学到了东西。

我们将通过预测神经网络输出的标签来检查这个问题,并和正确样本(ground-truth)对比。如果预测是正确的,我们将样本添加到正确预测的列表中。

dataiter = iter(testloader)
images, labels = dataiter.next()

# print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))

# output:
# GroundTruth:    cat  ship  ship plane

然后,我们需要重新载入我们之前保存的模型。并查看输入在模型的处理下,输出会是神马

net = Net()
net.load_state_dict(torch.load(PATH))

outputs = net(images)

输出是10个类别的概率值。一个类的值越高,代表网络就越认为这个图像属于该类。我们得到最高量值的下标/索引;

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

print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))

# output:
# Predicted:    dog  ship  ship plane

简单的测试结束,我们再看看网络在整个数据集上效果怎么样:

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))

# output:
# Accuracy of the network on the 10000 test images: 54 %

从结果来看,这显然比随机(10%)的效果好多了。同时,我们也可以看哪些class的识别效果比较好,哪些的不是很好:

class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs, 1)
        c = (predicted == labels).squeeze()
        for i in range(4):
            label = labels[i]
            class_correct[label] += c[i].item()
            class_total[label] += 1


for i in range(10):
    print('Accuracy of %5s : %2d %%' % (
        classes[i], 100 * class_correct[i] / class_total[i]))

# output:
# Accuracy of plane : 75 %
# Accuracy of   car : 85 %
# Accuracy of  bird : 32 %
# Accuracy of   cat : 30 %
# Accuracy of  deer : 31 %
# Accuracy of   dog : 56 %
# Accuracy of  frog : 67 %
# Accuracy of horse : 68 %
# Accuracy of  ship : 40 %
# Accuracy of truck : 58 %

GPU 相关

就像我们把tensor发到GPU,我们也可以把网络发到GPU。

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)

# cuda:0

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

net.to(device)

同时,要记得把输入和目标在每一步都送入GPU

inputs, labels = inputs.to(device), labels.to(device)

关于GPU加速的其他操作

REF

  • https://pytorch.apachecn.org/docs/1.4/blitz/cifar10_tutorial.html
  • https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#test-the-network-on-the-test-data

你可能感兴趣的:(Pytorch)