訓練神經(jīng)網(wǎng)絡
在上一部分中,我們建立的神經(jīng)網(wǎng)絡不是那么好,它對我們的手寫數(shù)字一無所知。 神經(jīng)網(wǎng)絡的非線性激活函數(shù)工作方式類似于通用函數(shù)擬合。 有一些函數(shù),可以將您的輸入映射到輸出。 例如,將手寫數(shù)字圖像分類的概率。 神經(jīng)網(wǎng)絡的強大之處,在于我們可以訓練它們以逼近該F函數(shù)。只要給定任何具有足夠數(shù)據(jù)和計算時間,就可以得到F函數(shù),但這個函數(shù)可能非常復雜。

起初,網(wǎng)絡是無知的,它不知道將輸入映射到輸出函數(shù)。 我們將通過真實數(shù)據(jù)的示例來訓練網(wǎng)絡,然后調(diào)整網(wǎng)絡參數(shù)以使其接近此F函數(shù)。
為了找到這些參數(shù),我們需要通過網(wǎng)絡預測實際輸出。 為此,我們計算了損失函數(shù)(也稱為成本),這是對我們的預測誤差的度量。 例如,均方損失函數(shù)通常用于回歸和二元分類問題:
其中是訓練示例的數(shù)量,
是真實的標簽,
是預測的標簽。
通過相對于網(wǎng)絡參數(shù),使這種損失最小化,我們可以找到損失最小且網(wǎng)絡能夠以高精度預測正確標簽的參數(shù)。 我們使用梯度下降算法尋找最小值。 梯度是損失函數(shù)的斜率,指向變化最快的方向。 為了在最短的時間內(nèi)達到最小,我們要遵循梯度(向下)。 您可以認為這就像通過沿著最陡峭的坡道下山。

反向傳播
對于單層網(wǎng)絡,梯度下降很容易實現(xiàn)。 但是,對于像我們構建的那樣的更深層次的多層神經(jīng)網(wǎng)絡來說,它要復雜得多。 如此復雜,以至于研究人員花了大約30年的時間才弄清楚如何訓練多層網(wǎng)絡。
訓練多層網(wǎng)絡是通過反向傳播來完成的,反向傳播實際上只是微積分中鏈式法則的一種應用。 如果將兩層網(wǎng)絡轉(zhuǎn)換為圖形表示,則最容易理解。

在網(wǎng)絡的前向傳播中,我們的數(shù)據(jù)和操作在這里從下到上。 我們輸入經(jīng)過權重為
且偏置項為
的線性變換
。 然后,經(jīng)過sigmoig函數(shù)操作
和另一個線性變換
。 最后,我們計算損失
。 我們使用損失函數(shù)來衡量網(wǎng)絡預測的準確程度。 然后的目標是調(diào)整權重和偏差以使損失最小化。
為了訓練梯度下降的權重,我們通過網(wǎng)絡向后傳播得到梯度。 每個操作在輸入和輸出之間都有一定的梯度。 在反向傳播時,我們將輸入的梯度乘以操作的梯度。 從數(shù)學上講,這實際上只是使用鏈式法則計算損失函數(shù)的梯度。
注意:我在這里省略了一些向量微積分知識。我們使用具有一定學習率 的梯度更新權重。
設置學習率α,利用最小迭代次數(shù)使權重快速更新,以使得損失函數(shù)最小化。
損失函數(shù)
讓我們開始看看如何使用PyTorch計算損失函數(shù)。 通過nn模塊,PyTorch提供了諸如交叉熵損失函數(shù)(nn.CrossEntropyLoss)。 您通常會看到損失分配給 criterion。 如上述所示,對于例如 MNIST 的分類問題,我們使用softmax函數(shù)預測類概率。 對于softmax輸出,您想使用交叉熵作為損失函數(shù)。 要實際計算誤差,先要定義標準 criterion,然后再傳遞網(wǎng)絡輸出和正確的標簽。
這里要特別注意的重要事項。 查看the documentation for nn.CrossEntropyLoss的文檔。
此條件將
nn.LogSoftmax()和nn.NLLLoss()組合在一個類中。該輸入應包含每個類的分數(shù)。
這意味著我們需要將網(wǎng)絡的原始輸出傳遞到損失函數(shù)中,而不是softmax函數(shù)中。 我們使用logits是因為softmax給您的概率通常非常接近零或一,但是浮點數(shù)不能準確地表示接近零或一。 最好避免使用概率進行計算,因此我們使用對數(shù)概率。
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import datasets, transforms
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,)),
])
# Download and load the training data
trainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)
注意:如果還不了解nn.Sequential,請看上一次的內(nèi)容。
# Build a feed-forward network
model = nn.Sequential(nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 10))
# Define the loss
criterion = nn.CrossEntropyLoss()
# Get our data
images, labels = next(iter(trainloader))
# Flatten images
images = images.view(images.shape[0], -1)
# Forward pass, get our logits
logits = model(images)
# Calculate the loss with the logits and the labels
loss = criterion(logits, labels)
print(loss)
tensor(2.3010, grad_fn=<NllLossBackward>)
根據(jù)經(jīng)驗,使用log-softmax(用nn.LogSoftmax或F.log_softmax函數(shù))構建模型更為方便。 然后,您可以通過取指數(shù)torch.exp(output)來獲得實際概率。 對于log-softmax輸出,您要使用負對數(shù)似然損失nn.NLLLoss(文檔)。
練習:建立一個返回log-softmax作為輸出的模型,并使用負對數(shù)似然損失來計算損失。 請注意,對于
nn.LogSoftmax和F.log_softmax,您需要適當?shù)卦O置dim關鍵字參數(shù)。dim = 0計算各行的softmax,因此每一列的總和為1,而dim = 1計算各列的總和,因此每一行的總和為1??紤]一下輸出是什么,并適當選擇dim。
# TODO: Build a feed-forward network
model = nn.Sequential(nn.Linear(784,128),
nn.ReLU(),
nn.Linear(128,64),
nn.ReLU(),
nn.Linear(64,10),
nn.LogSoftmax(dim=1))
# TODO: Define the loss
criterion = nn.NLLLoss()
### Run this to check your work
# Get our data
images, labels = next(iter(trainloader))
# Flatten images
images = images.view(images.shape[0], -1)
# Forward pass, get our logits
logits = model(images)
# Calculate the loss with the logits and the labels
loss = criterion(logits, labels)
print(loss)
tensor(2.3090, grad_fn=<NllLossBackward>)
自動求梯度
現(xiàn)在我們知道了如何計算損失函數(shù),如何使用它進行反向傳播? Torch提供了一個autograd模塊,用于自動計算張量的梯度。 我們可以使用它來計算所有參數(shù)相對于損失函數(shù)的梯度。 Autograd的工作方式是跟蹤張量上執(zhí)行的操作,然后向后進行這些操作,并計算沿途的梯度。 為了確保PyTorch跟蹤張量上的操作并計算梯度,你需要在張量上設置require_grad = True。 你可以在創(chuàng)建時使用require_grad關鍵字來執(zhí)行此操作,也可以隨時使用x.requires_grad_(True)來執(zhí)行此操作。
你可以使用 torch.no_grad() 來關閉梯度的計算:
x = torch.zeros(1, requires_grad=True)
>>> with torch.no_grad():
... y = x * 2
>>> y.requires_grad
False
另外,您可以使用torch.set_grad_enabled(True | False)來打開或關閉梯度。
使用z.backward()針對某些變量z計算梯度。 這會反向傳播創(chuàng)建z的操作。
x = torch.randn(2,2, requires_grad=True)
print(x)
tensor([[-0.7619, -0.9604],
[-0.6987, 1.2588]], requires_grad=True)
y = x**2
print(y)
tensor([[0.5805, 0.9223],
[0.4882, 1.5845]], grad_fn=<PowBackward0>)
在下面我們可以看到創(chuàng)建y的操作,即冪操作PowBackward0。
## grad_fn shows the function that generated this variable
print(y.grad_fn)
<PowBackward0 object at 0x000002AD868AD780>
autograd模塊會跟蹤這些操作,并且知道如何計算每個梯度。 通過這種方式,它可以針對任何一個張量計算一系列操作的梯度。 讓我們將張量y變?yōu)闃肆?,即取均值?/p>
z = y.mean()
print(z)
tensor(0.8938, grad_fn=<MeanBackward0>)
請檢查 x 與y 的梯度是否為空
print(x.grad)
None
要計算梯度,您需要在變量(例如z)上運行.backward方法。 這將計算z相對于x的梯度
z.backward()
print(x.grad)
print(x/2)
tensor([[-0.3809, -0.4802],
[-0.3493, 0.6294]])
tensor([[-0.3809, -0.4802],
[-0.3493, 0.6294]], grad_fn=<DivBackward0>)
這些梯度計算對于神經(jīng)網(wǎng)絡特別有用。 對于訓練,我們需要相對于損失函數(shù)的梯度。 使用PyTorch,我們通過網(wǎng)絡正向傳播數(shù)據(jù)以計算損失,然后反向傳播以計算相對于損失函數(shù)的梯度。 一旦有了梯度,就可以進行梯度下降步驟。
損失與梯度
當我們使用PyTorch創(chuàng)建網(wǎng)絡時,所有參數(shù)都使用require_grad = True初始化。 這意味著當我們計算損失并調(diào)用loss.backward()時,將計算參數(shù)的梯度。 這些梯度用于通過梯度下降來更新權重。 在下面,您可以看到一個利用反向傳播通過計算梯度的例子。
# Build a feed-forward network
model = nn.Sequential(nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 10),
nn.LogSoftmax(dim=1))
criterion = nn.NLLLoss()
images, labels = next(iter(trainloader))
images = images.view(images.shape[0], -1)
logits = model(images)
loss = criterion(logits, labels)
print('Before backward pass: \n', model[0].weight.grad)
loss.backward()
print('After backward pass: \n', model[0].weight.grad)
Before backward pass:
None
After backward pass:
tensor([[ 0.0002, 0.0002, 0.0002, ..., 0.0002, 0.0002, 0.0002],
[ 0.0058, 0.0058, 0.0058, ..., 0.0058, 0.0058, 0.0058],
[-0.0002, -0.0002, -0.0002, ..., -0.0002, -0.0002, -0.0002],
...,
[ 0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000],
[-0.0012, -0.0012, -0.0012, ..., -0.0012, -0.0012, -0.0012],
[ 0.0024, 0.0024, 0.0024, ..., 0.0024, 0.0024, 0.0024]])
訓練神經(jīng)網(wǎng)絡
我們需要開始進行最后一步訓練,這是一個優(yōu)化器,我們將使用它使用梯度來更新權重。 我們是從PyTorch的optim中獲得的。 例如,我們可以將隨機梯度下降與optim.SGD一起使用。 您可以在下面查看如何定義優(yōu)化器。
from torch import optim
# Optimizers require the parameters to optimize and a learning rate
optimizer = optim.SGD(model.parameters(), lr=0.01)
現(xiàn)在我們知道了如何使用所有各個部分,現(xiàn)在該看看它們?nèi)绾螀f(xié)同工作。 在遍歷所有數(shù)據(jù)之前,我們只考慮一個學習步驟。 PyTorch的一般過程:
- 通過網(wǎng)絡進行正向傳播傳遞
- 使用網(wǎng)絡輸出來計算損失
- 使用
loss.backward()通過網(wǎng)絡進行反向傳播以計算梯度 - 使用優(yōu)化器(隨機梯度下降算法)更新權重
下面,我將進行一個訓練步驟,并打印出權重和梯度,以便您查看其變化。 請注意,我有一行代碼optimizer.zero_grad()。 當你使用相同的參數(shù)進行多次向后傳遞時,會導致梯度累積。 這意味著你需要在每次訓練通過時將梯度歸零,否則你將保留先前訓練批次中的梯度。
print('Initial weights - ', model[0].weight)
images, labels = next(iter(trainloader))
images.resize_(64, 784)
# Clear the gradients, do this because gradients are accumulated
optimizer.zero_grad()
# Forward pass, then backward pass, then update weights
output = model(images)
loss = criterion(output, labels)
loss.backward()
print('Gradient -', model[0].weight.grad)
Initial weights - Parameter containing:
tensor([[ 0.0310, -0.0118, -0.0347, ..., -0.0017, 0.0066, -0.0122],
[ 0.0007, 0.0074, 0.0232, ..., -0.0357, 0.0227, 0.0052],
[ 0.0121, -0.0286, 0.0265, ..., 0.0174, 0.0127, -0.0132],
...,
[ 0.0347, 0.0156, 0.0166, ..., 0.0303, -0.0136, 0.0295],
[-0.0146, -0.0036, 0.0253, ..., -0.0104, 0.0069, 0.0213],
[ 0.0028, 0.0031, -0.0184, ..., -0.0025, 0.0256, -0.0037]],
requires_grad=True)
Gradient - tensor([[ 0.0002, 0.0002, 0.0002, ..., 0.0002, 0.0002, 0.0002],
[-0.0004, -0.0004, -0.0004, ..., -0.0004, -0.0004, -0.0004],
[-0.0001, -0.0001, -0.0001, ..., -0.0001, -0.0001, -0.0001],
...,
[-0.0003, -0.0003, -0.0003, ..., -0.0003, -0.0003, -0.0003],
[-0.0002, -0.0002, -0.0002, ..., -0.0002, -0.0002, -0.0002],
[ 0.0013, 0.0013, 0.0013, ..., 0.0013, 0.0013, 0.0013]])
# Take an update step and few the new weights
optimizer.step()
print('Updated weights - ', model[0].weight)
Updated weights - Parameter containing:
tensor([[ 0.0310, -0.0118, -0.0347, ..., -0.0017, 0.0066, -0.0122],
[ 0.0007, 0.0074, 0.0232, ..., -0.0357, 0.0227, 0.0052],
[ 0.0121, -0.0286, 0.0265, ..., 0.0174, 0.0127, -0.0132],
...,
[ 0.0347, 0.0156, 0.0166, ..., 0.0303, -0.0136, 0.0296],
[-0.0146, -0.0035, 0.0253, ..., -0.0104, 0.0069, 0.0213],
[ 0.0028, 0.0031, -0.0184, ..., -0.0025, 0.0256, -0.0037]],
requires_grad=True)
真正訓練神經(jīng)網(wǎng)絡
現(xiàn)在,我們將該算法放入循環(huán)中,以便可以遍歷所有圖像。 遍歷整個數(shù)據(jù)集的過程稱為epoch。 因此,在這里,我們將遍歷Trainloader,以獲取我們的訓練批次。 對于每一批,我們將進行一次訓練,計算損失,進行反向傳播,并更新權重。
練習:我們利用神經(jīng)網(wǎng)絡進行訓練。 如果過程沒問題的化,則每個epoch的訓練損失都會減少。
## Your solution here
model = nn.Sequential(nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 10),
nn.LogSoftmax(dim=1))
criterion = nn.NLLLoss()
optimizer = optim.SGD(model.parameters(), lr=0.003)
epochs = 10
for e in range(epochs):
running_loss = 0
for images, labels in trainloader:
# Flatten MNIST images into a 784 long vector
images = images.view(images.shape[0], -1)
# TODO: Training pass
optimizer.zero_grad()
output = model(images)
loss = criterion(output, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
else:
print(f"Training loss: {running_loss/len(trainloader)}")
Training loss: 1.9486986867654552
Training loss: 0.8663170544831738
Training loss: 0.5123799103917852
Training loss: 0.4224105821108259
Training loss: 0.38050861858419266
Training loss: 0.3551620597651264
Training loss: 0.33704469087662725
Training loss: 0.3233772503859453
Training loss: 0.31237514997755034
Training loss: 0.3026550426952112
經(jīng)過訓練的神經(jīng)網(wǎng)絡,我們可以查看它的預測。
%matplotlib inline
import helper
images, labels = next(iter(trainloader))
img = images[0].view(1, 784)
# Turn off gradients to speed up this part
with torch.no_grad():
logps = model(img)
# Output of the network are log-probabilities, need to take exponential for probabilities
ps = torch.exp(logps)
helper.view_classify(img.view(1, 28, 28), ps)

現(xiàn)在,我們的網(wǎng)絡非常出色。 它可以準確預測我們圖像中的數(shù)字。