import matplotlib.pyplot as plt
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)
test_iter.num_workers = 0
train_iter.num_workers = 0
num_inputs = 784 # 将图片数据拉伸成一个向量 28*28=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)
def softmax(x):
x_exp = torch.exp(x)
partition = x_exp.sum(1,keepdim=True)
return x_exp/partition # 使用了广播机制 使得矩阵所有元素均大于0,且可解释为概率
# 验证softmax
x = torch.normal(0,1,(2,5))
x_prob = softmax(x)
x_prob,x_prob.sum(1)
# 实现softmax回归模型,得到可解释为概率的张量
def net(x):
# x.reshape为268*784的矩阵
return softmax(torch.matmul(x.reshape((-1,w.shape[0])),w)+b)
# 拿出预测索引,其中包含两个样本在三个类别的预测
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]
"""[0,1]指的是真实样本的下标,对于第0个样本,拿出y[0]样本类别的预测值,
对于第1个样本,拿出y[1]样本类别的预测值。拿出真实标号类的预测值。"""
# 交叉熵损失函数
def cross_entropy(y_hat,y):
return -torch.log(y_hat[range(len(y_hat)),y])
cross_entropy(y_hat,y)
# 比较预测值和真实y
def accuracy(y_hat,y):
if len(y_hat.shape)>1 and y_hat.shape[1]>1:
# 元素最大的那个下表存到y_hat里面
y_hat = y_hat.argmax(axis=1)
#把y_hat转为y的数据类型再与y做比较,存入cmp
cmp = y_hat.type(y.dtype)==y
#返回预测正确的aggravate
return float(cmp.type(y.dtype).sum())
accuracy(y_hat,y)/len(y)
def evaluate_accuracy(net,data_iter):
"""计算指定数据集上的精度"""
if isinstance(net,torch.nn.Module):
"""将模型设置为评估模式"""
net.eval()
"""正确预测数,预测总数"""
metric = Accumulator(2)
for x,y in data_iter:
metric.add(accuracy(net(x),y),y.numel())
return metric[0] / metric[1]
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)
# softmax回归训练
def train_epoch_ch3(net,train_iter,loss,updater):
if isinstance(net,torch.nn.Module):
net.train()
"""长度为3的迭代器来累加信息"""
metric = Accumulator(3)
for x,y in train_iter:
y_hat = net(x)
l = loss(y_hat,y)
if isinstance(updater,torch.optim.Optimizer):
# 梯度置0
updater.zero_grad()
# 计算梯度
l.backward()
# 更新参数
updater.step()
#
metric.add(
float(l)*len(y),accuracy(y_hat,y),
y.size().numel())
else:
l.sum().backward()
updater(x.shape[0])
metric.add(float(l.sum()),accuracy(y_hat,y),y.numel())
# 返回的是损失,所有loss的累加除以样本总数, 分类正确是样本数除以样本总数
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()
d2l.plt.draw()
d2l.plt.pause(0.001)
display.display(self.fig)
display.clear_output(wait=True)
# 训练函数
def train_ch3(net,train_iter,test_iter,loss,num_epochs,updater):
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
lr = 0.1
def updater(batch_size):
return d2l.sgd([w,b],lr,batch_size)
# 训练模型10个迭代周期
num_epochs = 10
train_ch3(net,train_iter,test_iter,cross_entropy,num_epochs,updater)
d2l.plt.show()
一开始不出图,后来 再add函数中加
d2l.plt.draw()
d2l.plt.pause(0.001)
最后加d2l.plt.show()
参考