定义初始化参数函数

def init_params(): # 初始化权重w为正态分布随机数,形状为(num_inputs, 1),并要求计算梯度 w = torch.normal(0, 1, size=(num_inputs, 1), requires_grad=True) # 初始化偏置b为0,并要求计算梯度 b = torch.zeros(1, requires_grad=True) return [w, b]

定义L2范数惩罚项函数

def l2_penalty(w): # 计算w的L2范数的平方并除以2 return torch.sum(w.pow(2)) / 2

定义训练函数,传入参数lambd为L2范数惩罚项系数

def train(lambd): # 初始化参数w和b 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) # 每5轮输出一次损失值 if (epoch + 1) % 5 == 0: animator.add(epoch + 1, (d2l.evaluate_loss(net, train_iter, loss), d2l.evaluate_loss(net, test_iter, loss))) # 输出最后的参数w的L2范数 print('w的L2范数是:', torch.norm(w).item())

使用L2范数惩罚项系数为0训练模型

train(lambd=0)

使用L2范数惩罚项系数为3训练模型

train(lambd=3

对以下代码进行注释:def init_params w = torchnormal0 1 size=num_inputs 1 requires_grad=True b = torchzeros1 requires_grad=True return w bdef l2_penaltyw return torchsumwpow2 2def trainlambd w b

原文地址: https://www.cveoy.top/t/topic/ckWh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录