机器学习——权重衰减

发布时间 2023-10-30 20:50:18作者: Yohoc

权重衰减(Weight Decay)是正则化的一种技术,是针对神经网络权重参数的正则化手段。其通过为损失函数添加权重参数的L2范数来实现。在优化神经网络时,权重衰减会惩罚权重参数值过大,从而达到正则化的效果。

常见的权重衰减在损失函数中以如下形式添加:

loss = 损失函数 + λ * 权重L2范数 

其中λ是超参数,控制权重衰减的力度。权重L2范数即各个权重参数的平方和。

 

由于权重衰减在神经网络优化中很常用, 深度学习框架为了便于我们使用权重衰减, 将权重衰减集成到优化算法中,以便与任何损失函数结合使用。 此外,这种集成还有计算上的好处, 允许在不增加任何额外的计算开销的情况下向算法中添加权重衰减。(以pyTorch框架为例)

def train_concise(wd):
    net = nn.Sequential(nn.Linear(num_inputs, 1))
    for param in net.parameters():
        param.data.normal_()
    loss = nn.MSELoss(reduction='none')
    num_epochs, lr = 100, 0.003
    # 偏置参数没有衰减
    trainer = torch.optim.SGD([
        {"params":net[0].weight,'weight_decay': wd},
        {"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())