权重衰退 梯度爆炸

梯度爆炸

目的

限制权重w,防止梯度爆炸

内容讲解

原理及方法介绍

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import matplotlib.pyplot as plt

import torch
from torch import nn
from d2l import torch as d2l

#生成人工数据集
n_train, n_test, num_inputs = 20, 100, 200
batch_size = 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用于绘图
animator = d2l.Animator(xlabel='epoch', ylabel='loss', yscale='log',
xlim=[5, num_epochs], legend=['train', 'test'])
for epoch in range(num_epochs):
for X, y in train_iter:
l = loss(net(X), y) + lambd * l2_penalty(w)
l.sum().backward() #计算梯度,backword()只能用于标量,所以要用sum()将l变成标量
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 __name__ == "__main__":
# 训练时加权衰退
train(lambd=10)
plt.show()

个人理解

在训练时引用权重参数L2惩罚,可以有效限制权重w的增长,即总体损失和w的增长共同限制参数变化。因为当w变化过大时,随着深度增加,梯度呈指数级增长,会导致梯度爆炸。

梯度爆炸


权重衰退 梯度爆炸
http://example.com/2025/08/15/25_08_15权重衰退/
作者
ZF ZHAO
发布于
2025年8月15日
许可协议