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

相关推荐
xiaoyalian2 小时前
R语言绘图过程中遇到图例的图块中出现字符“a“的解决方法
笔记·r语言·数据可视化
Red Red3 小时前
网安基础知识|IDS入侵检测系统|IPS入侵防御系统|堡垒机|VPN|EDR|CC防御|云安全-VDC/VPC|安全服务
网络·笔记·学习·安全·web安全
贰十六4 小时前
笔记:Centos Nginx Jdk Mysql OpenOffce KkFile Minio安装部署
笔记·nginx·centos
知兀4 小时前
Java的方法、基本和引用数据类型
java·笔记·黑马程序员
Natural_yz5 小时前
大数据学习17之Spark-Core
大数据·学习·spark
qq_172805595 小时前
RUST学习教程-安装教程
开发语言·学习·rust·安装
一只小小汤圆5 小时前
opencascade源码学习之BRepOffsetAPI包 -BRepOffsetAPI_DraftAngle
c++·学习·opencascade
醉陌离5 小时前
渗透测试笔记——shodan(4)
笔记
虾球xz6 小时前
游戏引擎学习第20天
前端·学习·游戏引擎
LateBloomer7776 小时前
FreeRTOS——信号量
笔记·stm32·学习·freertos