KLDivLoss¶
- class torch.nn.KLDivLoss(size_average=None, reduce=None, reduction='mean', log_target=False)[source][source]¶
Kullback-Leibler 散度损失。
对于相同形状的张量 ,其中 是
input
, 是target
,我们将逐点 KL 散度定义为为了避免计算此数量时出现下溢问题,此损失期望参数
input
在对数空间中。如果log_target
= True,则参数target
也可以在对数空间中提供。总结一下,此函数大致等同于计算
if not log_target: # default loss_pointwise = target * (target.log() - input) else: loss_pointwise = target.exp() * (target - input)
然后根据参数
reduction
减少此结果,如下所示if reduction == "mean": # default loss = loss_pointwise.mean() elif reduction == "batchmean": # mathematically correct loss = loss_pointwise.sum() / input.size(0) elif reduction == "sum": loss = loss_pointwise.sum() else: # reduction == "none" loss = loss_pointwise
注意
与 PyTorch 中的所有其他损失一样,此函数期望第一个参数
input
是模型的输出(例如,神经网络),第二个参数target
是数据集中的观测值。这与标准数学符号 不同,其中 表示观测值的分布, 表示模型。警告
reduction
= “mean” 不返回真正的 KL 散度值,请使用reduction
= “batchmean”,它与数学定义一致。- 参数
size_average (bool, 可选) – 已弃用(请参阅
reduction
)。默认情况下,损失在批次中的每个损失元素上取平均值。请注意,对于某些损失,每个样本有多个元素。如果size_average
字段设置为 False,则损失将改为对每个小批量求和。当reduce
为 False 时忽略。默认值:Truereduce (bool, 可选) – 已弃用(请参阅
reduction
)。默认情况下,损失根据size_average
在每个小批量的观测值上取平均值或求和。当reduce
为 False 时,返回每个批次元素的损失,并忽略size_average
。默认值:Truereduction (str, 可选) – 指定应用于输出的缩减方式。默认值:“mean”
log_target (bool, 可选) – 指定目标是否为对数空间。默认值:False
- 形状
输入:,其中 表示任意数量的维度。
目标:,与输入形状相同。
输出:默认情况下为标量。如果
reduction
为 ‘none’,则为 ,与输入形状相同。
- 示例:
>>> kl_loss = nn.KLDivLoss(reduction="batchmean") >>> # input should be a distribution in the log space >>> input = F.log_softmax(torch.randn(3, 5, requires_grad=True), dim=1) >>> # Sample a batch of distributions. Usually this would come from the dataset >>> target = F.softmax(torch.rand(3, 5), dim=1) >>> output = kl_loss(input, target)
>>> kl_loss = nn.KLDivLoss(reduction="batchmean", log_target=True) >>> log_target = F.log_softmax(torch.rand(3, 5), dim=1) >>> output = kl_loss(input, log_target)