import torch
from IPython import display
from d2l import torch as d2l
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
import torch
:导入 PyTorch 库,用于张量操作、模型定义和训练等。
display
模块: 这个模块通常用于在 Jupyter Notebook 中显示图片、图表等。
d2l
(Deep Learning Book)库中导入 PyTorch 相关的功能,并将其别名设置为 d2l
。这个库提供了许多深度学习相关的实用工具和数据集加载函数。
batch_size
变量,设置每个训练批次的样本数量为多少。批量大小是训练过程中每次更新模型参数时使用的样本数量。
load_data_fashion_mnist
函数加载 Fashion MNIST 数据集,并根据给定的 batch_size
进行分批次处理。这个函数返回两个迭代器:
-
train_iter
:训练集的数据迭代器,用于遍历训练样本。 -
test_iter
:测试集的数据迭代器,用于遍历测试样本。
Fashion MNIST
是一个用于图像分类的标准数据集,它包含了 10 类服饰图像,用于训练和评估模型。
1、将展平每个图像,把它们看作长度为784的向量。 因为我们的数据集有10个类别,所以网络输出维度为10
num_inputs = 784
num_outputs = 10
W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True)
b = torch.zeros(num_outputs, requires_grad=True)
torch.normal(0, 0.01, size=(num_inputs, num_outputs))
:从均值为 0
、标准差为 0.01
的正态分布中生成一个张量。这个张量的形状为 (num_inputs, num_outputs)
,即 784x10
,表示权重矩阵。
requires_grad=True
:表示需要计算梯度,以便进行反向传播和优化。
torch.zeros(num_outputs)`:创建一个全为零的张量,形状为 `(num_outputs,)
2、给定一个矩阵X
,我们可以对所有元素求和
X = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
X.sum(0, keepdim=True), X.sum(1, keepdim=True)
X.sum(0)
:计算沿第 0 维(即行方向)的和。结果将是每列的和。
keepdim=True
:保持原有的维度,使得结果仍然是一个二维张量,形状为 (1, 3)
,而不是一维的 (3,)
。
X.sum(1)
:计算沿第 1 维(即列方向)的和。结果将是每行的和
3、
def softmax(X):
X_exp = torch.exp(X)
partition = X_exp.sum(1, keepdim=True)
return X_exp / partition
Softmax 是一种常用于多分类问题的激活函数,它将一个实数向量转换为一个概率分布
torch.exp(X)
:对 X
张量的每个元素计算指数函数(e^x
),生成一个新的张量
X_exp.sum(1, keepdim=True)
:沿着第 1 维(即每行)计算 X_exp
张量的和,得到每一行的所有指数值之和。
keepdim=True
:保持原有的维度,使得结果的形状为 (batch_size, 1)
,这样可以方便地用于广播(broadcasting),确保分母的形状与 X_exp
进行逐元素除法时能够匹配。
4、我们将每个元素变成一个非负数。 此外,依据概率原理,每行总和为1
X = torch.normal(0, 1, (2, 5))
X_prob = softmax(X)
X_prob, X_prob.sum(1)
torch.normal(0, 1, (2, 5))
:生成一个形状为 (2, 5)
的张量 X
,其中的元素来自均值为 0
、标准差为 1
的正态分布。
softmax(X)
:对 X
进行 Softmax 变换,计算每个元素的 Softmax 概率。Softmax 函数将张量 X
的每一行转换为一个概率分布,使得每一行的元素和为 1
。
X.reshape((-1, W.shape[0]))
:将输入张量 X
重塑为一个新的形状。-1
表示自动推断维度的大小,使得新形状的第一个维度与 W.shape[0]
对应。
W.shape[0]
是权重矩阵 W
的行数,通常等于输入特征的数量。在这个上下文中,它表示每个样本的特征数。
5、实现softmax回归模型
def net(X):
return softmax(torch.matmul(X.reshape((-1, W.shape[0])), W) + b)
torch.matmul
:执行矩阵乘法操作。这里的 X.reshape((-1, W.shape[0]))
是形状为 (batch_size, 784)
的张量,W
是形状为 (784, 10)
的权重矩阵。
乘法的结果是一个形状为 (batch_size, 10)
的张量,每行表示每个样本在各个类别上的未归一化的预测分数(logits)。
6、 创建一个数据样本y_hat
,其中包含2个样本在3个类别的预测概率, 以及它们对应的标签y
。 使用y
作为y_hat
中概率的索引
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]
y_hat
是一个二维张量,表示每个样本对每个类别的预测概率。形状为 (2, 3)
,即 2 个样本,每个样本对 3 个类别的概率预测。
y_hat[[0, 1], y]
:使用高级索引来选择 y_hat
中的元素。这里的 y
张量作为列索引,[0, 1]
作为行索引。
7、实现交叉熵损失函数
交叉熵损失是评估模型预测概率与实际标签之间差距的一种标准方法
def cross_entropy(y_hat, y):
return - torch.log(y_hat[range(len(y_hat)), y])
cross_entropy(y_hat, y)
torch.log
:对选择的预测概率取自然对数(log)。由于交叉熵损失是基于对数概率的负对数计算的,所以取负值。
8、将预测类别与真实y
元素进行比较
def accuracy(y_hat, y):
"""计算预测正确的数量"""
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.type(y.dtype).sum())
accuracy(y_hat, y) / len(y)
y_hat.argmax(axis=1)
:对 y_hat
的每一行找到概率最高的类别索引(即预测的类别),将其转换为一维张量,每个元素表示每个样本的预测类别。
9、我们可以评估在任意模型net
的精度
def evaluate_accuracy(net, data_iter):
"""计算在指定数据集上模型的精度"""
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]
isinstance(net, torch.nn.Module)
:检查 net
是否是一个 PyTorch 模型(torch.nn.Module
的实例)。
net.eval()
:将模型设置为评估模式。评估模式会禁用训练时的某些特性(例如 dropout 和 batch normalization),以确保模型在评估阶段的行为是确定的。
with torch.no_grad()
:禁用梯度计算,以减少内存消耗和计算开销。这在评估和推断时是常见的做法,因为我们不需要更新模型参数。
metric.add(accuracy(net(X), y), y.numel())
:将当前批次的准确预测数量和样本总数累积到 metric
中。
metric[0]
:累积的正确预测数量。
metric[1]
:累积的样本总数量。
metric[0] / metric[1]
:计算并返回准确率,即正确预测数量除以样本总数。
10、Accumulator
实例中创建了2个变量, 分别用于存储正确预测的数量和预测的总数量
class Accumulator:
"""在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]
evaluate_accuracy(net, test_iter)
假设 Accumulator
是一个用于累积计数的简单类
11、Softmax回归的训练
def train_epoch_ch3(net, train_iter, loss, updater):
"""训练模型一个迭代周期(定义见第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):
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]
一个训练周期的训练过程:包括前向传播、计算损失、反向传播以及参数更新
net.train()
:将模型设置为训练模式。这会启用诸如 dropout 和 batch normalization 的训练特性。
如果 updater
是一个 PyTorch 优化器(如 torch.optim.SGD
):
-
updater.zero_grad()
:清零优化器中的梯度。 -
l.mean().backward()
:对平均损失计算梯度。 -
updater.step()
:更新模型参数。
如果 updater
不是 PyTorch 优化器(通常是自定义的学习率更新器):
-
l.sum().backward()
:对损失总和计算梯度。 -
updater(X.shape[0])
:调用自定义的更新器进行参数更新。
12、定义一个在动画中绘制数据的实用程序类
class Animator:
"""在动画中绘制数据"""
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, ]
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)
Animator
类用于在训练过程中可视化数据的变化,它会动态地绘制图形并更新。这个类在机器学习实验中非常有用,可以实时跟踪模型的训练过程、损失函数值或其他指标。
nn.Sequential
:一个顺序容器,按顺序将模块(层)应用于输入数据。
nn.Flatten()
:将输入数据展平。假设输入数据是一个形状为 (batch_size, 28, 28)
的张量,Flatten
将其转换为形状为 (batch_size, 784)
的张量,其中 784 是 28x28 的乘积。
nn.Linear(784, 10)
:一个全连接层,将输入的 784 维数据映射到 10 维输出。这里假设有 10 个类别,因此输出的维度是 10。
apply
方法会递归地遍历网络中的所有子模块,并对每个子模块调用 init_weights
函数。
reduction
参数
-
reduction='none'
:指定损失的减少方式。reduction
参数可以取以下几种值:-
'none'
:返回每个样本的损失值,不进行任何汇总。 -
'mean'
:计算所有样本损失的均值。 -
'sum'
:计算所有样本损失的总和。
-
-
在这种情况下,
reduction='none'
表示损失函数不会对每个样本的损失进行汇总,而是返回一个与输入数据的形状相同的张量,其中包含每个样本的损失值。这对于需要对每个样本的损失进行进一步处理(例如加权平均或选择性优化)时特别有用。
torch.optim.SGD
:这是 PyTorch 提供的随机梯度下降(SGD)优化器。SGD 是一种经典的优化算法,用于在每次迭代中根据梯度更新模型参数。
net.parameters()
:获取模型 net
中所有可训练的参数。parameters()
方法返回一个生成器,生成模型中的所有参数张量(例如权重和偏置)。
lr=0.1
:设置学习率为 0.1。学习率是一个超参数,用于控制每次参数更新的步长。较高的学习率可能导致训练不稳定,而较低的学习率可能导致训练过程过慢。
优化器的作用
-
更新参数:
torch.optim.SGD
通过计算梯度并按指定的学习率更新参数,来最小化损失函数。 -
训练过程中的迭代:在每个训练周期(epoch),优化器会对模型的所有参数进行更新,以优化模型性能。
13、训练函数
def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):
"""训练模型(定义见第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
14、小批量随机梯度下降来优化模型的损失函数
lr = 0.1
def updater(batch_size):
return d2l.sgd([W, b], lr, batch_size)
15、训练模型10个迭代周期
num_epochs = 10
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
16、对图像进行分类预测
def predict_ch3(net, test_iter, n=6):
"""预测标签(定义见第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)