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

0. 基本介绍

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

SmoothL1Loss的公式为:

l o s s ( x , y ) = { 0.5 ( x − y ) 2 if  ∣ x − y ∣ < 1 ∣ x − y ∣ − 0.5 otherwise loss(x,y) = \begin{cases} 0.5(x-y)^2 & \text{if } |x-y| < 1 \\ |x-y| - 0.5 & \text{otherwise} \end{cases} loss(x,y)={0.5(xy)2xy0.5if xy<1otherwise

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

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

1. 绘制SmoothL1Loss函数

通过修改torch.linspace中的参数,可以改变图像的横坐标范围;通过修改torch.zeros中的参数,可以改变图像的高度和形状。

import torch.nn as nn
import matplotlib.pyplot as plt
import torch

# 定义函数和参数
smooth_l1_loss = nn.SmoothL1Loss(reduction='none')
x = torch.linspace(-1, 1, 10000)
y = smooth_l1_loss(torch.zeros(10000), x)

# x2 = 1e3*x
# y2 = 1e-3*smooth_l1_loss(torch.zeros(10000), x2)

# 绘制图像
plt.plot(x, y)
# plt.plot(x, y2)
plt.xlabel('x')
plt.ylabel('SmoothL1Loss')
plt.title('SmoothL1Loss Function')
plt.show()

在这里插入图片描述

2. 移动SmoothL1Loss公式的临界点

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

移动到0.1

import torch.nn as nn
import matplotlib.pyplot as plt
import torch

# 定义函数和参数
smooth_l1_loss = nn.SmoothL1Loss(reduction='none')
x = torch.linspace(-1, 1, 10000)
y = smooth_l1_loss(torch.zeros(10000), x)

x2 = 1e1*x
y2 = 1e-1*smooth_l1_loss(torch.zeros(10000), x2)

# 绘制图像
plt.plot(x, y)
plt.plot(x, y2)
plt.xlabel('x')
plt.ylabel('SmoothL1Loss')
plt.title('SmoothL1Loss Function')
plt.show()

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

移动到0.01

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

import torch.nn as nn
import matplotlib.pyplot as plt
import torch

# 定义函数和参数
smooth_l1_loss = nn.SmoothL1Loss(reduction='none')
x = torch.linspace(-1, 1, 10000)
y = smooth_l1_loss(torch.zeros(10000), x)

x2 = 1e2*x
y2 = 1e-2*smooth_l1_loss(torch.zeros(10000), x2)

# 绘制图像
plt.plot(x, y)
plt.plot(x, y2)
plt.xlabel('x')
plt.ylabel('SmoothL1Loss')
plt.title('SmoothL1Loss Function')
plt.show()

在这里插入图片描述

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值