损失函数
损失函数衡量模型预测与真实值的差距。训练的目标就是最小化损失。
MSE:均方误差
Section titled “MSE:均方误差”import torchimport 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.09MAE:平均绝对误差
Section titled “MAE:平均绝对误差”mae = nn.L1Loss()(y_pred, y_true)print(f"MAE: {mae:.4f}")| 损失 | 对异常值 | 梯度 | 使用场景 |
|---|---|---|---|
| MSE | 敏感(平方放大) | 随误差线性变化 | 大多数回归 |
| MAE | 鲁棒 | 恒为 ±1 | 有异常值时 |
Cross-Entropy
Section titled “Cross-Entropy”分类任务的标准损失:
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:二分类
Section titled “BCE:二分类”bce = nn.BCEWithLogitsLoss()(torch.randn(3), torch.rand(3))print(f"BCE: {bce:.4f}")Triplet Loss
Section titled “Triplet Loss”让同类样本靠近,异类样本远离:
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 / InfoNCE | L2 归一化 |