4.5 weight reduction

1
2
3
4
5
#我们为了减小过拟合,也就是死记硬背不能达到学习的目的,我们加入惩罚项,使其不能死记硬背
#将原来的训练目标:最小化训练标签上的预测损失,调整为最小化预测损失和惩罚项之和。
#we take L2 norm as the penalty term. If the weight vector increases largely, our learning algorithm will more
#concentrate on minimizing weight norm ||w||^2.
#more details we will make up in the future.

4.5.2 high-dimension linear regression

1
2
3
4
%matplotlib inline
import torch
from torch import nn
from d2l import torch as d2l
1
2
3
4
5
6
7
8
9
10
11
#firstly we generate some data like previously, with x just one order.
#y = 0.05 + sigma(i=1, d, 0.01x_i) + epsilon, and epsilon satisfying N(0, 0.01), namely Gauss noise
# for more explicit fitting result, the dimension of problem can be increased to d=200., samples=20
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#也就是w是0.01的列向量,行数为输入维度200,很正常because we will
#calculate XW
train_data = d2l.synthetic_data(true_w, true_b, n_train)#generate data, return X with num_inputs rows and y with num_inputs rows
#注意这里生成的是normal distribution的数据矩阵。
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)

4.5.3 start from zero

1
#we just need add the penalty term to the origin target function.

1. Initialize model parameters

1
2
3
4
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]

2. define L2 norm penalty

1
2
def l2_penalty(w):
return torch.sum(w.pow(2)) / 2

3.define training code realization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#because from chapter 3, the linear network and square loss are not changed, so we directly use integrated functions about them.
def train(lambd):
w, b = init_params()
net, loss = lambda X: d2l.linreg(X, w, b), d2l.squared_loss#lambda相当于创建函数
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 penalty term, and boardcasting make l2_penalty(w) become a vector with length batch_size
l = loss(net(X), y) + lambd * l2_penalty(w)#因为最后y结果出来是batch_size, 1的向量
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())#item将张量转换为标量。

4. overview regularization directly training

1
2
3
#we now use lambd=0 to forbid weight reduction and then run this code.
#The result is training error has decreased but testing error has not decreased, so overfitting comes into being.
train(lambd=0)#为什么没有输出呢
w的L2范数是: 13.45615291595459

svg

5. Using weight reduction

1
2
#There, training error has increased but testing error has decreased, it's our desired results.
train(lambd=3)
w的L2范数是: 0.34696102142333984

svg

4.5.4 concisely realize

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
#深度学习框架将权重衰减集成到优化算法中,以便与任何损失函数结合使用。此外,计算上,允许在不增加任何额外的计算开销情况下向算法中添加权重衰减

#由于更新的权重衰减部分仅依赖每个参数的当前值,因此优化器必须至少接触每个参数一次。
#
#我们在instance优化器时,直接通过weight_decay指定weight decay hyper params.
#In default, PyTorch reduce weight and bias samutaneously
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')# preserver the sample-level loss, not summing or meaning them.
num_epochs, lr = 100, 0.003
#偏置参数没有衰减
trainer = torch.optim.SGD([{"params": net[0].weight, 'weight_decay': wd},#也就是加入了权重衰减, wd是权重衰减系数
{"params": net[0].bias}], lr=lr)
#create a optimizer using sGD algorithm
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())
1
train_concise(0)
w的L2范数: 14.142910957336426

svg

1
train_concise(3)
w的L2范数: 0.6731933355331421

svg

1
2
3
4
5
#conclusion: regularization is a common method to tackle overfitting: we add the penalty term in the loss function of 
#training sets, in order to reduce complexity of learned model.

#a special choice is L2 punishing weight reduction, which will cause that learning algorithm updates the weight reduction
#in the step.