权重衰退——weight decay

(一)权重衰退 weight decay

是常见的处理过拟合的方法。

如何去控制一个模型的容量呢,即解决过拟合问题?

  • 把模型变小,参数变小
  • 参数的可选范围较小,也就是今天的内容

使用均方范数作为硬性限制

  • 通过限制参数值的选择范围来控制模型容量
  • 通常不限制b,因为限制没什么区别
  • 小的θ意味着更强的正则项,就是让w不那么大,减少他的作用能力

min\ L(w,b) \ \ \ subject\ to\ ||w||^2 \leq \theta
使用均方范数作为柔性限制

  • 对于每个θ,都可以找到λ使得上面的函数等价于下面这个函数
  • 超参数λ控制了正则项的重要程度

min\ L(\mathbf{w}, b) + \frac{\lambda}{2} \|\mathbf{w}\|^2

然后相当于重新定义了一个新的更新法则计算梯度:
\frac{\partial}{\partial w}(l(w,b)+\frac{\lambda}{2}||w||^2 = \frac{\partial l(w,b)}{\partial w}) + \lambda w

我们原来的梯度更新是这样的:
W_{t+1} = W_t - η\frac{\partial l}{\partial W_t}
我们把新的函数带入,简化就得到了下面的式子:
W_{t+1} = (1-η\lambda)W_t - η\frac{\partial l(W_t,b_t)}{\partial W_t}

通常ηλ < 1, 在深度学习中常常叫做权重衰退。

总结:
  • 权重衰退通过L2正则项使得模型参数不会过大,从而控制了模型的复杂度,解决过拟合问题
  • 正则项权重是控制模型复杂度的超参数 λ

(二)权重衰退的代码实现

权重衰减是最广泛使用的正则化技术之一

%matplotlib inline
import torch
from torch import nn
from d2l import torch as d2l

制造人工数据集,生成数据。

n_train, n_test, num_inputs, batch_size = 20, 100, 200, 5
true_w, true_b = torch.ones((num_inputs, 1)) * 0.01, 0.05
train_data = d2l.synthetic_data(true_w, true_b, n_train)
train_iter = d2l.load_array(train_data, batch_size)
test_data = d2l.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), requires_grad=True)
    b = torch.zeros(1, requires_grad=True)
    return [w, b]

# L2范数惩罚
def l2_penalty(w):
    return torch.sum(w.pow(2)) / 2

# 模型训练函数
def train(lambd):
    w, b = init_params()
    net, loss = lambda X: d2l.linreg(X, w, b), d2l.squared_loss
    num_epochs, lr = 100, 0.003
    animator = d2l.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())
train(0) #不用权重衰退
# w的L2范数是: 13.994298934936523
# 训练在降,而验证机上没有作用
weight_decay=0
train(32) #使用权重衰退
# w的L2范数是: 0.014938468113541603
# 有一定的效果,可以看出w变小了许多
weight_decay=32
简洁实现
def train_concise(lambd):
    net = nn.Sequential(nn.Linear(200,1))
    for param in net.parameters():
        param.data.normal_()
    # 等价于 net[0].weight.data.normal_()
    loss = nn.MSELoss(reduction='none')
    num_epochs, lr = 100, 0.001 #这里的lr不能设的太大,否则会出bug,我一开始写成了0.3,找了半天bug
    trainer = torch.optim.SGD(params=net.parameters(),weight_decay=lambd,lr=lr)
    # # 第二种写法
    # trainer = torch.optim.SGD([
    #     {"params":net[0].weight,'weight_decay': lambd},
    #     {"params":net[0].bias}], lr=lr)
    animator = d2l.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())

train_concise(64)    
lr=0.3时出现的bug.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容