深度学习 —— 个人学习笔记6(权重衰减)

声明

本文章为个人学习使用,版面观感若有不适请谅解,文中知识仅代表个人观点,若出现错误,欢迎各位批评指正。

十三、权重衰减

使用以下公式为例做演示:

y = 0.05 + ∑ i = 1 d 0.01 x i + ε w h e r e ε    ~    N ( 0 , 0.0 1 2 ) y = 0.05 + \sum_{i=1}^{d} 0.01x_i + \varepsilon \quad where \quad \varepsilon \; ~ \; N ( 0 , 0.01^2 ) y=0.05+i=1∑d0.01xi+εwhereε~N(0,0.012)

  • 权重衰减的实现

    import torch
    from torch import nn
    from d2l import torch as d2l
    from IPython import display

    def synthetic_data(w, b, num_examples):
    """生成 y = Xw + b + 噪声。"""
    X = torch.normal(0, 1, (num_examples, len(w))).cuda() # 均值为 0,方差为 1,有 num_examples 个样本,列数为 w 长度
    y = torch.matmul(X, w).cuda() + b # y = Xw + b
    y += torch.normal(0, 0.01, y.shape).cuda() # 随机噪音
    return X, y.reshape((-1, 1)) # x,y作为列向量返回

    class Animator: # 定义一个在动画中绘制数据的实用程序类 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, ]
    # 使用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):
          # Add multiple data points into the figure
          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)
          # 通过以下两行代码实现了在PyCharm中显示动图
          d2l.plt.draw()
          d2l.plt.pause(interval=0.001)
          display.clear_output(wait=True)
          d2l.plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

    n_train, n_test, num_inputs, batch_size = 20, 100, 200, 5
    true_w, true_b = torch.ones((num_inputs, 1)).cuda() * 0.01, 0.05
    train_data = synthetic_data(true_w, true_b, n_train)
    train_iter = d2l.load_array(train_data, batch_size)
    test_data = synthetic_data(true_w, true_b, n_test)
    test_iter = d2l.load_array(test_data, batch_size, is_train=False)

    ############## 权重衰减的实现 #############
    def init_params():
    """ 初始化参数 """
    w = torch.normal(0, 1, size=(num_inputs, 1)).cuda()
    b = torch.zeros(1).cuda()
    w.requires_grad_(True)
    b.requires_grad_(True)
    return [w, b]

    def l2_penalty(w):
    """ 定义 L2 范数惩罚 """
    return (torch.sum(w.pow(2)) / 2).cuda()

    def train(lambd):
    flag_button = "使用"
    w, b = init_params()
    net, loss = lambda X: d2l.linreg(X, w, b), d2l.squared_loss
    num_epochs, lr = 150, 0.005
    animator = Animator(xlabel='epochs', ylabel='loss', yscale='log',
    xlim=[5, num_epochs], legend=['train', 'test'])
    for epoch in range(num_epochs):
    for X, y in train_iter:
    # 增加了 L2 范数惩罚项,、
    # 广播机制使 l2_penalty(w) 成为一个长度为 batch_size 的向量
    l = loss(net(X), y) + lambd * l2_penalty(w)
    l.sum().backward()
    d2l.sgd([w, b], lr, batch_size)
    if (epoch + 1) % 5 == 0:
    animator.add(epoch + 1, (d2l.evaluate_loss(net, train_iter, loss),
    d2l.evaluate_loss(net, test_iter, loss)))
    # print('w的L2范数是:', torch.norm(w).item())
    if lambd == 0:flag_button = "禁用"
    d2l.plt.title(f"{flag_button}权重衰减 (lambda = {lambd})\nw 的 L2 范数是:{torch.norm(w).item()}")
    d2l.plt.show()

    train(lambd=0)

    train(lambd=15)


  • 权重衰减的简洁实现

    import torch
    from torch import nn
    from d2l import torch as d2l
    from IPython import display

    def synthetic_data(w, b, num_examples):
    """生成 y = Xw + b + 噪声。"""
    X = torch.normal(0, 1, (num_examples, len(w))).cuda() # 均值为 0,方差为 1,有 num_examples 个样本,列数为 w 长度
    y = torch.matmul(X, w).cuda() + b # y = Xw + b
    y += torch.normal(0, 0.01, y.shape).cuda() # 随机噪音
    return X, y.reshape((-1, 1)) # x,y作为列向量返回

    class Animator: # 定义一个在动画中绘制数据的实用程序类 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, ]
    # 使用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):
          # Add multiple data points into the figure
          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)
          # 通过以下两行代码实现了在PyCharm中显示动图
          d2l.plt.draw()
          d2l.plt.pause(interval=0.001)
          display.clear_output(wait=True)
          d2l.plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

    n_train, n_test, num_inputs, batch_size = 20, 100, 200, 5
    true_w, true_b = torch.ones((num_inputs, 1)).cuda() * 0.01, 0.05
    train_data = synthetic_data(true_w, true_b, n_train)
    train_iter = d2l.load_array(train_data, batch_size)
    test_data = synthetic_data(true_w, true_b, n_test)
    test_iter = d2l.load_array(test_data, batch_size, is_train=False)

    ############## 权重衰减的简洁实现 #############

    def train_concise(wd):
    flag_button = "使用"
    net = nn.Sequential(nn.Linear(num_inputs, 1)).cuda()
    for param in net.parameters():
    param.data.normal_().cuda()
    loss = nn.MSELoss(reduction='none').cuda()
    num_epochs, lr = 150, 0.005
    # 偏置参数没有衰减
    trainer = torch.optim.SGD([
    {"params":net[0].weight,'weight_decay': wd},
    {"params":net[0].bias}], lr=lr)
    animator = Animator(xlabel='epochs', ylabel='loss', yscale='log',
    xlim=[5, num_epochs], legend=['train', 'test'])
    for epoch in range(num_epochs):
    for X, y in train_iter:
    trainer.zero_grad()
    l = loss(net(X), y)
    l.mean().backward()
    trainer.step()
    if (epoch + 1) % 5 == 0:
    animator.add(epoch + 1,
    (d2l.evaluate_loss(net, train_iter, loss),
    d2l.evaluate_loss(net, test_iter, loss)))
    # print('w的L2范数:', net[0].weight.norm().item())
    if wd == 0:flag_button = "禁用"
    d2l.plt.title(f"{flag_button}权重衰减 (lambda = {wd})\nw 的 L2 范数是:{net[0].weight.norm().item()}")
    d2l.plt.show()

    train_concise(0)

    train_concise(-2)



