pytorch 计算 kl散度 F.kl_div()

部署运行你感兴趣的模型镜像

先附上官方文档说明:torch.nn.functional — PyTorch 1.13 documentation

torch.nn.functional.kl_div(inputtargetsize_average=Nonereduce=Nonereduction='mean')

Parameters

  • input – Tensor of arbitrary shape

  • target – Tensor of the same shape as input

  • size_average (booloptional) – Deprecated (see reduction). By default, the losses are averaged over each loss element in the batch. Note that for some losses, there multiple elements per sample. If the field size_average is set to False, the losses are instead summed for each minibatch. Ignored when reduce is False. Default: True

  • reduce (booloptional) – Deprecated (see reduction). By default, the losses are averaged or summed over observations for each minibatch depending on size_average. When reduce is False, returns a loss per batch element instead and ignores size_average. Default: True

  • reduction (stringoptional) – Specifies the reduction to apply to the output: 'none' | 'batchmean' | 'sum' | 'mean''none': no reduction will be applied 'batchmean': the sum of the output will be divided by the batchsize 'sum': the output will be summed 'mean': the output will be divided by the number of elements in the output Default: 'mean'

然后看看怎么用:第一个参数传入的是一个对数概率矩阵,第二个参数传入的是概率矩阵。这里很重要,不然求出来的kl散度可能是个负值

比如现在我有两个矩阵X, Y。因为kl散度具有不对称性,存在一个指导和被指导的关系,因此这连个矩阵输入的顺序需要确定一下。

举个例子:如果现在想用Y指导X,第一个参数要传X,第二个要传Y。就是被指导的放在前面,然后求相应的概率和对数概率就可以了。

import torch
import torch.nn.functional as F

# 定义两个矩阵
x = torch.randn((4, 5))
y = torch.randn((4, 5))

# 因为要用y指导x,所以求x的对数概率,y的概率
logp_x = F.log_softmax(x, dim=-1)
p_y = F.softmax(y, dim=-1)


kl_sum = F.kl_div(logp_x, p_y, reduction='sum')
kl_mean = F.kl_div(logp_x, p_y, reduction='mean')

print(kl_sum, kl_mean)


>>> tensor(3.4165) tensor(0.1708)

贴一下下面的评论解释一下reduction参数,比如mean是对所有元素求平均,那么最后kl_sum就是kl_mean的4*5=20倍,即3.41是0.17的20倍。 

您可能感兴趣的与本文相关的镜像

PyTorch 2.8

PyTorch 2.8

PyTorch
Cuda

PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值