参与11月更文挑战的第16天,活动详情查看:2021最后一次更文挑战
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)
复制代码
首先是生成人工数据集:
这段代码就不具体解释了,看不明白的看这里:动手学深度学习4.5 正则化 权重衰退代码手动实现 - 掘金 (juejin.cn)
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 train_concise(wd):
net = nn.Sequential(nn.Linear(num_inputs, 1))
for param in net.parameters():
param.data.normal_()
loss = nn.MSELoss()
num_epochs, lr = 100, 0.003
# 偏置参数没有衰减,只设置weight decay。
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:
with torch.enable_grad():
trainer.zero_grad()
l = loss(net(X), y)
l.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())
复制代码
直接通过weight_decay
指定weight decay超参数。
默认情况下,PyTorch同时衰减权重和偏移。
这里我们只为权重设置了weight_decay
,所以bias参数b不会衰减。
看起来代码可能比权重衰退代码手动实现并没有短多少,但是它们运行得更快,更容易实现,对于更复杂的问题,这一优势更加显著。
train_concise(0)
train_concise(3)
复制代码
训练。
看一下结果:
train_concise(0):
train_concise(3):
正则化之后过拟合现象有所缓解。
《动手学深度学习》系列更多可以看这里:《动手学深度学习》 - LolitaAnn的专栏 - 掘金 (juejin.cn)
笔记还在更新中…………