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(lambd=10)
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(lambd=10)
标签:loss,num,权重,torch,pytroch,衰退,train,d2l,test From: https://www.cnblogs.com/jinbb/p/17591368.html