我们在“线性回归的简洁实现”一节中已经了解了使用PyTorch实现模型的便利。下面,让我们再次使用PyTorch来实现一个softmax回归模型。首先导入所需的包或模块。
%matplotlib inline
import d2ltorch as d2lt
import torch
from torch import nn, optim
我们仍然使用Fashion-MNIST数据集和上一节中设置的批量大小。
root = '~/dataset/'
batch_size = 256
train_iter, test_iter = d2lt.load_data_fashion_mnist(root, batch_size=batch_size)
在“softmax回归”一节中提到,softmax回归的输出层是一个全连接层。因此,我们添加一个输出个数为10的全连接层。我们使用均值为0、标准差为0.01的正态分布随机初始化模型的权重参数。
这里我们提前使用 “4.2. 模型参数的访问、初始化和共享” 一节中定义的初始化方法 `params_init(model, init, kwargs)`
class MySoftMax(nn.Module):
def __init__(self, **kwargs):
super(MySoftMax, self).__init__(**kwargs)
self.linear = nn.Linear(28 * 28, 10)
def forward(self, x):
x = x.reshape(-1, 28 * 28)
return self.linear(x)
net = MySoftMax()
d2lt.params_init(model=net, init=nn.init.normal_, std=0.01)
如果做了上一节的练习,那么你可能意识到了分开定义softmax运算和交叉熵损失函数可能会造成数值不稳定。因此,PyTorch提供了一个包括softmax运算和交叉熵损失计算的函数。它的数值稳定性更好。
loss = nn.CrossEntropyLoss()
我们使用学习率为0.1的小批量随机梯度下降作为优化算法。
optimizer = optim.SGD(net.parameters(), lr=0.1)
接下来,我们使用上一节中定义的训练函数来训练模型。
num_epochs = 5
d2lt.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)
epoch 1, loss 0.0031, train acc 0.751, test acc 0.775 epoch 2, loss 0.0022, train acc 0.813, test acc 0.795 epoch 3, loss 0.0021, train acc 0.825, test acc 0.810 epoch 4, loss 0.0020, train acc 0.832, test acc 0.811 epoch 5, loss 0.0019, train acc 0.836, test acc 0.823