快捷键

KLDivLoss

class torch.nn.KLDivLoss(size_average=None, reduce=None, reduction='mean', log_target=False)[source][source]

库尔洛克-莱布勒散度损失。

对于形状相同的张量 ypred, ytruey_{\text{pred}},\ y_{\text{true}} ,其中 ypredy_{\text{pred}}inputytruey_{\text{true}}target ,我们定义点 wise KL-散度如下

L(ypred, ytrue)=ytruelogytrueypred=ytrue(logytruelogypred)L(y_{\text{pred}},\ y_{\text{true}}) = y_{\text{true}} \cdot \log \frac{y_{\text{true}}}{y_{\text{pred}}} = y_{\text{true}} \cdot (\log y_{\text{true}} - \log y_{\text{pred}})

为了避免在计算此数量时出现下溢问题,此损失期望在对数空间中的参数 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 是数据集中的观测值。这与标准数学符号 KL(P  Q)KL(P\ ||\ Q) 不同,其中 PP 表示观测值的分布, QQ 表示模型。

警告

reduction = “mean”不会返回真正的 KL 散度值,请使用 reduction = “batchmean”,这与数学定义一致。

参数:
  • size_average(布尔值,可选)- 已弃用(见 reduction )。默认情况下,损失会在批次的每个损失元素上平均。注意,对于某些损失,每个样本可能有多个元素。如果将字段 size_average 设置为 False,则损失将针对每个 minibatch 进行求和。当 reduce 为 False 时忽略。默认:True

  • reduce(布尔值,可选)- 已弃用(见 reduction )。默认情况下,损失会根据 size_average 在 minibatch 的观测值上平均或求和。当 reduce 为 False 时,返回每个批次的损失元素,并忽略 size_average 。默认:True

  • reduction(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)

© 版权所有 PyTorch 贡献者。

使用 Sphinx 构建,并使用 Read the Docs 提供的主题。

文档

PyTorch 的全面开发者文档

查看文档

教程

深入了解初学者和高级开发者的教程

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源