- PyTorch 圖像分類(lèi)器
你已經(jīng)了解了如何定義神經(jīng)網(wǎng)絡(luò),計(jì)算損失值和網(wǎng)絡(luò)里權(quán)重的更新。
現(xiàn)在你也許會(huì)想應(yīng)該怎么處理數(shù)據(jù)?
通常來(lái)說(shuō),當(dāng)你處理圖像,文本,語(yǔ)音或者視頻數(shù)據(jù)時(shí),你可以使用標(biāo)準(zhǔn) python 包將數(shù)據(jù)加載成 numpy 數(shù)組格式,然后將這個(gè)數(shù)組轉(zhuǎn)換成 torch.*Tensor
- 對(duì)于圖像,可以用 Pillow,OpenCV
- 對(duì)于語(yǔ)音,可以用 scipy,librosa
- 對(duì)于文本,可以直接用 Python 或 Cython 基礎(chǔ)數(shù)據(jù)加載模塊,或者用 NLTK 和 SpaCy
特別是對(duì)于視覺(jué),我們已經(jīng)創(chuàng)建了一個(gè)叫做 totchvision 的包,該包含有支持加載類(lèi)似Imagenet,CIFAR10,MNIST 等公共數(shù)據(jù)集的數(shù)據(jù)加載模塊 torchvision.datasets 和支持加載圖像數(shù)據(jù)數(shù)據(jù)轉(zhuǎn)換模塊 torch.utils.data.DataLoader。
這提供了極大的便利,并且避免了編寫(xiě)“樣板代碼”。
對(duì)于本教程,我們將使用CIFAR10數(shù)據(jù)集,它包含十個(gè)類(lèi)別:‘a(chǎn)irplane’, ‘a(chǎn)utomobile’, ‘bird’, ‘cat’, ‘deer’, ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’。CIFAR-10 中的圖像尺寸為33232,也就是RGB的3層顏色通道,每層通道內(nèi)的尺寸為32*32。

