代码:
# 导入包,引入Fashion-MNIST数据集
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)
"""
初始化化模型参数:
1、原始图像为28×28,展平为784的向量
2、数据集有10个类别,输出维度为10
3、权重为784×10的矩阵,偏置为1×10的向量
4、使用正态分布N(0, 0.01)来初始化权重w,偏置b初始化为0
"""
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)
"""
定义softmax操作:softmax(X)=exp(X)/∑(exp(X))
1、对X做指数操作,为分子
2、对指数操作的X求和作为分母,保持求和X的维度不变
3、相除得到softmax(X)
"""
def softmax(X):
X_exp = torch.exp(X)
partition = X_exp.sum(1, keepdim=True)
return X_exp / partition # 这里应用了广播机制
"""
定义模型:softmax(W*X + b)
1、数据传递到模型之前,将原始图像展平为向量
2、X.reshape((-1, W.shape[0]):行不管,将列转换为权重W相同的行数
"""
def net(X):
return softmax(torch.matmul(X.reshape(-1, W.shape[0]), W)+b)
"""
实现交叉熵损失函数:-∑ylog(y')
1、y'是y_hat预测值,y是y真实值
2、range(len(y')):预测值y'中元素的集合
3、预测值y'与真实值y做交叉熵操作
"""
def cross_entropy(y_hat, y):
return - torch.log(y_hat[range(len(y_hat)), y])
cross_entropy(y_hat, y)
"""
计算预测正确的数量:
1、y_hat是矩阵,第二个维度储存每个类的预测分数(y_hat.shape[1]),使用argmax最大元素的索引来获取类别
2、将预测类别与真实y元素进行比较,通过"=="输出0(错误)或者1(正确)
3、将正确预测的数量相加
"""
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.type(y.dtype).sum())
"""
计算在指定数据集上模型的精度:
1、将模型设置为评估模式
2、将正确预测数和预测总数进行储存
3、精度为:正确预测数/总预测数
"""
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]
"""
定义一个实用类Accumulator,对n个变量进行累加:
1、初始化根据传入n的大小来创建空间,全部初始化为0
2、把原来类中对应位置的data与新传入的args相加(float格式),从而达到累加效果
3、重新设置空间大小并初始化
4、实现类似数组的取操作
"""
class Accumulator: #@save
"""在n个变量上累加"""
def __init__(self, n):
self.data = [0.0] * n
# zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
# 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
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]
"""
训练模型一个迭代周期:
1、将模型设置为训练模式
2、设置Accumulator类对3个变量进行储存:训练损失总和、训练准确度总和、样本数
3、在训练集中计算损失loss及其梯度,使用内置优化器或者自定义优化器进行更新
4、对Accumulator类中储存的3个变量进行相加
5、返回训练损失(损失/样本数)和训练精度(训练精确的总和/样本数)
"""
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.zeros_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]
"""
定义在动画中绘制数据的程序类Animator
"""
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)
"""
训练模型:
1、在train_iter访问的数据集上训练一个模型net
2、训练函数运行多个迭代周期
3、每个迭代周期结束,利用test_acc访问的测试集数据进行评估
4、利用Animator类来可视化训练进度
"""
def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater): #@save
"""训练模型(定义见第三章)"""
# x轴为'epoch',定义域为[1,迭代周期];y轴为[0.3, 0.9];添加图例:train loss, train acc, test acc
animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],
legend=['train loss', 'trian acc', 'test acc'])
for epoch in range(num_epochs):
# train_metrics储存的是训练损失和训练精度
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
"""
定义优化器:
1、使用d2l库中的小批量随机梯度下降来优化模型的损失函数
"""
lr = 0.1
def updater(batch_size):
return d2l.sgd([W, b], lr, batch_size)
"""
训练模型迭代10个周期:
1、可视化train loss, train acc, test acc
"""
num_epochs = 10
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
部分代码解释:
import matplotlib.pyplot as plt
# 创建一个2x2的坐标轴数组
fig, axs = plt.subplots(nrows=2, ncols=2)
print(type(axs)) # 输出:<class 'numpy.ndarray'>
print(axs)
print(axs[0 ])
# 创建一个单独的坐标轴
fig, ax = plt.subplots(nrows=1, ncols=1)
print(type(ax)) # 输出:<class 'matplotlib.axes._subplots.AxesSubplot'>
print(ax)
hasattr(object, name):
在Python中,hasattr(object, name) 函数用于检查对象是否包含名为 name 的属性,并返回一个布尔值(True 或 False)。在你给出的代码片段 if not hasattr(y, "__len__"): 中,这个条件用于检查变量 y 是否没有 __len__ 属性。
n = 3
X = [[] for _ in range(n)]
Y = [[] for _ in range(n)]
print(X)
print(Y)
for i in range(n): # 假设n是已知的,且已经足够大以包含至少一个元素
a = 1 # a的赋值逻辑
b = 2 # b的赋值逻辑
X[i].append(a)
Y[i].append(b)
print(X)
print(Y)
输出结果:
[[], [], []]
[[], [], []]
[[1], [1], [1]]
[[2], [2], [2]]