深度学习——回归任务损失函数
一、回归损失函数的定义
1.回归任务损失函数-MAE损失函数
Mean absolute loss(MAE)也被称为L1 Loss,是以绝对误差作为距离。损失函数公式:
\[\mathcal{L} = \frac{1}{n}\sum_{i=1}^{n} \big| y_i - f_\theta(x_i) \big|
\]
特点是:
- 由于L1 loss具有稀疏性,为了惩罚较大的值,因此常常将其作为正则项添加到其他loss中作为约束。
- L1 loss的最大问题是梯度在零点不平滑,导致会跳过极小值。
2.回归任务损失函数-MSE损失函数
Mean Squared Loss/ Quadratic Loss(MSE loss)也被称为L2 loss,或欧氏距离,它以误差的平方和的均值作为距离
损失函数公式:
\[\mathcal{L} = \frac{1}{n}\sum_{i=1}^{n} \big(y_i - f_\theta(x_i)\big)^2
\]
特点是:
- L2 loss也常常作为正则项。
- 当预测值与目标值相差很大时, 梯度容易爆炸。
3.回归任务损失函数-Smooth L1损失函数
Smooth L1说的是光滑之后的L1。损失函数公式:
\[\text{smooth}_{L_1}(x)=
\begin{cases}
0.5x^2 & \text{if } |x| < 1 \\
|x| - 0.5 & \text{otherwise}
\end{cases}
\]
其中:\(x=f(x)-y\) 为真实值和预测值的差值。
从右图中可以看出,该函数实际上就是一个分段函数
- 在\([-1,1]\)之间实际上就是L2损失,这样解决了L1的不光滑问题
- 在\([-1,1]\)区间外,实际上就是L1损失,这样就解决了离群点梯度爆炸的问题
二、代码实现
1.导包
import torch
import torch.nn as nn
2.定义函数,演示:MAE 损失函数
def dm01():
# 1. 定义变量,记录:预测值
y_true = torch.tensor([2.0,2.0,2.0],dtype=torch.float)
# 2. 定义变量,记录:预测值
y_pred = torch.tensor([1.0,1.0,1.9],requires_grad=True)
# 3. 创建MAE损失函数对象
criterion = nn.L1Loss()
# 4. 计算损失
loss = criterion(y_pred, y_true)
# 5. 输出损失
print(f"MAE:{loss}")
3.定义函数,演示:MSE 损失函数
def dm02():
# 1. 定义变量,记录:预测值
y_true = torch.tensor([2.0,2.0,2.0],dtype=torch.float)
# 2. 定义变量,记录:预测值
y_pred = torch.tensor([1.0,1.0,1.9],requires_grad=True)
# 3. 创建MAE损失函数对象
criterion = nn.MSELoss()
# 4. 计算损失
loss = criterion(y_pred, y_true)
# 5. 输出损失
print(f"MSE:{loss}")
4. 定义函数,演示:Smooth L1 损失函数
def dm03():
# 1. 定义变量,记录:预测值
y_true = torch.tensor([2.0,2.0,2.0],dtype=torch.float)
# 2. 定义变量,记录:预测值
y_pred = torch.tensor([1.0,1.0,1.9],requires_grad=True)
# 3. 创建MAE损失函数对象
criterion = nn.SmoothL1Loss()
# 4. 计算损失
loss = criterion(y_pred, y_true)
# 5. 输出损失
print(f"SmoothL1Loss:{loss}")
5.测试
if __name__ == '__main__':
dm01()
dm02()
dm03()

浙公网安备 33010602011771号