訓(xùn)練一個(gè)圖像分類(lèi)器
我們將按次序的做如下幾步:
- 使用torchvision加載并且歸一化CIFAR10的訓(xùn)練和測(cè)試數(shù)據(jù)集
- 定義一個(gè)卷積神經(jīng)網(wǎng)絡(luò)
- 定義一個(gè)損失函數(shù)
- 在訓(xùn)練樣本數(shù)據(jù)上訓(xùn)練網(wǎng)絡(luò)
- 在測(cè)試樣本數(shù)據(jù)上測(cè)試網(wǎng)絡(luò)
加載并歸一化 CIFAR10 使用 torchvision ,用它來(lái)加載 CIFAR10 數(shù)據(jù)非常簡(jiǎn)單。
import torch
import torchvision
import torchvision.transforms as transforms
torchvision 數(shù)據(jù)集的輸出是范圍在[0,1]之間的 PILImage,我們將他們轉(zhuǎn)換成歸一化范圍為[-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
讓我們來(lái)展示其中的一些訓(xùn)練圖片。
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)))
輸出:
cat plane ship frog
定義一個(gè)卷積神經(jīng)網(wǎng)絡(luò) 在這之前先 從神經(jīng)網(wǎng)絡(luò)章節(jié) 復(fù)制神經(jīng)網(wǎng)絡(luò),并修改它為3通道的圖片(在此之前它被定義為1通道)
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()
定義一個(gè)損失函數(shù)和優(yōu)化器 讓我們使用分類(lèi)交叉熵Cross-Entropy 作損失函數(shù),動(dòng)量SGD做優(yōu)化器。
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
訓(xùn)練網(wǎng)絡(luò) 這里事情開(kāi)始變得有趣,我們只需要在數(shù)據(jù)迭代器上循環(huán)傳給網(wǎng)絡(luò)和優(yōu)化器 輸入就可以。
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
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')
輸出:
[1, 2000] loss: 2.187
[1, 4000] loss: 1.852
[1, 6000] loss: 1.672
[1, 8000] loss: 1.566
[1, 10000] loss: 1.490
[1, 12000] loss: 1.461
[2, 2000] loss: 1.389
[2, 4000] loss: 1.364
[2, 6000] loss: 1.343
[2, 8000] loss: 1.318
[2, 10000] loss: 1.282
[2, 12000] loss: 1.286
Finished Training
在測(cè)試集上測(cè)試網(wǎng)絡(luò) 我們已經(jīng)通過(guò)訓(xùn)練數(shù)據(jù)集對(duì)網(wǎng)絡(luò)進(jìn)行了2次訓(xùn)練,但是我們需要檢查網(wǎng)絡(luò)是否已經(jīng)學(xué)到了東西。
我們將用神經(jīng)網(wǎng)絡(luò)的輸出作為預(yù)測(cè)的類(lèi)標(biāo)來(lái)檢查網(wǎng)絡(luò)的預(yù)測(cè)性能,用樣本的真實(shí)類(lèi)標(biāo)來(lái)校對(duì)。如果預(yù)測(cè)是正確的,我們將樣本添加到正確預(yù)測(cè)的列表里。
好的,第一步,讓我們從測(cè)試集中顯示一張圖像來(lái)熟悉它。
輸出:
GroundTruth: cat ship ship plane
現(xiàn)在讓我們看看 神經(jīng)網(wǎng)絡(luò)認(rèn)為這些樣本應(yīng)該預(yù)測(cè)成什么:
outputs = net(images)
輸出是預(yù)測(cè)與十個(gè)類(lèi)的近似程度,與某一個(gè)類(lèi)的近似程度越高,網(wǎng)絡(luò)就越認(rèn)為圖像是屬于這一類(lèi)別。所以讓我們打印其中最相似類(lèi)別類(lèi)標(biāo):
_, predicted = torch.max(outputs, 1)
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
for j in range(4)))
輸出:
Predicted: cat ship car ship
結(jié)果看起開(kāi)非常好,讓我們看看網(wǎng)絡(luò)在整個(gè)數(shù)據(jù)集上的表現(xiàn)。
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))
輸出:
Accuracy of the network on the 10000 test images: 54 %
這看起來(lái)比隨機(jī)預(yù)測(cè)要好,隨機(jī)預(yù)測(cè)的準(zhǔn)確率為10%(隨機(jī)預(yù)測(cè)出為10類(lèi)中的哪一類(lèi))??磥?lái)網(wǎng)絡(luò)學(xué)到了東西。
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]))
輸出:
<pre style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", Courier, monospace; font-size: 1em; white-space: pre;">Accuracy of plane : 57 %
Accuracy of car : 73 %
Accuracy of bird : 49 %
Accuracy of cat : 54 %
Accuracy of deer : 18 %
Accuracy of dog : 20 %
Accuracy of frog : 58 %
Accuracy of horse : 74 %
Accuracy of ship : 70 %
Accuracy of truck : 66 %</pre>
所以接下來(lái)呢?
我們?cè)趺丛贕PU上跑這些神經(jīng)網(wǎng)絡(luò)?
在GPU上訓(xùn)練 就像你怎么把一個(gè)張量轉(zhuǎn)移到GPU上一樣,你要將神經(jīng)網(wǎng)絡(luò)轉(zhuǎn)到GPU上。 如果CUDA可以用,讓我們首先定義下我們的設(shè)備為第一個(gè)可見(jiàn)的cuda設(shè)備。
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Assume that we are on a CUDA machine, then this should print a CUDA device:
print(device)
輸出:
<pre style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", Courier, monospace; font-size: 12px; white-space: pre; margin: 0px; padding: 12px; display: block; overflow: auto; line-height: 1.4;">cuda:0
</pre>
本節(jié)剩余部分都會(huì)假定設(shè)備就是臺(tái)CUDA設(shè)備。
接著這些方法會(huì)遞歸地遍歷所有模塊,并將它們的參數(shù)和緩沖器轉(zhuǎn)換為CUDA張量。
<pre style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", Courier, monospace; font-size: 12px; white-space: pre; margin: 0px; padding: 12px; display: block; overflow: auto; line-height: 1.4;">net.to(device)
</pre>
記住你也必須在每一個(gè)步驟向GPU發(fā)送輸入和目標(biāo):
<pre style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", Courier, monospace; font-size: 12px; white-space: pre; margin: 0px; padding: 12px; display: block; overflow: auto; line-height: 1.4;">inputs, labels = inputs.to(device), labels.to(device)
</pre>
為什么沒(méi)有注意到與CPU相比巨大的加速?因?yàn)槟愕木W(wǎng)絡(luò)非常小。
練習(xí):嘗試增加你的網(wǎng)絡(luò)寬度(首個(gè) nn.Conv2d 參數(shù)設(shè)定為 2,第二個(gè)nn.Conv2d參數(shù)設(shè)定為1--它們需要有相同的個(gè)數(shù)),看看會(huì)得到怎么的速度提升。
目標(biāo):
- 深度理解了PyTorch的張量和神經(jīng)網(wǎng)絡(luò)
- 訓(xùn)練了一個(gè)小的神經(jīng)網(wǎng)絡(luò)來(lái)分類(lèi)圖像
在多個(gè)GPU上訓(xùn)練
如果你想要來(lái)看到大規(guī)模加速,使用你的所有GPU,請(qǐng)查看:數(shù)據(jù)并行性(https://pytorch.org/tutorials/beginner/blitz/data_parallel_tutorial.html)。PyTorch 60 分鐘入門(mén)教程:數(shù)據(jù)并行處理
http://pytorchchina.com/2018/12/11/optional-data-parallelism/
下載 Python 源代碼:
下載 Jupyter 源代碼: