0


深度学习(23):SmoothL1Loss损失函数

0. 基本介绍

SmoothL1Loss是一种常用的损失函数,通常用于回归任务中,其相对于均方差(MSE)损失函数的优势在于对异常值(如过大或过小的离群点)的惩罚更小,从而使模型更加健壮。

SmoothL1Loss的公式为:

  1. l
  2. o
  3. s
  4. s
  5. (
  6. x
  7. ,
  8. y
  9. )
  10. =
  11. {
  12. 0.5
  13. (
  14. x
  15. y
  16. )
  17. 2
  18. if
  19. x
  20. y
  21. <
  22. 1
  23. x
  24. y
  25. 0.5
  26. otherwise
  27. loss(x,y) = \begin{cases} 0.5(x-y)^2 & \text{if } |x-y| < 1 \\ |x-y| - 0.5 & \text{otherwise} \end{cases}
  28. loss(x,y)={0.5(xy)2xy∣−0.5if xy∣<1otherwise

其中,x和y分别为模型的输出和标签,|x-y|表示它们之间的差异。当|x-y|小于1时,采用平方误差;否则采用线性误差。这使得SmoothL1Loss相比于MSE更加鲁棒,即对于异常值的响应更加平缓。

在PyTorch中,可以使用nn.SmoothL1Loss()函数来构建SmoothL1Loss损失函数。

1. 绘制

  1. SmoothL1Loss

函数

通过修改

  1. torch.linspace

中的参数,可以改变图像的横坐标范围;通过修改

  1. torch.zeros

中的参数,可以改变图像的高度和形状。

  1. import torch.nn as nn
  2. import matplotlib.pyplot as plt
  3. import torch
  4. # 定义函数和参数
  5. smooth_l1_loss = nn.SmoothL1Loss(reduction='none')
  6. x = torch.linspace(-1,1,10000)
  7. y = smooth_l1_loss(torch.zeros(10000), x)# x2 = 1e3*x# y2 = 1e-3*smooth_l1_loss(torch.zeros(10000), x2)# 绘制图像
  8. plt.plot(x, y)# plt.plot(x, y2)
  9. plt.xlabel('x')
  10. plt.ylabel('SmoothL1Loss')
  11. plt.title('SmoothL1Loss Function')
  12. plt.show()

在这里插入图片描述

2. 移动SmoothL1Loss公式的临界点

移动临界点是为了在不尽兴其他操作的情况下,放大模型的损失

移动到0.1

  1. import torch.nn as nn
  2. import matplotlib.pyplot as plt
  3. import torch
  4. # 定义函数和参数
  5. smooth_l1_loss = nn.SmoothL1Loss(reduction='none')
  6. x = torch.linspace(-1,1,10000)
  7. y = smooth_l1_loss(torch.zeros(10000), x)
  8. x2 =1e1*x
  9. y2 =1e-1*smooth_l1_loss(torch.zeros(10000), x2)# 绘制图像
  10. plt.plot(x, y)
  11. plt.plot(x, y2)
  12. plt.xlabel('x')
  13. plt.ylabel('SmoothL1Loss')
  14. plt.title('SmoothL1Loss Function')
  15. plt.show()

如下,箭头处保持玩弯曲
在这里插入图片描述

移动到0.01

如下,箭头处还可以看到弯曲

  1. import torch.nn as nn
  2. import matplotlib.pyplot as plt
  3. import torch
  4. # 定义函数和参数
  5. smooth_l1_loss = nn.SmoothL1Loss(reduction='none')
  6. x = torch.linspace(-1,1,10000)
  7. y = smooth_l1_loss(torch.zeros(10000), x)
  8. x2 =1e2*x
  9. y2 =1e-2*smooth_l1_loss(torch.zeros(10000), x2)# 绘制图像
  10. plt.plot(x, y)
  11. plt.plot(x, y2)
  12. plt.xlabel('x')
  13. plt.ylabel('SmoothL1Loss')
  14. plt.title('SmoothL1Loss Function')
  15. plt.show()

在这里插入图片描述


本文转载自: https://blog.csdn.net/BIT_HXZ/article/details/130458821
版权归原作者 biter0088 所有, 如有侵权,请联系我们删除。

“深度学习(23):SmoothL1Loss损失函数”的评论:

还没有评论