PyTorch 提供了一系列预定义的损失函数(Loss Functions),这些损失函数可以帮助你在训练神经网络时计算预测值和真实值之间的差异。以下是一些常用的损失函数:
回归损失函数(Regression Loss)
torch.nn.MSELoss
:均方误差损失(Mean Squared Error Loss),计算预测值和真实值之间平方差的平均值。torch.nn.L1Loss
:平均绝对误差损失(Mean Absolute Error Loss),计算预测值和真实值之间绝对差的平均值。torch.nn.SmoothL1Loss
:平滑的 L1 损失,是 L1Loss 的变体,对离群点(outliers)更鲁棒。torch.nn.HuberLoss
:Huber 损失,结合了 L1Loss 和 MSELoss 的优点,通过参数delta
控制两者之间的切换。
分类损失函数(Classification Loss)
torch.nn.CrossEntropyLoss
:交叉熵损失,用于多分类问题。输入通常是原始分数(logits),目标标签是类别索引。torch.nn.NLLLoss
:负对数似然损失(Negative Log Likelihood Loss),通常与torch.nn.LogSoftmax
结合使用,用于多分类问题。torch.nn.BCELoss
:二分类交叉熵损失(Binary Cross Entropy Loss),用于二分类问题,输入通常是未经 Sigmoid 激活的分数。torch.nn.BCEWithLogitsLoss
:带有 Sigmoid 激活的二分类交叉熵损失,输入是原始分数,内部会进行 Sigmoid 激活。torch.nn.MultiLabelMarginLoss
:多标签分类的边际损失。torch.nn.MultiLabelSoftMarginLoss
:多标签分类的软边际损失,用于多标签分类问题。torch.nn.SoftMarginLoss
:二分类的软边际损失。
序列损失函数(Sequence Loss)
torch.nn.CTCLoss
:连接时序分类损失(Connectionist Temporal Classification Loss),用于处理序列标签问题,如语音识别。
自定义损失函数
如果 PyTorch 提供的损失函数不满足你的需求,你可以通过继承 torch.nn.Module
类来定义自己的损失函数。例如:
import torch
import torch.nn as nn
class CustomLoss(nn.Module):
def __init__(self):
super(CustomLoss, self).__init__()
def forward(self, input, target):
# 自定义损失计算逻辑
loss = torch.mean((input - target) ** 2) # 例如,自定义为均方误差
return loss
使用自定义损失函数时,只需实例化该类并将其传递给优化器即可。