代码如下
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)
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)
x = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
#0代表对列求和, 1代表对行求和, keepdim代表是否保持维度不变
x.sum(0, keepdim=True), x.sum(1, keepdim=True)
#将矩阵的各个元素的值转为概率的分布
def softmax(x):
x_exp = torch.exp(x)#对矩阵的每个元素求指数
partition = x_exp.sum(1, keepdim=True)#矩阵的每个行的元素相加
return x_exp / partition #求指数后的元素与每行元素的和相除, 得到概率
lr = 0.1
def updater(batch_size):
return d2l.sgd([w, b], lr, batch_size)
def net(x):
#因为x时每个元素的图像代表是28*28的矩阵, 所以需要给reshape成[1,784]以满足矩阵乘法法则,本例得到1行10列的结果
#shape[0]得到的是矩阵的行数
return softmax(torch.matmul(x.reshape((-1, w.shape[0])), w) + b)
y_hat = torch.tensor([[1, 2, 3], [4, 5, 60]])
#交叉熵损失函数
def cross_entropy(y_hat, y):
return - torch.log(y_hat[range(len(y_hat)), y])
#计算预测正确的数量
def accuracy(y_hat, y):
#len(y_hat.shape)>1是为验证y_hat是一个有行有列的矩阵, y_hat.shape[1]是为了验证矩阵的列数>1
if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
y_hat = y_hat.argmax(axis=1)#将每一行中元素最大的下标存到y_hat中
cmp = y_hat.type(y.dtype) == y#将y_hat转成y的数据类型与y做比较, 结果为布尔类型
return float(cmp.type(y.dtype).sum())#将布尔类型转成y的类型后求和
class Accumulator: #@save
"""在n个变量上累加"""
def __init__(self, n):
self.data = [0.0] * n#得到容量为n的数组: data内容 [0.0, 0.0, 0.0] n内容 3
def add(self, *args):
self.data = [a + float(b) for a, b in zip(self.data, args)]
#将args的内容与data中的内容相加存储在data中
# args内容(591.230712890625, 34.0, 256)
# data内容[0.0, 0.0, 0.0]
# 后data内容[591.230712890625, 34.0, 256.0]
def reset(self):
self.data = [0.0] * len(self.data)
def __getitem__(self, idx):
return self.data[idx]
#一顿操作得到精度, 正确的个数/总数=精度
def evaluate_accuracy(net, data_iter): #@save
#判断net是否是一个PyTorch的神经网络模型
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())#y.numel()代表整个样本的总数
return metric[0] / metric[1]
def train_epoch_ch3(net, train_iter, loss, updater): #@save
# 将模型设置为训练模式, 如果是pytorch自带的模型, 将模型设为训练模式
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()#将模型更新得到新的w与b
else:
# 使用定制的优化器和损失函数
l.sum().backward()
updater(x.shape[0])
#y.numel代表y中元素个数
metric.add(float(l.sum()), accuracy(y_hat, y), y.numel())
# 返回训练损失和训练精度
return metric[0] / metric[2], metric[1] / metric[2]
#数据可视化
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)
d2l.plt.show()
d2l.plt.pause(0.001)
display.clear_output(wait=True)
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
num_epochs = 10
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
运行结果如图