先附上官方文档说明:

torch.nn.functional.kl_div(input, target, size_average=none, reduce=none, reduction=’mean’)

parameters

input – tensor of arbitrary shape

target – tensor of the same shape as input

size_average (bool, optional) – 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 (bool, optional) – 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 (string, optional) – 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。就是被指导的放在前面,然后求相应的概率和对数概率就可以了。

补充:pytorch中的kl散度,为什么kl散度是负数?

f.kl_div()或者nn.kldivloss()是pytroch中计算kl散度的函数,它的用法有很多需要注意的细节。

输入

第一个参数传入的是一个对数概率矩阵,第二个参数传入的是概率矩阵。并且因为kl散度具有不对称性,存在一个指导和被指导的关系,因此这连个矩阵输入的顺序需要确定一下。如果现在想用y指导x,第一个参数要传x,第二个要传y。就是被指导的放在前面,然后求相应的概率和对数概率就可以了。

所以,一随机初始化一个tensor为例,对于第一个输入,我们需要先对这个tensor进行softmax(确保各维度和为1),然后再取log;对于第二个输入,我们需要对这个tensor进行softmax。

为什么kl散度计算出来为负数

先确保对第一个输入进行了softmax+log操作,对第二个参数进行了softmax操作。不进行softmax操作就可能为负。

然后查看自己的输入是否是小数点后有很多位,当小数点后很多位的时候,pytorch下的softmax会产生各维度和不为1的现象,导致kl散度为负,如下所示:

输出如下,我们可以看到softmax_b的各维度和不为1:

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。