.. _sec_softmax_scratch:
softmax回归的从零开始实现
=========================
就像我们从零开始实现线性回归一样,
我们认为softmax回归也是重要的基础,因此应该知道实现softmax回归的细节。
本节我们将使用刚刚在
:numref:`sec_fashion_mnist`\ 中引入的Fashion-MNIST数据集,
并设置数据迭代器的批量大小为256。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
X = mindspore.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
X.sum(0, keepdims=True), X.sum(1, keepdims=True)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
(Tensor(shape=[1, 3], dtype=Float32, value=
[[ 5.00000000e+00, 7.00000000e+00, 9.00000000e+00]]),
Tensor(shape=[2, 1], dtype=Float32, value=
[[ 6.00000000e+00],
[ 1.50000000e+01]]))
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
X = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
X.sum(0, keepdims=True), X.sum(1, keepdims=True)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
(tensor([[5., 7., 9.]]),
tensor([[ 6.],
[15.]]))
.. raw:: html
.. raw:: html
回想一下,实现softmax由三个步骤组成:
1. 对每个项求幂(使用\ ``exp``\ );
2. 对每一行求和(小批量中每个样本是一行),得到每个样本的规范化常数;
3. 将每一行除以其规范化常数,确保结果的和为1。
在查看代码之前,我们回顾一下这个表达式:
.. math::
\mathrm{softmax}(\mathbf{X})_{ij} = \frac{\exp(\mathbf{X}_{ij})}{\sum_k \exp(\mathbf{X}_{ik})}.
分母或规范化常数,有时也称为\ *配分函数*\ (其对数称为对数-配分函数)。
该名称来自\ `统计物理学 `__\ 中一个模拟粒子群分布的方程。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def softmax(X):
X_exp = d2l.exp(X)
partition = X_exp.sum(1, keepdim=True)
return X_exp / partition # 这里应用了广播机制
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def softmax(X):
X_exp = torch.exp(X)
partition = X_exp.sum(1, keepdim=True)
return X_exp / partition # 这里应用了广播机制
.. raw:: html
.. raw:: html
正如上述代码,对于任何随机输入,我们将每个元素变成一个非负数。
此外,依据概率原理,每行总和为1。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
X = mindspore.tensor(d2l.normal((2, 5), 0, 1))
X_prob = softmax(X)
X_prob, X_prob.sum(1, keepdims=True)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
(Tensor(shape=[2, 5], dtype=Float32, value=
[[ 4.17834967e-01, 7.70997405e-02, 2.44843155e-01, 1.46264493e-01, 1.13957644e-01],
[ 1.00048698e-01, 5.07675558e-02, 3.94639224e-01, 2.21406654e-01, 2.33137891e-01]]),
Tensor(shape=[2, 1], dtype=Float32, value=
[[ 1.00000000e+00],
[ 1.00000000e+00]]))
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
X = torch.normal(0, 1, (2, 5))
X_prob = softmax(X)
X_prob, X_prob.sum(1)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
(tensor([[0.1278, 0.1336, 0.0986, 0.0523, 0.5877],
[0.2781, 0.5381, 0.0989, 0.0390, 0.0459]]),
tensor([1.0000, 1.0000]))
.. raw:: html
.. raw:: html
注意,虽然这在数学上看起来是正确的,但我们在代码实现中有点草率。
矩阵中的非常大或非常小的元素可能造成数值上溢或下溢,但我们没有采取措施来防止这点。
定义模型
--------
定义softmax操作后,我们可以实现softmax回归模型。
下面的代码定义了输入如何通过网络映射到输出。
注意,将数据传递到模型之前,我们使用\ ``reshape``\ 函数将每张原始图像展平为向量。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
class Net(nn.Cell):
def __init__(self, num_inputs, num_outputs):
super().__init__()
self.W = W
self.b = b
def construct(self, X):
return softmax(ops.matmul(X.reshape((-1, self.W.shape[0])), self.W) + self.b)
net = Net(num_inputs, num_outputs)
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def net(X):
return softmax(torch.matmul(X.reshape((-1, W.shape[0])), W) + b)
.. raw:: html
.. raw:: html
定义损失函数
------------
接下来,我们实现 :numref:`sec_softmax`\ 中引入的交叉熵损失函数。
这可能是深度学习中最常见的损失函数,因为目前分类问题的数量远远超过回归问题的数量。
回顾一下,交叉熵采用真实标签的预测概率的负对数似然。
这里我们不使用Python的for循环迭代预测(这往往是低效的),
而是通过一个运算符选择所有元素。
下面,我们创建一个数据样本\ ``y_hat``\ ,其中包含2个样本在3个类别的预测概率,
以及它们对应的标签\ ``y``\ 。
有了\ ``y``\ ,我们知道在第一个样本中,第一类是正确的预测;
而在第二个样本中,第三类是正确的预测。
然后使用\ ``y``\ 作为\ ``y_hat``\ 中概率的索引,
我们选择第一个样本中第一个类的概率和第二个样本中第三个类的概率。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
y = mindspore.tensor([0, 2])
y_hat = mindspore.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y_hat[[0, 1], y]
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
Tensor(shape=[2], dtype=Float32, value= [ 1.00000001e-01, 5.00000000e-01])
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
y = torch.tensor([0, 2])
y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y_hat[[0, 1], y]
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
tensor([0.1000, 0.5000])
.. raw:: html
.. raw:: html
现在我们只需一行代码就可以实现交叉熵损失函数。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def cross_entropy(y_hat, y):
return - d2l.log(y_hat[d2l.arange(len(y_hat)), y])
cross_entropy(y_hat, y)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
Tensor(shape=[2], dtype=Float32, value= [ 2.30258512e+00, 6.93147182e-01])
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def cross_entropy(y_hat, y):
return - torch.log(y_hat[torch.arange(len(y_hat)), y])
cross_entropy(y_hat, y)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
tensor([2.3026, 0.6931])
.. raw:: html
.. raw:: html
分类精度
--------
给定预测概率分布\ ``y_hat``\ ,当我们必须输出硬预测(hard
prediction)时, 我们通常选择预测概率最高的类。
许多应用都要求我们做出选择。如Gmail必须将电子邮件分类为“Primary(主要邮件)”、
“Social(社交邮件)”“Updates(更新邮件)”或“Forums(论坛邮件)”。
Gmail做分类时可能在内部估计概率,但最终它必须在类中选择一个。
当预测与标签分类\ ``y``\ 一致时,即是正确的。
分类精度即正确预测数量与总预测数量之比。
虽然直接优化精度可能很困难(因为精度的计算不可导),
但精度通常是我们最关心的性能衡量标准,我们在训练分类器时几乎总会关注它。
为了计算精度,我们执行以下操作。
首先,如果\ ``y_hat``\ 是矩阵,那么假定第二个维度存储每个类的预测分数。
我们使用\ ``argmax``\ 获得每行中最大元素的索引来获得预测类别。
然后我们将预测类别与真实\ ``y``\ 元素进行比较。
由于等式运算符“\ ``==``\ ”对数据类型很敏感,
因此我们将\ ``y_hat``\ 的数据类型转换为与\ ``y``\ 的数据类型一致。
结果是一个包含0(错)和1(对)的张量。
最后,我们求和会得到正确预测的数量。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def accuracy(y_hat, y): #@save
"""计算预测正确的数量"""
if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
y_hat = d2l.argmax(y_hat, axis=1)
cmp = y_hat.astype(y.dtype) == y
return float(cmp.sum())
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def accuracy(y_hat, y): #@save
"""计算预测正确的数量"""
if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
y_hat = y_hat.argmax(axis=1)
cmp = y_hat.type(y.dtype) == y
return float(cmp.sum())
.. raw:: html
.. raw:: html
我们将继续使用之前定义的变量\ ``y_hat``\ 和\ ``y``\ 分别作为预测的概率分布和标签。
可以看到,第一个样本的预测类别是2(该行的最大元素为0.6,索引为2),这与实际标签0不一致。
第二个样本的预测类别是2(该行的最大元素为0.5,索引为2),这与实际标签2一致。
因此,这两个样本的分类精度率为0.5。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
accuracy(y_hat, y) / len(y)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
0.5
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
accuracy(y_hat, y) / len(y)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
0.5
.. raw:: html
.. raw:: html
同样,对于任意数据迭代器\ ``data_iter``\ 可访问的数据集,
我们可以评估在任意模型\ ``net``\ 的精度。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def evaluate_accuracy(net, data_iter): #@save
"""计算在指定数据集上模型的精度"""
metric = Accumulator(2) # 正确预测数、预测总数
for X, y in data_iter:
metric.add(accuracy(net(X), y), y.numel())
return metric[0] / metric[1]
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def evaluate_accuracy(net, data_iter): #@save
"""计算在指定数据集上模型的精度"""
if isinstance(net, torch.nn.Module):
net.eval() # 将模型设置为评估模式
metric = Accumulator(2) # 正确预测数、预测总数
with torch.no_grad():
for X, y in data_iter:
metric.add(accuracy(net(X), y), y.numel())
return metric[0] / metric[1]
.. raw:: html
.. raw:: html
这里定义一个实用程序类\ ``Accumulator``\ ,用于对多个变量进行累加。
在上面的\ ``evaluate_accuracy``\ 函数中,
我们在\ ``Accumulator``\ 实例中创建了2个变量,
分别用于存储正确预测的数量和预测的总数量。
当我们遍历数据集时,两者都将随着时间的推移而累加。
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
class Accumulator: #@save
"""在n个变量上累加"""
def __init__(self, n):
self.data = [0.0] * n
def add(self, *args):
self.data = [a + float(b) for a, b in zip(self.data, args)]
def reset(self):
self.data = [0.0] * len(self.data)
def __getitem__(self, idx):
return self.data[idx]
由于我们使用随机权重初始化\ ``net``\ 模型,
因此该模型的精度应接近于随机猜测。 例如在有10个类别情况下的精度为0.1。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
evaluate_accuracy(net, test_iter)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
0.0632
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
evaluate_accuracy(net, test_iter)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
0.0825
.. raw:: html
.. raw:: html
训练
----
在我们看过 :numref:`sec_linear_scratch`\ 中的线性回归实现,
softmax回归的训练过程代码应该看起来非常眼熟。
在这里,我们重构训练过程的实现以使其可重复使用。
首先,我们定义一个函数来训练一个迭代周期。
请注意,\ ``updater``\ 是更新模型参数的常用函数,它接受批量大小作为参数。
它可以是\ ``d2l.sgd``\ 函数,也可以是框架的内置优化函数。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def train_epoch_ch3(net, train_iter, loss, updater): #@save
"""训练模型一个迭代周期(定义见第3章)。"""
# 定义前向网络
def forward_fn(x, y):
y_hat = net(x)
if isinstance(updater, nn.Optimizer):
l = loss(y_hat, y).mean()
factor = train_iter.get_batch_size()
else:
l = loss(y_hat, y).sum()
factor = 1
return l, y_hat, factor
grad_fn = mindspore.value_and_grad(forward_fn, grad_position=None, weights=updater.parameters, has_aux=True)
metric = d2l.Accumulator(3)
for X, y in train_iter:
(l, y_hat, factor), grads = grad_fn(X, y)
updater(grads)
metric.add(float(l.asnumpy()), accuracy(y_hat, y), y.size)
return metric[0] / metric[2] * factor, metric[1] / metric[2]
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def train_epoch_ch3(net, train_iter, loss, updater): #@save
"""训练模型一个迭代周期(定义见第3章)"""
# 将模型设置为训练模式
if isinstance(net, torch.nn.Module):
net.train()
# 训练损失总和、训练准确度总和、样本数
metric = Accumulator(3)
for X, y in train_iter:
# 计算梯度并更新参数
y_hat = net(X)
l = loss(y_hat, y)
if isinstance(updater, torch.optim.Optimizer):
# 使用PyTorch内置的优化器和损失函数
updater.zero_grad()
l.mean().backward()
updater.step()
else:
# 使用定制的优化器和损失函数
l.sum().backward()
updater(X.shape[0])
metric.add(float(l.sum()), accuracy(y_hat, y), y.numel())
# 返回训练损失和训练精度
return metric[0] / metric[2], metric[1] / metric[2]
.. raw:: html
.. raw:: html
在展示训练函数的实现之前,我们定义一个在动画中绘制数据的实用程序类\ ``Animator``\ ,
它能够简化本书其余部分的代码。
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
class Animator: #@save
"""在动画中绘制数据"""
def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
figsize=(3.5, 2.5)):
# 增量地绘制多条线
if legend is None:
legend = []
d2l.use_svg_display()
self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
if nrows * ncols == 1:
self.axes = [self.axes, ]
# 使用lambda函数捕获参数
self.config_axes = lambda: d2l.set_axes(
self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
self.X, self.Y, self.fmts = None, None, fmts
def add(self, x, y):
# 向图表中添加多个数据点
if not hasattr(y, "__len__"):
y = [y]
n = len(y)
if not hasattr(x, "__len__"):
x = [x] * n
if not self.X:
self.X = [[] for _ in range(n)]
if not self.Y:
self.Y = [[] for _ in range(n)]
for i, (a, b) in enumerate(zip(x, y)):
if a is not None and b is not None:
self.X[i].append(a)
self.Y[i].append(b)
self.axes[0].cla()
for x, y, fmt in zip(self.X, self.Y, self.fmts):
self.axes[0].plot(x, y, fmt)
self.config_axes()
display.display(self.fig)
display.clear_output(wait=True)
接下来我们实现一个训练函数,
它会在\ ``train_iter``\ 访问到的训练数据集上训练一个模型\ ``net``\ 。
该训练函数将会运行多个迭代周期(由\ ``num_epochs``\ 指定)。
在每个迭代周期结束时,利用\ ``test_iter``\ 访问到的测试数据集对模型进行评估。
我们将利用\ ``Animator``\ 类来可视化训练进度。
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater): #@save
"""训练模型(定义见第3章)"""
animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],
legend=['train loss', 'train acc', 'test acc'])
for epoch in range(num_epochs):
train_metrics = train_epoch_ch3(net, train_iter, loss, updater)
test_acc = evaluate_accuracy(net, test_iter)
animator.add(epoch + 1, train_metrics + (test_acc,))
train_loss, train_acc = train_metrics
assert train_loss < 0.5, train_loss
assert train_acc <= 1 and train_acc > 0.7, train_acc
assert test_acc <= 1 and test_acc > 0.7, test_acc
作为一个从零开始的实现,我们使用
:numref:`sec_linear_scratch`\ 中定义的
小批量随机梯度下降来优化模型的损失函数,设置学习率为0.1。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
lr = 0.1
updater = d2l.SGD(lr, batch_size, net.trainable_params())
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
lr = 0.1
def updater(batch_size):
return d2l.sgd([W, b], lr, batch_size)
.. raw:: html
.. raw:: html
现在,我们训练模型10个迭代周期。
请注意,迭代周期(\ ``num_epochs``\ )和学习率(\ ``lr``\ )都是可调节的超参数。
通过更改它们的值,我们可以提高模型的分类精度。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
num_epochs = 10
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
.. figure:: output_softmax-regression-scratch_a48321_135_0.png
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
num_epochs = 10
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
.. figure:: output_softmax-regression-scratch_a48321_138_0.svg
.. raw:: html
.. raw:: html
预测
----
现在训练已经完成,我们的模型已经准备好对图像进行分类预测。
给定一系列图像,我们将比较它们的实际标签(文本输出的第一行)和模型预测(文本输出的第二行)。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def predict_ch3(net, test_iter, n=6):
"""预测标签(定义见第3章)。"""
for X, y in test_iter:
break
trues = d2l.get_fashion_mnist_labels(y.asnumpy())
preds = d2l.get_fashion_mnist_labels(net(X).argmax(axis=1).asnumpy())
titles = [true +'\n' + pred for true, pred in zip(trues, preds)]
d2l.show_images(
X[0:n].reshape((n, 28, 28)), 1, n, titles=titles[0:n])
predict_ch3(net, test_iter)
.. figure:: output_softmax-regression-scratch_a48321_144_0.png
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def predict_ch3(net, test_iter, n=6): #@save
"""预测标签(定义见第3章)"""
for X, y in test_iter:
break
trues = d2l.get_fashion_mnist_labels(y)
preds = d2l.get_fashion_mnist_labels(net(X).argmax(axis=1))
titles = [true +'\n' + pred for true, pred in zip(trues, preds)]
d2l.show_images(
X[0:n].reshape((n, 28, 28)), 1, n, titles=titles[0:n])
predict_ch3(net, test_iter)
.. figure:: output_softmax-regression-scratch_a48321_147_0.svg
.. raw:: html
.. raw:: html
小结
----
- 借助softmax回归,我们可以训练多分类的模型。
- 训练softmax回归循环模型与训练线性回归模型非常相似:先读取数据,再定义模型和损失函数,然后使用优化算法训练模型。大多数常见的深度学习模型都有类似的训练过程。
练习
----
1. 本节直接实现了基于数学定义softmax运算的\ ``softmax``\ 函数。这可能会导致什么问题?提示:尝试计算\ :math:`\exp(50)`\ 的大小。
2. 本节中的函数\ ``cross_entropy``\ 是根据交叉熵损失函数的定义实现的。它可能有什么问题?提示:考虑对数的定义域。
3. 请想一个解决方案来解决上述两个问题。
4. 返回概率最大的分类标签总是最优解吗?例如,医疗诊断场景下可以这样做吗?
5. 假设我们使用softmax回归来预测下一个单词,可选取的单词数目过多可能会带来哪些问题?
.. raw:: html
.. raw:: html
`讨论 `__
.. raw:: html
.. raw:: html
`讨论 `__
.. raw:: html
.. raw:: html