Skip to content

损失函数

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

MSE=1n∑i=1n(yi−y^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}") # 约 0.09
MAE=1n∑i=1n∣yi−y^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}")

注意:CrossEntropyLoss 内部包含 Softmax,不要在外面重复加。

bce = nn.BCEWithLogitsLoss()(torch.randn(3), torch.rand(3))
print(f"BCE: {bce:.4f}")

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

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 归一化