《动手学深度学习》softmax回归的从零开始实现

3.6. softmax回归的从零开始实现(动手学深度学习)
代码学习笔记

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)

3.6.1 初始化模型参数

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)

3.6.2 定义softmax操作

X=torch.tensor([[1.0,2.0,3.0],[4.0,5.0,6.0]])
#分别以维度0和1求和,6=【1,2,3】相加 15=【4,5,6】自己相加
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)
  #广播机制,每一项除以总和,求概率,每行概率和为1
  return X_exp / partition
X = torch.normal(0,1,(2,5))
X_prob = softmax(X)
X_prob,X_prob.sum(1)

3.6.3 定义模型

def net(X):
  return softmax(torch.matmul(X.reshape((-1,W.shape[0])),W)+b)

3.6.4 定义损失函数

y = torch.tensor([0,2])
y_hat = torch.tensor([[0.1,0.3,0.6],[0.3,0.2,0.5]])
#[0,1]对应y[0]->0.y[1]->2;
#从中选取y_hat[0,0]->0.1,y_hat[1,2]->0.5
y_hat[[0,1],y]
def cross_entropy(y_hat,y):
  #y_hat=torch.tensor([[0.1,0.3,0.6],[0.3,0.2,0.5]])得出len(y_hat)=2
  #-torch.log(y_hat[0][0])、-torch.log(y_hat[1][2])
  return -torch.log(y_hat[range(len(y_hat)),y])

cross_entropy(y_hat,y)

3.6.5 分类精度

def accuracy(y_hat,y):
  '''计算预测正确的数量'''
  if len(y_hat.shape)>1 and y_hat.shape[1]>1:
    #解释没有参数时,是默认将数组展平,当axis=1,是在行中比较,选出最大的列索引
    y_hat = y_hat.argmax(axis=1)
  #其实就是先把y_hat换成和y一样的数据类型,然后比较y_hat和y是否在每一个位置上的值相等。y之前的类型是troch.in64
  #y与y_hat进行比较,第一个位置不等,第二个位置相等,y_hat=torch.tensor([2,2]),y=torch.tensor([0,2])
  #也就是说第一张图片预测错误,第二章图片预测正确。所以我们得到[False, True],即[0,1]
  cmp = y_hat.type(y.dtype) == y
  return float(cmp.type(y.dtype).sum())
#(0+1)/2=0.5
accuracy(y_hat,y)/len(y)
def evaluate_accuracy(net, data_iter):
  '''计算在指定数据集上模型的精度'''
  #isinstance(net, torch.nn.Module)  判断net是否为torch.nn.Module
  if isinstance(net, torch.nn.Module):
    #将模型设置为评估模式
    net.eval()  
  #正确预测数、预测总数
  # 累加器,正确预测数metric[0]、预测总数metric[1]
  metric = Accumulator(2)
  #关闭梯度运算
  with torch.no_grad():
    for X,y in data_iter:
      #把预测对的个数,预测总数放入一个列表,y.numel()返回输入张量元素的总数
      metric.add(accuracy(net(X),y),y.numel())
  #计算正确率,并返回
  return metric[0] / metric[1]

出现报错:TypeError: ‘Accumulator’ object is not subscriptable
修改:在使用对象数组时,不要直接用’对象名.[i]',修改为‘对象名.data[i]’。
即:return metric[0] / metric[1]
修改为: return metric.data[0] / metric.data[1]

class Accumulator:
  #在n个变量上累加
  #在初始化的时候会根据传进来的n的大小来创建n个空间,且初始化全部为0.0
  def __init__(self,n):
    self.data = [0.0] * n
  
  #虽然*args代表这里可以传入任意个参数,但是因为要和初始化的个数相同不然要报错
  def add(self,*args):
    #for a,b in zip(self.data,args)是把原来类中对应位置的data和新传入的args做 a + float(b)加法操作然后重新赋给该位置的data
    #a是data中的数,b是args中的数·
    self.data = [a + float(b) for a,b in zip(self.data,args)]

  #重新设置空间大小并初始化
  def reset(self):
    self.data = [0.0] * len(self.data)
  #__getitem__实现类似数组的取操作
  def __gititem__(self, idx):
    return self.data[idx]
evaluate_accuracy(net, test_iter)

3.6.6 训练

def train_epoch_ch3(net,train_iter,loss,updater):
  '''训练模型一个迭代周期(定义见第三章)'''
  #将模型设置为训练模式
  if isinstance(net, torch.nn.Module):
    # 如果是torch.nn.Module则开始训练
    net.train()
  #训练损失总和、训练准确度总和、样本数
  metric = Accumulator(3)
  for X,y in train_iter:
    #计算梯度并更新参数
    y_hat = net(X)
    # 通过交叉熵损失函数来计算l
    l = loss(y_hat,y)

    #使用PyTorch内置的优化器和损失函数
    if isinstance(updater,torch.optim.Optimizer):
      #梯度置零
      updater.zero_gard()
      #计算梯度
      l.mean().backward()
      #更新参数
      updater.step()
    else:
      #使用定制的优化器和损失函数
      #如果全是自己实现的话,则l是一个向量,计算梯度并求和
      l.sum().backward()
      # 更新批量大小更新参数
      updater(X.shape[0])
    #记录分类的损失和,准确数,样本数
    #累加loss,准确数,样本数
    metric.add(float(l.sum()),accuracy(y_hat,y),y.numel())
  #返回训练损失和训练精度
  return metric.data[0]/metric.data[2],metric.data[1]/metric.data[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)
        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
lr = 0.1

def updater(batch_size):
    return d2l.sgd([W, b], lr, batch_size)

现在,我们训练模型10个迭代周期。 请注意,迭代周期(num_epochs)和学习率(lr)都是可调节的超参数。 通过更改它们的值,我们可以提高模型的分类精度。

num_epochs = 10
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)

3.6.7 预测
现在训练已经完成,我们的模型已经准备好对图像进行分类预测。 给定一系列图像,我们将比较它们的实际标签(文本输出的第一行)和模型预测(文本输出的第二行)。

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)

3.6.8 小结
(1)借助softmax回归,我们可以训练多分类的模型。
(2)训练softmax回归循环模型与训练线性回归模型非常相似:先读取数据,再定义模型和损失函数,然后使用优化算法训练模型。大多数常见的深度学习模型都有类似的训练过程。

参考链接:
《动手学深度学习》softmax回归的从零开始实现代码理解
实用程序类Accumulator
softmax线性回归的简洁实现
Python zip()用法,看这一篇就够了
Python报错:TypeError: ‘Accumulator‘ object is not subscriptable
《动手学习深度学习》

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值