文中部分知识参考:B 站 ------ 跟李沐学AI;百度百科

相关推荐
GLDbalala7 分钟前
GPU PRO 5 - 1.2 Reducing Texture Memory Usage by 2-Channel Color Encoding 笔记
笔记
IT199514 分钟前
Docker笔记-对docker-compose.yml基本认识
笔记·docker·容器
剑穗挂着新流苏31232 分钟前
114_PyTorch 进阶:模型保存与读取的两大方式及“陷阱”避坑指南
人工智能·pytorch·深度学习
猹叉叉(学习版)1 小时前
【系统分析师_知识点整理】 1.计算机系统
笔记·软考·系统分析师
星幻元宇VR2 小时前
VR环保学习机|科技助力绿色教育新模式
大数据·科技·学习·安全·vr·虚拟现实
CryptoPP2 小时前
开发者指南:构建实时期货黄金数据监控系统
大数据·数据结构·笔记·金融·区块链
_一只小QQ2 小时前
软考中级第二节
学习
天理小学渣2 小时前
JavaScript_基础教程_自学笔记
开发语言·javascript·笔记
棱镜研途3 小时前
EI会议分享 | 2026年图像处理与模式识别国际会议(IC-IPPR 2026)【SPIE出版】
图像处理·人工智能·深度学习·目标检测·计算机·计算机视觉·视觉检测