深度学习 —— 个人学习笔记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;百度百科

相关推荐
明明真系叻16 分钟前
第二十六周机器学习笔记:PINN求正反解求PDE文献阅读——正问题
人工智能·笔记·深度学习·机器学习·1024程序员节
XianxinMao1 小时前
Transformer 架构对比:Dense、MoE 与 Hybrid-MoE 的优劣分析
深度学习·架构·transformer
青春男大2 小时前
java栈--数据结构
java·开发语言·数据结构·学习·eclipse
HyperAI超神经2 小时前
未来具身智能的触觉革命!TactEdge传感器让机器人具备精细触觉感知,实现织物缺陷检测、灵巧操作控制
人工智能·深度学习·机器人·触觉传感器·中国地质大学·机器人智能感知·具身触觉
mashagua3 小时前
RPA系列-uipath 学习笔记3
笔记·学习·rpa
nikoni233 小时前
828考研资料汇总
笔记·其他·硬件工程
沐泽Mu3 小时前
嵌入式学习-QT-Day05
开发语言·c++·qt·学习
请站在我身后3 小时前
复现Qwen-Audio 千问
人工智能·深度学习·语言模型·语音识别
锦亦之22333 小时前
cesium入门学习二
学习·html
m0_748256144 小时前
前端 MYTED单篇TED词汇学习功能优化
前端·学习