Skip to content

损失函数

损失函数衡量模型预测与真实值的差距。训练的目标就是最小化损失。

最常用的回归损失:

MSE=1ni=1n(yiy^i)2\text{MSE} = \frac{1}{n}\sum_{i=1}^{n}(y_i - \hat{y}_i)^2
import torch
import torch.nn as nn
y_true = torch.tensor([3.0, 5.0, 2.0])
y_pred = torch.tensor([2.8, 4.5, 2.5])
mse = nn.MSELoss()(y_pred, y_true)
print(f"MSE: {mse:.4f}")

对异常值更鲁棒:

MAE=1ni=1nyiy^i\text{MAE} = \frac{1}{n}\sum_{i=1}^{n}|y_i - \hat{y}_i|
mae = nn.L1Loss()(y_pred, y_true)
print(f"MAE: {mae:.4f}")
损失对异常值梯度
MSE敏感(平方放大误差)随误差线性变化
MAE鲁棒恒为 ±1

分类任务的标准损失:

CE=c=1Cyclog(y^c)\text{CE} = -\sum_{c=1}^{C} y_c \log(\hat{y}_c)
# 多分类
logits = torch.randn(3, 5) # 3 个样本,5 个类别
labels = torch.tensor([1, 3, 0])
ce = nn.CrossEntropyLoss()(logits, labels)
print(f"Cross-Entropy: {ce:.4f}")
# 二分类
bce = nn.BCEWithLogitsLoss()(torch.randn(3), torch.rand(3))
print(f"BCE: {bce:.4f}")

让同类样本靠近,异类样本远离:

# anchor: 基准样本,positive: 同类,negative: 异类
triplet_loss = nn.TripletMarginLoss(margin=1.0)
anchor = torch.randn(10, 128)
positive = torch.randn(10, 128)
negative = torch.randn(10, 128)
loss = triplet_loss(anchor, positive, negative)
print(f"Triplet Loss: {loss:.4f}")
任务损失函数输出层
回归MSE 或 MAE无激活
二分类BCEWithLogitsLoss无激活(内置 Sigmoid)
多分类CrossEntropyLoss无激活(内置 Softmax)
多标签分类BCEWithLogitsLoss无激活
对比学习TripletLoss / InfoNCEL2 归一化