现在我们有了模型和数据,是时候通过优化数据上的参数来训练、验证和测试我们的模型了。训练模型是一个迭代过程;在每次迭代中,模型都会对输出进行猜测,计算其猜测中的误差(损失),收集相对于其参数的导数的误差(如我们在上一节中看到的),并使用梯度下降优化这些参数。有关此过程的更详细演练,请观看3Blue1Brown 的反向传播有关视频。
%matplotlib inline
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().__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()
超参数是可调整的参数,可让您控制模型优化过程。不同的超参数值会影响模型训练和收敛速度(阅读有关超参数调整的更多信息)
我们定义以下训练超参数:
learning_rate = 1e-3
batch_size = 64
epochs = 5
一旦我们设置了超参数,我们就可以使用优化循环来训练和优化我们的模型。优化循环的每次迭代称为一个epoch。
每个 epoch由两个主要部分组成:
让我们简单熟悉一下训练循环中使用的一些概念。向前跳转查看优化循环的完整实现。
当提供一些训练数据时,我们未经训练的网络可能不会给出正确的答案。损失函数衡量的是得到的结果与目标值的不相似程度,它是我们在训练时想要最小化的损失函数。为了计算损失,我们使用给定数据样本的输入进行预测,并将其与真实数据标签值进行比较。
常见的损失函数包括:
nn.LogSoftmax
和nn.NLLLoss
。我们将模型的输出 logits 传递给nn.CrossEntropyLoss
,这将标准化 logits 并计算预测误差。
# Initialize the loss function
loss_fn = nn.CrossEntropyLoss()
优化是调整模型参数以减少每个训练步骤中模型误差的过程。Optimization algorithms定义了如何执行此过程(在本例中我们使用 Stochastic Gradient Descent 随机梯度下降)。所有优化逻辑都封装在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)
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)
num_batches = len(dataloader)
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 /= 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(train_dataloader, model, loss_fn)
print("Done!")
Epoch 1
----------
loss: 2.301911 0/60000
loss: 2.292816 6400/60000
loss: 2.287881 12800/60000
loss: 2.287051 19200/60000
loss: 2.255377 25600/60000
loss: 2.253076 32000/60000
loss: 2.260443 38400/60000
loss: 2.247314 44800/60000
loss: 2.241305 51200/60000
loss: 2.210870 57600/60000
Test Error:
Accuracy: 36.2%, Avg loss: 2.231190
Epoch 2
----------
loss: 2.239081 0/60000
loss: 2.230416 6400/60000
loss: 2.228071 12800/60000
loss: 2.236214 19200/60000
loss: 2.153478 25600/60000
loss: 2.158298 32000/60000
loss: 2.178127 38400/60000
loss: 2.160697 44800/60000
loss: 2.154827 51200/60000
loss: 2.075521 57600/60000
Test Error:
Accuracy: 36.6%, Avg loss: 2.133443
Epoch 3
----------
loss: 2.146330 0/60000
loss: 2.128829 6400/60000
loss: 2.128925 12800/60000
loss: 2.157317 19200/60000
loss: 1.988493 25600/60000
loss: 2.024168 32000/60000
loss: 2.047211 38400/60000
loss: 2.034990 44800/60000
loss: 2.041876 51200/60000
loss: 1.895464 57600/60000
Test Error:
Accuracy: 36.6%, Avg loss: 2.005870
Epoch 4
----------
loss: 2.021032 0/60000
loss: 1.997008 6400/60000
loss: 2.011971 12800/60000
loss: 2.068262 19200/60000
loss: 1.803704 25600/60000
loss: 1.892051 32000/60000
loss: 1.908679 38400/60000
loss: 1.918824 44800/60000
loss: 1.930000 51200/60000
loss: 1.739982 57600/60000
Test Error:
Accuracy: 36.9%, Avg loss: 1.891897
Epoch 5
----------
loss: 1.902151 0/60000
loss: 1.882296 6400/60000
loss: 1.913334 12800/60000
loss: 1.990550 19200/60000
loss: 1.657651 25600/60000
loss: 1.794650 32000/60000
loss: 1.795805 38400/60000
loss: 1.831202 44800/60000
loss: 1.833831 51200/60000
loss: 1.629697 57600/60000
Test Error:
Accuracy: 37.4%, Avg loss: 1.799645
Epoch 6
----------
loss: 1.802362 0/60000
loss: 1.789743 6400/60000
loss: 1.826163 12800/60000
loss: 1.926406 19200/60000
loss: 1.548903 25600/60000
loss: 1.718380 32000/60000
loss: 1.711547 38400/60000
loss: 1.762800 44800/60000
loss: 1.758859 51200/60000
loss: 1.552383 57600/60000
Test Error:
Accuracy: 38.0%, Avg loss: 1.727585
Epoch 7
----------
loss: 1.725688 0/60000
loss: 1.717472 6400/60000
loss: 1.751318 12800/60000
loss: 1.876573 19200/60000
loss: 1.472371 25600/60000
loss: 1.662801 32000/60000
loss: 1.653247 38400/60000
loss: 1.712392 44800/60000
loss: 1.704763 51200/60000
loss: 1.500154 57600/60000
Test Error:
Accuracy: 39.0%, Avg loss: 1.674637
Epoch 8
----------
loss: 1.668191 0/60000
loss: 1.661058 6400/60000
loss: 1.691381 12800/60000
loss: 1.841454 19200/60000
loss: 1.421006 25600/60000
loss: 1.622762 32000/60000
loss: 1.614252 38400/60000
loss: 1.674310 44800/60000
loss: 1.665184 51200/60000
loss: 1.463472 57600/60000
Test Error:
Accuracy: 40.0%, Avg loss: 1.635488
Epoch 9
----------
loss: 1.624500 0/60000
loss: 1.616901 6400/60000
loss: 1.642325 12800/60000
loss: 1.813562 19200/60000
loss: 1.385301 25600/60000
loss: 1.592487 32000/60000
loss: 1.585913 38400/60000
loss: 1.645142 44800/60000
loss: 1.634234 51200/60000
loss: 1.435932 57600/60000
Test Error:
Accuracy: 41.0%, Avg loss: 1.604748
Epoch 10
----------
loss: 1.588852 0/60000
loss: 1.580336 6400/60000
loss: 1.601489 12800/60000
loss: 1.791107 19200/60000
loss: 1.359017 25600/60000
loss: 1.568917 32000/60000
loss: 1.563138 38400/60000
loss: 1.620597 44800/60000
loss: 1.591901 51200/60000
loss: 1.372489 57600/60000
Test Error:
Accuracy: 42.0%, Avg loss: 1.533991
Done!
您可能已经注意到该模型最初不是很好(没关系!)。尝试运行循环更多的 epochs
或将 learning_rate
调整为更大的数字。也可能是这样的情况,我们选择的模型配置可能不是解决此类问题的最佳配置(事实并非如此)。后续课程将更深入地研究适用于视觉问题的模型形状。
当您对模型的性能感到满意时,可以使用 torch.save
保存它。 PyTorch 模型将学习到的参数存储在internal state dictionar内部状态字典中,称为 state_dict
。这些可以通过 torch.save
方法保存:
torch.save(model.state_dict(), "data/model.pth")
print("Save PyToch Model State to model.pth")
Save PyToch Model State to model.pth