Pytorch(7)-优化模型参数
现在我们有了模型和数据,是时候通过优化数据上的参数来训练,验证和测试模型了。训练模型是一个反复的过程;在每次迭代(称为epoch)中,模型都会对输出进行猜测,计算其猜测中的误差(损失),收集误差相对于其参数的导数(如上一节所述)并进行优化这些参数使用梯度下降。有关此过程的更详细的演练,请观看有关3Blue1Brown反向传播的视频。
我们从上一节的数据集,数据加载器 和构建模型中加载代码。
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor()
)
test_data = datasets.FashionMNIST(
root="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(NeuralNetwork, self).__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),
nn.ReLU()
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
model = NeuralNetwork()
超参数是可调整的参数,可让您控制模型优化过程。不同的超参数值可能会影响模型训练和收敛速度(了解有关超参数调整的更多信息)
我们定义以下用于训练的超参数:
epoch-遍历数据集的次数
batchsize-更新参数之前通过网络传播的数据样本的数量
learning rate-每个批次/时期更新模型参数的数量。较小的值会导致学习速度变慢,而较大的值可能会导致训练期间出现无法预测的行为。
learning_rate = 1e-3
batch_size = 64
epochs = 5
设置超参数后,我们便可以使用优化循环来训练和优化模型。优化循环的每次迭代都称为epoch。
每个时期包括两个主要部分:
训练循环-遍历训练数据集并尝试收敛到最佳参数。
验证/测试循环-遍历测试数据集以检查模型性能是否有所改善。
让我们简短地熟悉一下训练循环中使用的一些概念。快来看优化循环的完整实现。
当提供一些训练数据时,我们未经训练的网络很可能无法给出正确的答案。损失函数衡量的是获得的结果与目标值的不相似程度,这是我们在训练过程中要最小化的损失函数。为了计算损失,我们使用给定数据样本的输入进行预测,并将其与真实数据标签值进行比较。
常见的损失函数包括用于回归任务的nn.MSELoss(均方误差)和 用于分类的nn.NLLLoss(负对数似然)。 nn.CrossEntropyLoss结合nn.LogSoftmax和nn.NLLLoss。
我们将模型的输出logits传递给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)
在训练循环中,优化过程分为三个步骤:
我们定义train_loop遍历优化代码的循环,并test_loop根据测试数据评估模型的性能。
def train_loop(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
for batch, (X, y) in enumerate(dataloader):
# Compute prediction and loss
pred = model(X)
loss = loss_fn(pred, y)
# Backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch % 100 == 0:
loss, current = loss.item(), batch * len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
def test_loop(dataloader, model, loss_fn):
size = len(dataloader.dataset)
test_loss, correct = 0, 0
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 /= size
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
我们初始化损失函数和优化器,并将其传递给train_loop和test_loop。随意增加时期数以跟踪模型的改进性能。
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!")
Epoch 1
-------------------------------
loss: 2.307221 [ 0/60000]
loss: 2.301727 [ 6400/60000]
loss: 2.293826 [12800/60000]
loss: 2.281427 [19200/60000]
loss: 2.280947 [25600/60000]
loss: 2.282351 [32000/60000]
loss: 2.265730 [38400/60000]
loss: 2.277632 [44800/60000]
loss: 2.260041 [51200/60000]
loss: 2.213695 [57600/60000]
Test Error:
Accuracy: 37.0%, Avg loss: 0.035116
Epoch 2
-------------------------------
loss: 2.265179 [ 0/60000]
loss: 2.257184 [ 6400/60000]
loss: 2.236612 [12800/60000]
loss: 2.194381 [19200/60000]
loss: 2.216037 [25600/60000]
loss: 2.230935 [32000/60000]
loss: 2.192703 [38400/60000]
loss: 2.228704 [44800/60000]
loss: 2.191200 [51200/60000]
loss: 2.091365 [57600/60000]
Test Error:
Accuracy: 37.9%, Avg loss: 0.033755
Epoch 3
-------------------------------
loss: 2.220718 [ 0/60000]
loss: 2.198574 [ 6400/60000]
loss: 2.166590 [12800/60000]
loss: 2.072836 [19200/60000]
loss: 2.124839 [25600/60000]
loss: 2.173127 [32000/60000]
loss: 2.086044 [38400/60000]
loss: 2.166099 [44800/60000]
loss: 2.101436 [51200/60000]
loss: 1.932705 [57600/60000]
Test Error:
Accuracy: 38.2%, Avg loss: 0.031995
Epoch 4
-------------------------------
loss: 2.165899 [ 0/60000]
loss: 2.122554 [ 6400/60000]
loss: 2.080557 [12800/60000]
loss: 1.923087 [19200/60000]
loss: 2.013725 [25600/60000]
loss: 2.112495 [32000/60000]
loss: 1.962515 [38400/60000]
loss: 2.097708 [44800/60000]
loss: 2.007544 [51200/60000]
loss: 1.777454 [57600/60000]
Test Error:
Accuracy: 39.6%, Avg loss: 0.030214
Epoch 5
-------------------------------
loss: 2.106806 [ 0/60000]
loss: 2.043889 [ 6400/60000]
loss: 1.992362 [12800/60000]
loss: 1.787888 [19200/60000]
loss: 1.905058 [25600/60000]
loss: 2.050201 [32000/60000]
loss: 1.856685 [38400/60000]
loss: 2.031842 [44800/60000]
loss: 1.926060 [51200/60000]
loss: 1.661872 [57600/60000]
Test Error:
Accuracy: 42.0%, Avg loss: 0.028735
Epoch 6
-------------------------------
loss: 2.043752 [ 0/60000]
loss: 1.970670 [ 6400/60000]
loss: 1.907490 [12800/60000]
loss: 1.684472 [19200/60000]
loss: 1.807296 [25600/60000]
loss: 1.988052 [32000/60000]
loss: 1.773258 [38400/60000]
loss: 1.971488 [44800/60000]
loss: 1.857386 [51200/60000]
loss: 1.580941 [57600/60000]
Test Error:
Accuracy: 43.9%, Avg loss: 0.027557
Epoch 7
-------------------------------
loss: 1.982543 [ 0/60000]
loss: 1.909383 [ 6400/60000]
loss: 1.829998 [12800/60000]
loss: 1.604615 [19200/60000]
loss: 1.725794 [25600/60000]
loss: 1.929796 [32000/60000]
loss: 1.707731 [38400/60000]
loss: 1.921700 [44800/60000]
loss: 1.801901 [51200/60000]
loss: 1.520397 [57600/60000]
Test Error:
Accuracy: 45.0%, Avg loss: 0.026625
Epoch 8
-------------------------------
loss: 1.927654 [ 0/60000]
loss: 1.859316 [ 6400/60000]
loss: 1.763596 [12800/60000]
loss: 1.544053 [19200/60000]
loss: 1.661659 [25600/60000]
loss: 1.879479 [32000/60000]
loss: 1.655556 [38400/60000]
loss: 1.883750 [44800/60000]
loss: 1.755927 [51200/60000]
loss: 1.474720 [57600/60000]
Test Error:
Accuracy: 45.7%, Avg loss: 0.025886
Epoch 9
-------------------------------
loss: 1.879600 [ 0/60000]
loss: 1.818393 [ 6400/60000]
loss: 1.707610 [12800/60000]
loss: 1.496390 [19200/60000]
loss: 1.610458 [25600/60000]
loss: 1.838111 [32000/60000]
loss: 1.614197 [38400/60000]
loss: 1.854321 [44800/60000]
loss: 1.718269 [51200/60000]
loss: 1.437551 [57600/60000]
Test Error:
Accuracy: 46.2%, Avg loss: 0.025300
Epoch 10
-------------------------------
loss: 1.837761 [ 0/60000]
loss: 1.785227 [ 6400/60000]
loss: 1.661100 [12800/60000]
loss: 1.458276 [19200/60000]
loss: 1.570582 [25600/60000]
loss: 1.804275 [32000/60000]
loss: 1.581069 [38400/60000]
loss: 1.831521 [44800/60000]
loss: 1.686258 [51200/60000]
loss: 1.407434 [57600/60000]
Test Error:
Accuracy: 46.7%, Avg loss: 0.024828
Done!
优化模型参数