pytorch 實(shí)現(xiàn)計(jì)算 kl散度 F.kl_div()
先附上官方文檔說明:https://pytorch.org/docs/stable/nn.functional.html
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'
然后看看怎么用:
第一個(gè)參數(shù)傳入的是一個(gè)對(duì)數(shù)概率矩陣,第二個(gè)參數(shù)傳入的是概率矩陣。這里很重要,不然求出來的kl散度可能是個(gè)負(fù)值。
比如現(xiàn)在我有兩個(gè)矩陣X, Y。因?yàn)閗l散度具有不對(duì)稱性,存在一個(gè)指導(dǎo)和被指導(dǎo)的關(guān)系,因此這連個(gè)矩陣輸入的順序需要確定一下。
舉個(gè)例子:
如果現(xiàn)在想用Y指導(dǎo)X,第一個(gè)參數(shù)要傳X,第二個(gè)要傳Y。就是被指導(dǎo)的放在前面,然后求相應(yīng)的概率和對(duì)數(shù)概率就可以了。
import torch import torch.nn.functional as F # 定義兩個(gè)矩陣 x = torch.randn((4, 5)) y = torch.randn((4, 5)) # 因?yàn)橐脃指導(dǎo)x,所以求x的對(duì)數(shù)概率,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)
補(bǔ)充:pytorch中的kl散度,為什么kl散度是負(fù)數(shù)?
F.kl_div()或者nn.KLDivLoss()是pytroch中計(jì)算kl散度的函數(shù),它的用法有很多需要注意的細(xì)節(jié)。
輸入
第一個(gè)參數(shù)傳入的是一個(gè)對(duì)數(shù)概率矩陣,第二個(gè)參數(shù)傳入的是概率矩陣。并且因?yàn)閗l散度具有不對(duì)稱性,存在一個(gè)指導(dǎo)和被指導(dǎo)的關(guān)系,因此這連個(gè)矩陣輸入的順序需要確定一下。如果現(xiàn)在想用Y指導(dǎo)X,第一個(gè)參數(shù)要傳X,第二個(gè)要傳Y。就是被指導(dǎo)的放在前面,然后求相應(yīng)的概率和對(duì)數(shù)概率就可以了。
所以,一隨機(jī)初始化一個(gè)tensor為例,對(duì)于第一個(gè)輸入,我們需要先對(duì)這個(gè)tensor進(jìn)行softmax(確保各維度和為1),然后再取log;對(duì)于第二個(gè)輸入,我們需要對(duì)這個(gè)tensor進(jìn)行softmax。
import torch import torch.nn.functional as F a = torch.tensor([[0,0,1.1,2,0,10,0],[0,0,1,2,0,10,0]]) log_a =F.log_softmax(a) b = torch.tensor([[0,0,1.1,2,0,7,0],[0,0,1,2,0,10,0]]) softmax_b =F.softmax(b,dim=-1) kl_mean = F.kl_div(log_a, softmax_b, reduction='mean') print(kl_mean)
為什么KL散度計(jì)算出來為負(fù)數(shù)
先確保對(duì)第一個(gè)輸入進(jìn)行了softmax+log操作,對(duì)第二個(gè)參數(shù)進(jìn)行了softmax操作。不進(jìn)行softmax操作就可能為負(fù)。
然后查看自己的輸入是否是小數(shù)點(diǎn)后有很多位,當(dāng)小數(shù)點(diǎn)后很多位的時(shí)候,pytorch下的softmax會(huì)產(chǎn)生各維度和不為1的現(xiàn)象,導(dǎo)致kl散度為負(fù),如下所示:
a = torch.tensor([[0.,0,0.000001,0.0000002,0,0.0000007,0]]) log_a =F.log_softmax(a,dim=-1) print("log_a:",log_a) b = torch.tensor([[0.,0,0.000001,0.0000002,0,0.0000007,0]]) softmax_b =F.softmax(b,dim=-1) print("softmax_b:",softmax_b) kl_mean = F.kl_div(log_a, softmax_b,reduction='mean') print("kl_mean:",kl_mean)
輸出如下,我們可以看到softmax_b的各維度和不為1:
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。