softmax回归的简洁实现

通过深度学习框架的高级API能够使实现 softmax 回归变得更加容易

In [2]:
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)

Softmax 回归的输出层是一个全连接层

In [3]:
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);

在交叉熵损失函数中传递未归一化的预测,并同时计算softmax及其对数

In [4]:
loss = nn.CrossEntropyLoss()

使用学习率为0.1的小批量随机梯度下降作为优化算法

In [5]:
trainer = torch.optim.SGD(net.parameters(), lr=0.1)

调用 之前 定义的训练函数来训练模型

In [6]:
num_epochs = 10
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
2021-05-05T19:31:47.441249 image/svg+xml Matplotlib v3.3.4, https://matplotlib.org/