优化模型参数#
现在已经拥有了模型和数据,是时候通过在数据上优化其参数来训练、验证和测试模型了。训练模型是一个迭代过程;在每次迭代中,模型会对输出做出猜测,计算其猜测中的误差(损失),收集误差相对于其参数的导数(正如我们在先前部分看到的),并使用梯度下降法 优化 这些参数。想要更详细地了解这个过程,请查看这个关于反向传播的视频,由3Blue1Brown提供。
先决条件代码#
从之前的部分加载代码,包括数据集与DataLoaders和构建模型。
from set_env import temp_dir
项目根目录:/media/pc/data/lxw/ai/torch-book
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
training_data = datasets.FashionMNIST(
root=temp_dir/"data",
train=True,
download=True,
transform=ToTensor()
)
test_data = datasets.FashionMNIST(
root=temp_dir/"data",
train=False,
download=True,
transform=ToTensor()
)
train_dataloader = DataLoader(training_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)
class NeuralNetwork(nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
model = NeuralNetwork()
超参数#
超参数是可调参数,允许控制模型优化过程。不同的超参数值会影响模型训练和收敛速度(了解更多 关于超参数调优)
为训练定义了以下超参数:
Epoch 数量 - 遍历数据集的次数
批量大小 - 在更新参数之前通过网络传播的数据样本数量
学习率 - 在每个批次/epoch 更新模型参数的幅度。较小的值会导致学习速度缓慢,而较大的值可能会导致训练过程中出现不可预测的行为。
learning_rate = 1e-3
batch_size = 64
epochs = 5
循环优化#
一旦我们设置了超参数,就可以通过循环优化来训练和优化我们的模型。优化循环的每次迭代称为一个 epoch。
每个 epoch 包含两个主要部分:
训练循环:遍历训练数据集,尝试收敛到最优参数。
验证/测试循环:遍历测试数据集,检查模型性能是否有所提高。
简要熟悉一下训练循环中使用的一些概念。跳到 完整实现 查看循环优化的完整实现。
损失函数#
当给定一些训练数据时,未训练的网络可能不会给出正确的答案。损失函数 衡量获得结果与目标值之间的差异程度,希望在训练过程中最小化损失函数。为了计算损失,使用给定数据样本的输入进行预测,并将其与真实数据标签值进行比较。
常见的损失函数包括 torch.nn.MSELoss
(均方误差)用于回归任务,以及 torch.nn.NLLLoss
(负对数似然)用于分类任务。torch.nn.CrossEntropyLoss
结合了 torch.nn.LogSoftmax
和 torch.nn.NLLLoss
。
将模型的输出 logits
传递给 torch.nn.CrossEntropyLoss
,它将对 logits
进行归一化并计算预测误差。
# Initialize the loss function
loss_fn = nn.CrossEntropyLoss()
优化器#
优化是调整模型参数以在每个训练步骤中减少模型误差的过程。优化算法 定义了如何执行此过程(在本例中,使用随机梯度下降)。所有优化逻辑都封装在 optimizer
对象中。在这里,使用 SGD 优化器;此外,PyTorch 中还有许多 不同的优化器,例如 ADAM 和 RMSProp,它们适用于不同类型的模型和数据。
通过注册需要训练的模型参数并传入学习率超参数来初始化优化器。
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
在训练循环内部,优化分为三个步骤:
调用
optimizer.zero_grad()
来重置模型参数的梯度。默认情况下,梯度会累加;为了避免重复计算,我们在每次迭代时显式地将它们归零。通过调用
loss.backward()
反向传播预测损失。PyTorch 将损失相对于每个参数的梯度存储起来。一旦我们有了梯度,我们调用
optimizer.step()
来根据反向传播中收集的梯度调整参数。
完整实现#
定义 train_loop
来循环执行优化代码,并定义 test_loop
来评估模型在测试数据上的性能。
def train_loop(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
# Set the model to training mode - important for batch normalization and dropout layers
# Unnecessary in this situation but added for best practices
model.train()
for batch, (X, y) in enumerate(dataloader):
# Compute prediction and loss
pred = model(X)
loss = loss_fn(pred, y)
# Backpropagation
loss.backward()
optimizer.step()
optimizer.zero_grad()
if batch % 100 == 0:
loss, current = loss.item(), batch * batch_size + len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
def test_loop(dataloader, model, loss_fn):
# Set the model to evaluation mode - important for batch normalization and dropout layers
# Unnecessary in this situation but added for best practices
model.eval()
size = len(dataloader.dataset)
num_batches = len(dataloader)
test_loss, correct = 0, 0
# Evaluating the model with torch.no_grad() ensures that no gradients are computed during test mode
# also serves to reduce unnecessary gradient computations and memory usage for tensors with requires_grad=True
with torch.no_grad():
for X, y in dataloader:
pred = model(X)
test_loss += loss_fn(pred, y).item()
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
test_loss /= num_batches
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
初始化损失函数和优化器,并将其传递给 train_loop
和 test_loop
。可以随意增加 epoch
的数量以跟踪模型性能的提升。
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
epochs = 10
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train_loop(train_dataloader, model, loss_fn, optimizer)
test_loop(test_dataloader, model, loss_fn)
print("Done!")
Show code cell output
Epoch 1
-------------------------------
loss: 2.299955 [ 64/60000]
loss: 2.289047 [ 6464/60000]
loss: 2.262702 [12864/60000]
loss: 2.262147 [19264/60000]
loss: 2.255074 [25664/60000]
loss: 2.209852 [32064/60000]
loss: 2.228119 [38464/60000]
loss: 2.189891 [44864/60000]
loss: 2.186696 [51264/60000]
loss: 2.157851 [57664/60000]
Test Error:
Accuracy: 43.2%, Avg loss: 2.150610
Epoch 2
-------------------------------
loss: 2.160350 [ 64/60000]
loss: 2.152020 [ 6464/60000]
loss: 2.087391 [12864/60000]
loss: 2.109184 [19264/60000]
loss: 2.062347 [25664/60000]
loss: 1.993510 [32064/60000]
loss: 2.032360 [38464/60000]
loss: 1.952619 [44864/60000]
loss: 1.954293 [51264/60000]
loss: 1.886026 [57664/60000]
Test Error:
Accuracy: 60.6%, Avg loss: 1.879761
Epoch 3
-------------------------------
loss: 1.912941 [ 64/60000]
loss: 1.882683 [ 6464/60000]
loss: 1.757799 [12864/60000]
loss: 1.807219 [19264/60000]
loss: 1.694405 [25664/60000]
loss: 1.644480 [32064/60000]
loss: 1.674132 [38464/60000]
loss: 1.576804 [44864/60000]
loss: 1.595409 [51264/60000]
loss: 1.493224 [57664/60000]
Test Error:
Accuracy: 62.9%, Avg loss: 1.508747
Epoch 4
-------------------------------
loss: 1.576287 [ 64/60000]
loss: 1.541384 [ 6464/60000]
loss: 1.386807 [12864/60000]
loss: 1.465601 [19264/60000]
loss: 1.344606 [25664/60000]
loss: 1.341592 [32064/60000]
loss: 1.360759 [38464/60000]
loss: 1.288418 [44864/60000]
loss: 1.315813 [51264/60000]
loss: 1.218872 [57664/60000]
Test Error:
Accuracy: 64.0%, Avg loss: 1.244145
Epoch 5
-------------------------------
loss: 1.322750 [ 64/60000]
loss: 1.304346 [ 6464/60000]
loss: 1.136508 [12864/60000]
loss: 1.245479 [19264/60000]
loss: 1.122106 [25664/60000]
loss: 1.148881 [32064/60000]
loss: 1.172815 [38464/60000]
loss: 1.111189 [44864/60000]
loss: 1.142142 [51264/60000]
loss: 1.061584 [57664/60000]
Test Error:
Accuracy: 65.1%, Avg loss: 1.081436
Epoch 6
-------------------------------
loss: 1.154250 [ 64/60000]
loss: 1.156330 [ 6464/60000]
loss: 0.972618 [12864/60000]
loss: 1.107574 [19264/60000]
loss: 0.986492 [25664/60000]
loss: 1.020281 [32064/60000]
loss: 1.059144 [38464/60000]
loss: 0.999622 [44864/60000]
loss: 1.029244 [51264/60000]
loss: 0.964120 [57664/60000]
Test Error:
Accuracy: 66.0%, Avg loss: 0.977057
Epoch 7
-------------------------------
loss: 1.037883 [ 64/60000]
loss: 1.060785 [ 6464/60000]
loss: 0.861099 [12864/60000]
loss: 1.015254 [19264/60000]
loss: 0.901760 [25664/60000]
loss: 0.929478 [32064/60000]
loss: 0.985907 [38464/60000]
loss: 0.928371 [44864/60000]
loss: 0.951404 [51264/60000]
loss: 0.899121 [57664/60000]
Test Error:
Accuracy: 66.9%, Avg loss: 0.906147
Epoch 8
-------------------------------
loss: 0.952631 [ 64/60000]
loss: 0.994779 [ 6464/60000]
loss: 0.781947 [12864/60000]
loss: 0.949366 [19264/60000]
loss: 0.845234 [25664/60000]
loss: 0.862846 [32064/60000]
loss: 0.935118 [38464/60000]
loss: 0.881270 [44864/60000]
loss: 0.894825 [51264/60000]
loss: 0.852345 [57664/60000]
Test Error:
Accuracy: 68.1%, Avg loss: 0.855028
Epoch 9
-------------------------------
loss: 0.887047 [ 64/60000]
loss: 0.945449 [ 6464/60000]
loss: 0.722958 [12864/60000]
loss: 0.899695 [19264/60000]
loss: 0.804949 [25664/60000]
loss: 0.812118 [32064/60000]
loss: 0.896828 [38464/60000]
loss: 0.848763 [44864/60000]
loss: 0.851984 [51264/60000]
loss: 0.816333 [57664/60000]
Test Error:
Accuracy: 69.3%, Avg loss: 0.816232
Epoch 10
-------------------------------
loss: 0.834691 [ 64/60000]
loss: 0.905861 [ 6464/60000]
loss: 0.677137 [12864/60000]
loss: 0.861224 [19264/60000]
loss: 0.774445 [25664/60000]
loss: 0.772846 [32064/60000]
loss: 0.866035 [38464/60000]
loss: 0.825091 [44864/60000]
loss: 0.818532 [51264/60000]
loss: 0.787082 [57664/60000]
Test Error:
Accuracy: 70.5%, Avg loss: 0.785396
Done!