当前位置:   article > 正文

2--权重衰退_torch.norm().item()

torch.norm().item()

2.1 权重衰退

         权重衰减(weight decay)是最广泛使用的正则化的技术之一, 它通常也被称为L2正则化,这项技术通过函数与零的距离来衡量函数的复杂度。因为在所有函数f中,函数f=0(所有输入都得到值0) 在某种意义上是最简单的。 

        可以通过线性函数f(\mathbf{x}) = \mathbf{w}^\top \mathbf{x}的权重向量的范数来度量其复杂性,为了保证权重较小,一般会将其范数作为惩罚项加到最小化损失的问题中(一般使用L2范数)。这样损失函数就变为:

L(\mathbf{w}, b) + \frac{\lambda}{2} \|\mathbf{w}\|^2,

        其中正则化常数λ来描述这种权衡, 这是一个非负超参数,使用验证数据拟合。较小的λ值对应较少约束的w,而较大的λ值对w的约束更大。

        相应地,L2正则化回归的小批量随机梯度下降公式为:

\begin{aligned} \mathbf{w} & \leftarrow \left(1- \eta\lambda \right) \mathbf{w} - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}} \mathbf{x}^{(i)} \left(\mathbf{w}^\top \mathbf{x}^{(i)} + b - y^{(i)}\right). \end{aligned}

2.2代码实现

  1. !pip install git+https://github.com/d2l-ai/d2l-zh@release # installing d2l
  2. !pip install matplotlib==3.0.0
  3. %matplotlib inline
  4. import torch
  5. from torch import nn
  6. from d2l import torch as d2l
  7. n_train,n_test,num_inputs,batch_size = 20,100,200,5
  8. #训练集过小,模型越复杂相对来说是更容易过拟合
  9. true_w,true_b = torch.ones((num_inputs, 1))*0.01, 0.05
  10. train_data = d2l.synthetic_data(true_w,true_b,n_train)
  11. train_iter = d2l.load_array(train_data, batch_size)
  12. test_data = d2l.synthetic_data(true_w,true_b,n_test)
  13. test_iter = d2l.load_array(test_data, batch_size, is_train=False)
  14. def init_params():
  15. w = torch.normal(0,1,size=(num_inputs,1),requires_grad=True)
  16. b = torch.zeros(1,requires_grad=True)
  17. return [w,b]
  18. #定义L2范数惩罚
  19. def l2_penalty(w):
  20. #torch.sum(torch.abs(w)) #L1范式
  21. return torch.sum(w.pow(2))/2
  22. def train(lambd):
  23. w,b = init_params()
  24. #lambda函数也叫匿名函数,即函数没有具体的名称
  25. #def f(x):return x**2 print f(4) 与g = lambda x : x**2 print g(4) 等价
  26. net, loss = lambda X:d2l.linreg(X,w,b),d2l.squared_loss
  27. num_epochs, lr = 100, 0.003
  28. animator = d2l.Animator(xlabel='epochs',ylabel='loss',yscale='log',
  29. xlim=[5,num_epochs],legend=['train','test'])
  30. for epoch in range(num_epochs):
  31. for X,y in train_iter:
  32. l = loss(net(X),y)+ lambd*l2_penalty(w)
  33. l.sum().backward()
  34. d2l.sgd([w,b],lr,batch_size)
  35. if (epoch+1)%5 == 0:
  36. animator.add(epoch+1,(d2l.evaluate_loss(net,train_iter,loss),d2l.evaluate_loss(net,test_iter,loss)))
  37. print("w的L2范数是:",torch.norm(w).item())
  38. train(lambd=0)#正则化系数改为0
  39. train(lambd=10)#正则化系数为10

 train(lambd=0)运行结果:这里训练误差有了减少,但测试误差没有减少, 这意味着出现了严重的过拟合。

 train(lambd=10)运行结果:在这里训练误差增大,但测试误差减小。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/939051
推荐阅读
相关标签
  

闽ICP备14008679号