使用PyTorch訓練一個分類器

數據

通常,當你不得不處理圖像,文本,語音或者視頻數據時,你可以使用將數據加載到numpy數組的標準python包,接著可以將這個數組轉換成torch.Tensor

  • 對於圖像,需要像Pillow,OpenCV這些包。
  • 對於語音,需要像scipy,librosa這些包。
  • 對於文本,需要原始的Python或者基於loading的Cython,或者NLTK和SpaCy。

特別是對於視覺,我們已經創建了一個叫做totchvision的包,該包有對於如Imagenet,CIFAR10,MNIST等公共數據集的數據加載器和對於圖像的數據轉換器,即torchvision.datasets和torch.utils.data.DataLoader。這提供了極大的便利,並且避免了編寫樣板代碼。

對於本教程,我們將使用CIFAR10數據集,它的類別為:'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'。CIFAR-10中的圖像尺寸為3*32*32,也就是RGB的3層顏色通道,每層通道內的尺寸為32*32。

使用PyTorch訓練一個分類器

圖片一 cifar10

訓練一個圖像分類器

我們將按次序的做如下幾步:

  1. 使用torchvision加載並且歸一化CIFAR10的訓練和測試數據集
  2. 定義一個卷積神經網絡
  3. 定義一個損失函數
  4. 在訓練樣本數據上訓練網絡
  5. 在測試樣本數據上測試網絡

1. 加載並歸一化CIFAR10

使用torchvision,用它來加載CIFAR10數據是非常簡單

import torch
import torchvision
import torchvision.transforms as transforms

torchvision數據集的輸出是範圍在[0,1]之間的PILImage,我們將他們轉換成歸一化範圍為[-1,1]之間的張量Tensors。

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 Files already downloaded and verified

展示其中的一些訓練圖片。

import matplotlib.pyplot as pltimport 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()
# 得到一些隨機圖像
dataiter = iter(trainloader)images, labels = dataiter.next()
# show imagesimshow(torchvision.utils.make_grid(images))
# 打印類標
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))
使用PyTorch訓練一個分類器

圖片二

輸出:

cat car dog cat

2. 定義一個卷積神經網絡

在這之前從神經網絡章節複製神經網絡,修改它為3通道的圖片(在此之前它被定義為1通道)

import torch.nn as nnimport 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. 定義一個損失函數和優化器

讓我們使用分類交叉熵Cross-Entropy 作損失函數,動量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): # 多次循環遍歷數據集
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: # 每2000 mini-batchs輸出一次 print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')

輸出:

[1, 2000] loss: 2.211
[1, 4000] loss: 1.837
[1, 6000] loss: 1.659
[1, 8000] loss: 1.570
[1, 10000] loss: 1.521
[1, 12000] loss: 1.451
[2, 2000] loss: 1.411
[2, 4000] loss: 1.393
[2, 6000] loss: 1.348
[2, 8000] loss: 1.340
[2, 10000] loss: 1.363

[2, 12000] loss: 1.320
Finished Training

5. 在測試集上測試網絡

我們已經通過訓練數據集對網絡進行了2次訓練,但是我們需要檢查網絡是否已經學到了任何東西。

我們將用神經網絡的輸出作為預測的類標來檢查網絡的預測性能,用樣本的真實類標來校對。如果預測是正確的,我們將樣本添加到正確預測的列表裡。

好的,第一步,讓我們從測試集中顯示一張圖像來熟悉它。

dataiter = iter(testloader)images, labels = dataiter.next()
# 打印圖片
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
使用PyTorch訓練一個分類器

圖片三

輸出:

GroundTruth: cat ship ship plane

現在讓我們神經網絡認為這些樣本應該預測成什麼:

outputs = net(images)

輸出是預測十個類的近似程度,一個類的近似程度越高,網絡就越認為圖像是一個特定的類別。所以讓我們得到最高的相似程度的下標:

_, predicted = torch.max(outputs, 1)
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
for j in range(4)))

輸出:

Predicted: cat car car ship

結果看起開非常好,接下來看一下網絡在整個數據集上的表現。


correct = 0total = 0with 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))

輸出:

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

這看起來比隨機預測要好,隨機預測的準確率為10%(隨機預測出為10類中的哪一類)。看來網絡學到了東西。

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

輸出:

Accuracy of plane : 52 %
Accuracy of car : 73 %
Accuracy of bird : 34 %
Accuracy of cat : 54 %
Accuracy of deer : 48 %
Accuracy of dog : 26 %
Accuracy of frog : 68 %
Accuracy of horse : 51 %
Accuracy of ship : 63 %
Accuracy of truck : 60 %

所以接下來呢?

我們怎麼在GPU上跑這些神經網絡?

三 在GPU上訓練

就像你怎麼把一個張量轉移到GPU上一樣,你要將神經網絡轉到GPU上。

如果CUDA可以用,讓我們首先定義下我們的設備為第一個可見的cuda設備。

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# 假設在一臺CUDA機器上運行,那麼這裡將輸出一個CUDA設備號:
print(device)

輸出:

cuda:0

本節剩餘部分都會假定設備就是臺CUDA設備。

接著這些方法會遞歸地遍歷所有模塊,並將它們的參數和緩衝器轉換為CUDA張量。

net.to(device)

記住你也必須在每一個步驟向GPU發送輸入和目標:

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

為什麼沒有注意到與CPU相比巨大的加速?因為你的網絡非常小。

練習:嘗試增加網絡寬度(首個nn.Conv2d參數設定為2,第二個nn.Conv2d參數設定為1--它們需要有相同的個數),看看會得到怎麼的速度提升。

目標:

  • 深度理解了PyTorch的張量和神經網絡
  • 訓練了一個小的神經網絡來分類圖像

四 在多個GPU上訓練

如果你想要來看到大規模加速,使用你的所有GPU,請查看:數據並行性

(https://pytorch.org/tutorials/beginner/blitz/data_parallel_tutorial.html)。

五 接下來可以學哪些?

  • 訓練神經網絡玩電子遊戲(https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html)
  • 在imagenet上訓練最優ResNet網絡(https://github.com/pytorch/examples/tree/master/imagenet)
  • 使用生成網絡來訓練面部生成器(https://github.com/pytorch/examples/tree/master/dcgan)
  • 使用週期性LSTM網絡訓練一個詞級(word-level)語言模型(https://github.com/pytorch/examples/tree/master/word_language_model)
  • 更多例子 (https://github.com/pytorch/examples)
  • 更多教程 (https://github.com/pytorch/tutorials)
  • 在論壇上討論PyTorch (https://discuss.pytorch.org/)
  • 在Slack上與其他用戶交流 (https://pytorch.slack.com/messages/beginner/)

腳本總運行時間:(9分48.748秒)

下載python源代碼文件:cifar10_tutorial.py

(https://pytorch.org/tutorials/_downloads/ba100c1433c3c42a16709bb6a2ed0f85/cifar10_tutorial.py)

下載Jupyter notebook文件:cifar10_tutorial.ipynb

(https://pytorch.org/tutorials/_downloads/17a7c7cb80916fcdf921097825a0f562/cifar10_tutorial.ipynb)


分享到:


相關文章: