到目前為止,我們主要關(guān)注如何更新權(quán)重向量的優(yōu)化算法,而不是更新權(quán)重向量的速率。盡管如此,調(diào)整學(xué)習(xí)率通常與實際算法一樣重要。有幾個方面需要考慮:
-
最明顯的是學(xué)習(xí)率的大小很重要。如果它太大,優(yōu)化就會發(fā)散,如果它太小,訓(xùn)練時間太長,或者我們最終會得到一個次優(yōu)的結(jié)果。我們之前看到問題的條件編號很重要(例如,參見第 12.6 節(jié)了解詳細(xì)信息)。直觀地說,它是最不敏感方向的變化量與最敏感方向的變化量之比。
-
其次,衰減率同樣重要。如果學(xué)習(xí)率仍然很大,我們可能最終會在最小值附近跳來跳去,因此無法達(dá)到最優(yōu)。12.5 節(jié) 詳細(xì)討論了這一點,我們在12.4 節(jié)中分析了性能保證。簡而言之,我們希望速率下降,但可能比O(t?12)這將是凸問題的不錯選擇。
-
另一個同樣重要的方面是初始化。這既涉及參數(shù)的初始設(shè)置方式(詳見 第 5.4 節(jié)),也涉及它們最初的演變方式。這在熱身的綽號下進行,即我們最初開始朝著解決方案前進的速度。一開始的大步驟可能沒有好處,特別是因為初始參數(shù)集是隨機的。最初的更新方向也可能毫無意義。
-
最后,還有許多執(zhí)行循環(huán)學(xué)習(xí)率調(diào)整的優(yōu)化變體。這超出了本章的范圍。我們建議讀者查看 Izmailov等人的詳細(xì)信息。( 2018 ),例如,如何通過對整個參數(shù)路徑進行平均來獲得更好的解決方案。
鑒于管理學(xué)習(xí)率需要很多細(xì)節(jié),大多數(shù)深度學(xué)習(xí)框架都有自動處理這個問題的工具。在本章中,我們將回顧不同的調(diào)度對準(zhǔn)確性的影響,并展示如何通過學(xué)習(xí)率調(diào)度器有效地管理它。
12.11.1。玩具問題
我們從一個玩具問題開始,這個問題足夠簡單,可以輕松計算,但又足夠不平凡,可以說明一些關(guān)鍵方面。為此,我們選擇了一個稍微現(xiàn)代化的 LeNet 版本(relu
而不是 sigmoid
激活,MaxPooling 而不是 AveragePooling)應(yīng)用于 Fashion-MNIST。此外,我們混合網(wǎng)絡(luò)以提高性能。由于大部分代碼都是標(biāo)準(zhǔn)的,我們只介紹基礎(chǔ)知識而不進行進一步的詳細(xì)討論。如有需要,請參閱第 7 節(jié)進行復(fù)習(xí)。
%matplotlib inline
import math
import torch
from torch import nn
from torch.optim import lr_scheduler
from d2l import torch as d2l
def net_fn():
model = nn.Sequential(
nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(6, 16, kernel_size=5), nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Flatten(),
nn.Linear(16 * 5 * 5, 120), nn.ReLU(),
nn.Linear(120, 84), nn.ReLU(),
nn.Linear(84, 10))
return model
loss = nn.CrossEntropyLoss()
device = d2l.try_gpu()
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
# The code is almost identical to `d2l.train_ch6` defined in the
# lenet section of chapter convolutional neural networks
def train(net, train_iter, test_iter, num_epochs, loss, trainer, device,
scheduler=None):
net.to(device)
animator = d2l.Animator(xlabel='epoch', xlim=[0, num_epochs],
legend=['train loss', 'train acc', 'test acc'])
for epoch in range(num_epochs):
metric = d2l.Accumulator(3) # train_loss, train_acc, num_examples
for i, (X, y) in enumerate(train_iter):
net.train()
trainer.zero_grad()
X, y = X.to(device), y.to(device)
y_hat = net(X)
l = loss(y_hat, y)
l.backward()
trainer.step()
with torch.no_grad():
metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])
train_loss = metric[0] / metric[2]
train_acc = metric[1] / metric[2]
if (i + 1) % 50 == 0:
animator.add(epoch + i / len(train_iter),
(train_loss, train_acc, None))
test_acc = d2l.evaluate_accuracy_gpu(net, test_iter)
animator.add(epoch+1, (None, None, test_acc))
if scheduler:
if scheduler.__module__ == lr_scheduler.__name__:
# Using PyTorch In-Built scheduler
scheduler.step()
else:
# Using custom defined scheduler
for param_group in trainer.param_groups:
param_group['lr'] = scheduler(epoch)
print(f'train loss {train_loss:.3f}, train acc {train_acc:.3f}, '
f'test acc {test_acc:.3f}')
%matplotlib inline
from mxnet import autograd, gluon, init, lr_scheduler, np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l
npx.set_np()
net = nn.HybridSequential()
net.add(nn.Conv2D(channels=6, kernel_size=5, padding=2, activation='relu'),
nn.MaxPool2D(pool_size=2, strides=2),
nn.Conv2D(channels=16, kernel_size=5, activation='relu'),
nn.MaxPool2D(pool_size=2, strides=2),
nn.Dense(120, activation='relu'),
nn.Dense(84, activation='relu'),
nn.Dense(10))
net.hybridize()
loss = gluon.loss.SoftmaxCrossEntropyLoss()
device = d2l.try_gpu()
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
# The code is almost identical to `d2l.train_ch6` defined in the
# lenet section of chapter convolutional neural networks
def train(net, train_iter, test_iter, num_epochs, loss, trainer, device):
net.initialize(force_reinit=True, ctx=device, init=init.Xavier())
animator = d2l.Animator(xlabel='epoch', xlim=[0, num_epochs],
legend=['train loss', 'train acc', 'test acc'])
for epoch in range(num_epochs):
metric = d2l.Accumulator(3) # train_loss, train_acc, num_examples
for i, (X, y) in enumerate(train_iter):
X, y = X.as_in_ctx(device), y.as_in_ctx(device)
with autograd.record():
y_hat = net(X)
l = loss(y_hat, y)
l.backward()
trainer.step(X.shape[0])
metric.add(l.sum(), d2l.accuracy(y_hat, y), X.shape[0])
train_loss = metric[0] / metric[2]
train_acc = metric[1] / metric[2]
if (i + 1) % 50 == 0:
animator.add(epoch + i / len(train_iter),
(train_loss, train_acc, None))
test_acc = d2l.evaluate_accuracy_gpu(net, test_iter)
animator.add(epoch + 1, (None, None, test_acc))
print(f'train loss {train_loss:.3f}, train acc {train_acc:.3f}, '
f'test acc {test_acc:.3f}')
%matplotlib inline
import math
import tensorflow as tf
from tensorflow.keras.callbacks import LearningRateScheduler
from d2l import tensorflow as d2l
def net():
return tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters=6, kernel_size=5, activation='relu',
padding='same'),
tf.keras.layers.AvgPool2D(pool_size=2, strides=2),
tf.keras.layers.Conv2D(filters=16, kernel_size=5,
activation='relu'),
tf.keras.layers.AvgPool2D(pool_size=2, strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(120, activation='relu'),
tf.keras.layers.Dense(84, activation='sigmoid'),
tf.keras.layers.Dense(10)])
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
# The code is almost identical to `d2l.train_ch6` defined in the
# lenet section of chapter convolutional neural networks
def train(net_fn, train_iter, test_iter, num_epochs, lr,
device=d2l.try_gpu(), custom_callback = False):
device_name =
評論
查看更多