資料集的使用-以CIFAR10為例

我會嚶嚶嚶發表於2020-12-05

1 載入資料集

torchvision庫裡有很多資料集。我們這次用 CIFAR10 資料集,這是一個十分類的資料集。

import torch
import torchvision
import torchvision.transforms as transforms

The output of torchvision datasets are PILImage images of range [0, 1]. We transform them to Tensors of normalized range [-1, 1]. 還是建議把資料Normalize在[-1,1]這個區間。

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

torchvision.transforms這個函式可以對資料做很多種處理,詳見:
官方文件
簡略文件

我們來看一下訓練集的圖片:

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 = dataiter.next()

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

out:
在這裡插入圖片描述

plane   cat   car   car

2 定義網路

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 定義損失函式和優化器

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('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')

output:

[1,  2000] loss: 2.203
[1,  4000] loss: 1.874
[1,  6000] loss: 1.686
[1,  8000] loss: 1.599
[1, 10000] loss: 1.553
[1, 12000] loss: 1.484
[2,  2000] loss: 1.440
[2,  4000] loss: 1.384
[2,  6000] loss: 1.387
[2,  8000] loss: 1.345
[2, 10000] loss: 1.331
[2, 12000] loss: 1.324
Finished Training

快速儲存模型:

PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)

更詳細的可以看這裡:
https://blog.csdn.net/weixin_42468475/article/details/110700546

5 在測試集評估

我們先檢視一下測試集的圖片。
torchvision.utils.make_grid(images) 這個函式可以方便地檢視多個樣本,其中 images 的格式是(batchsize, channel, )

# 這也是一種資料迭代器的用法
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)))

在這裡插入圖片描述
檢視標籤類別:

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

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

Out:

Predicted:    cat  ship truck  ship

這四個的結果看起來相當不錯,接下來我們來看一下模型在整個testset上的表現。

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

out:

Accuracy of the network on the 10000 test images: 52 %

我們來看每一類的accuracy:

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

Out:

Accuracy of plane : 65 %
Accuracy of   car : 42 %
Accuracy of  bird : 19 %
Accuracy of   cat : 23 %
Accuracy of  deer : 52 %
Accuracy of   dog : 68 %
Accuracy of  frog : 58 %
Accuracy of horse : 62 %
Accuracy of  ship : 52 %
Accuracy of truck : 77 %

參考:
官方文件

相關文章