霜庭小筑

4.5 权重衰退的代码实现

4.5 权重衰退的代码实现

首先,我们生成一些数据,公式如下: y=0.05+∑i=1d0.01xi+ϵ where ϵ∈N(0,0.012)y=0.05+\sum_{i=1}^d0.01x_i+\epsilon\ where\ \epsilon\in\mathcal{N} (0,0.01^2) 为了使过拟合的效果更加明显,我们可以将问题的维数增加到 d=200d = 200 ,并使用一个只包含20个样本的小训练集。

%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]
def l2_penalty(w):
"""定义L2范数惩罚"""
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())

我们现在用lambd = 0禁用权重衰减后运行这个代码。 注意,这里训练误差有了减少,但测试误差没有减少, 这意味着出现了严重的过拟合。

train(lambd=0)
w的L2范数是: 14.14365291595459

svg

下面,我们使用权重衰减来运行代码。 注意,在这里训练误差增大,但测试误差减小。 这正是我们期望从正则化中得到的效果。

train(lambd=3)
w的L2范数是: 0.35196033120155334

svg

我们接着增大lambd。

train(lambd=10)
w的L2范数是: 0.01929609663784504

svg

  • 简洁实现 由于更新的权重衰减部分仅依赖于每个参数的当前值, 因此优化器必须至少接触每个参数一次。

默认情况下,PyTorch同时衰减权重和偏移。 这里我们只为权重设置了weight_decay,所以偏置参数 bb 不会衰减。

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())
train_concise(0)
w的L2范数: 15.155548095703125

svg

train_concise(3)
w的L2范数: 0.3790607154369354

svg

train_concise(10)
w的L2范数: 0.026397312059998512

svg

本文由 kaikaikk 原创,发布于 ; 转载请保留原文链接: https://kaikaikk.com/posts/d2l-4-5-weight-decay/