动手学深度学习(zh-v2.d2l.ai)
SoftMax也是单层的网络,其思路是将多类的输出转为概率表示,每类的输出在
0
−
1
0-1
0−1之间,且和为1.
数学表达为
y
^
=
s
o
f
t
m
a
x
(
o
)
其中
y
^
j
=
exp
(
o
j
)
∑
k
exp
(
o
k
)
\hat{\mathbf{y}} = \mathrm{softmax}(\mathbf{o})\quad \text{其中}\quad \hat{y}_j = \frac{\exp(o_j)}{\sum_k \exp(o_k)}
y^=softmax(o)其中y^j=∑kexp(ok)exp(oj)
import torch
import d2l.torch as d2l
import matplotlib.pyplot as plt
数据
采用fashion_mnist数据集,10分类。
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
定义模型
模型在这里使用简单的铺平加线性层。
使用apply
方法进行参数初始化
net = torch.nn.Sequential(torch.nn.Flatten(), torch.nn.Linear(784, 10))
def init_weights(m):
if type(m) == torch.nn.Linear:
torch.nn.init.normal_(m.weight, mean=0, std=0.01)
m.bias.data.fill_(0.01)
net.apply(init_weights)
loss = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
训练
训练采用D2L库中函数
num_epochs = 10
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, optimizer)
plt.show()
训练结果: