import torch
from torch import nn
from d2l import torch as d2l
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
7.1 初始化模型参数
softmax回归的输出层是一个全连接层。只需在Sequential中添加一个带有10个输出的全连接层。 我们仍然以均值0和标准差0.01随机初始化权重。
在这里Sequential并不是必要的, 但它是实现深度模型的基础。
# PyTorch不会隐式地调整输入的形状。因此,
# 我们在线性层前定义了展平层(flatten),来调整网络输入的形状
net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))
def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01)
net.apply(init_weights);
7.2 定义交叉熵损失函数
loss = nn.CrossEntropyLoss(reduction='none')
其中 reduction 参数用于控制输出损失的形式。
当 reduction=‘none’ 时,函数会输出一个形状为 (batch_size, num_classes) 的矩阵,表示每个样本的每个类别的损失。
当 reduction=‘sum’ 时,函数会对矩阵求和,输出一个标量,表示所有样本的损失之和。
当 reduction=‘elementwise_mean’ 时,函数会对矩阵求平均,输出一个标量,表示所有样本的平均损失。
7.3 优化算法
使用学习率为0.1的小批量随机梯度下降作为优化算法,同时也体现了优化器的通用性。
trainer = torch.optim.SGD(net.parameters(), lr=0.1)
7.4 训练
接下来调用 上一小节中定义的训练函数来训练模型
num_epochs = 10
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
和以前一样,这个算法使结果收敛到一个相当高的精度,而且这次的代码比之前更精简。