权重衰退——weight decay

分类: 365彩票数据最专业 作者: admin 时间: 2025-10-15 11:21:50 阅读: 3742
权重衰退——weight decay

(一)权重衰退 weight decay

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

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

把模型变小,参数变小

参数的可选范围较小,也就是今天的内容

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

通过限制参数值的选择范围来控制模型容量

通常不限制b,因为限制没什么区别

小的θ意味着更强的正则项,就是让w不那么大,减少他的作用能力

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

对于每个θ,都可以找到λ使得上面的函数等价于下面这个函数

超参数λ控制了正则项的重要程度

然后相当于重新定义了一个新的更新法则计算梯度:

我们原来的梯度更新是这样的:

我们把新的函数带入,简化就得到了下面的式子:

通常ηλ < 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

相关推荐

剑气书香
365投注被限制可以解除吗

剑气书香

09-19 ❤️ 511