目錄
- TRAINING A CLASSIFIER 訓練一個分類器
- 數據呢?
- Training an image classifier 訓練一個圖像分類器
- 1. 載入和歸一化CIFAR10
- 2. Define a Convolutional Neural Network 定義一個卷積神經網絡
- 3. Define a Loss function and optimizer 定義一個loss函數和優化器
- 4. Train the network 訓練網絡
- 5. Test the network on the test data 用測試數據測試網絡
- Training on GPU GPU上訓練
- Training on multiple GPUs 在多GPU上訓練.
- Where do I go next? 下面做什麼?
TRAINING A CLASSIFIER 訓練一個分類器
就這樣. 你已經知道怎樣定義神經網絡, 計算loss和更新網絡權重.
現在你可能會想:
數據呢?
一般, 當處理圖片, 文本, 音頻或者視頻數據時, 你可以使用標準的python包,將數據載入爲numpy array. 然後你可以將array轉化爲torch.*Tensor
.
對於圖片, Pillow, OpenCV之類的包較爲有用.
對於音頻, 可以用scipy和librosa
對於文本, 基於原生Python或Cython的載入功能, NLTK和SpaCy之類的較爲有用.
特別對於視覺(vision), 我們創建了一個包叫torchvision
. 它有常用datasets(如ImageNet, CIFAR10, MNIST等)的數據載入工具(data loader)和圖片轉換工具, 也就是torchvision.datasets
和torch.utils.data.DataLoader
.
用起來很方便.
這個教程裏. 我們用CIFAR10數據庫. 有 ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’, ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’十個類別的圖片. 圖片3x32x32. 也就是3通道, 32x32大小.
Training an image classifier 訓練一個圖像分類器
步驟:
- 用
torchvision
載入和歸一化訓練和測試數據, - 定義卷積神經網絡(CNN)
- 定義loss函數
- 訓練
- 測試
1. 載入和歸一化CIFAR10
使用torchvision
, 很簡單.
import torch
import torchvision
import torchvision.transforms as transforms
torchvision
的輸出是PILImage, 範圍[0,1]. 我們將其轉化爲歸一化到[-1, 1]範圍的Tensor
.
注意:
如果在Windows上出現BrokenPipeError
, 將torch.utils.data.DataLoader()
的num_worker
置爲0.
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')
Out:
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):
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)))
../../_images/sphx_glr_cifar10_tutorial_001.png
Out:
dog bird ship dog
2. Define a Convolutional Neural Network 定義一個卷積神經網絡
將之前定義的網絡拷貝過來, 修改爲接收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 定義一個loss函數和優化器
用分類交叉熵和帶動量(momentum)的SGD.
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
4. Train the network 訓練網絡
有意思的地方來了. 我們簡單地在數據迭代器(data iterator)上循環遍歷, 將輸入餵給網絡並優化.
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')
Out:
[1, 2000] loss: 2.235
[1, 4000] loss: 1.902
[1, 6000] loss: 1.674
[1, 8000] loss: 1.571
[1, 10000] loss: 1.529
[1, 12000] loss: 1.478
[2, 2000] loss: 1.389
[2, 4000] loss: 1.391
[2, 6000] loss: 1.359
[2, 8000] loss: 1.335
[2, 10000] loss: 1.330
[2, 12000] loss: 1.289
Finished Training
保存訓練好的模型:
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)
這裏有更多的保存模型的細節.
5. Test the network on the test data 用測試數據測試網絡
我們已經訓練了兩輪了, 我們看看網絡是否學到東西了.
我們將模型輸出的結果和真實結果(ground-truth)作比較. 如果預測是正確的, 我們將這個sample加到正確預測的list中.
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)))
Out:
GroundTruth: cat ship ship plane
然後, 重新載入保存的模型(注意: 保存和重新載入模型不是必要的, 我們這裏只是爲了說明怎樣做):
net = Net()
net.load_state_dict(torch.load(PATH))
好, 我們來看看模型分類結果如何:
outputs = net(images)
輸出是10類的置信度(energy). 某一類的置信度越高, 網絡認爲圖片是此類的可能性越大. 所以, 我們來獲取最高的置信度:
_, predicted = torch.max(outputs, 1)
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
for j in range(4)))
Out:
Predicted: cat ship ship ship
結果還不錯, 我們來看看整個數據集上的表現:
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: 53 %
看起來比隨機猜測要好. 隨機猜測正確率是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]))
Out:
Accuracy of plane : 56 %
Accuracy of car : 74 %
Accuracy of bird : 30 %
Accuracy of cat : 29 %
Accuracy of deer : 57 %
Accuracy of dog : 37 %
Accuracy of frog : 73 %
Accuracy of horse : 62 %
Accuracy of ship : 56 %
Accuracy of truck : 53 %
好了, 接下來做什麼呢?
怎樣在GPU上跑神經網絡呢?
Training on GPU GPU上訓練
正如將Tensor
轉到GPU上一樣, 你可以將網絡轉到GPU上.
如果CUDA有效的話, 將device定義爲第一個可用的cuda設備.
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)
Out:
cuda:0
剩下的部分, 我們認爲device就是CUDA device.
然後這些方法將會遞歸地遍歷我們的模型部件(module)並將他們的參數和buffer轉爲CUDA tensor:
net.to(device)
記住, 你必須要在每一步中將輸入圖像和目標輸出都轉到GPU上:
inputs, labels = data[0].to(device), data[1].to(device)
爲什麼我們有看到很大的速度提升? 因爲你的模型太小了.
練習: 嘗試增大網絡寬度(第一個nn.Conv2d
的第二個參數, 第二個nn.Conv2d
的第一個參數, 兩者要相等), 看看提速效果如何.
目標達成:
- 在高層(high level)上理解Pytorch Tensor庫和神經網絡.
- 訓練一個分類圖片的小神經網絡.
Training on multiple GPUs 在多GPU上訓練.
如果你想用多塊GPU訓練, 請看: Data Parallelism.
Where do I go next? 下面做什麼?
Total running time of the script: ( 3 minutes 29.428 seconds)