欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PyTorch的SoftMax交叉熵?fù)p失和梯度用法

 更新時(shí)間:2020年01月15日 16:31:07   作者:_icrazy_  
今天小編就為大家分享一篇PyTorch的SoftMax交叉熵?fù)p失和梯度用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

在PyTorch中可以方便的驗(yàn)證SoftMax交叉熵?fù)p失和對(duì)輸入梯度的計(jì)算

關(guān)于softmax_cross_entropy求導(dǎo)的過(guò)程,可以參考HERE

示例

# -*- coding: utf-8 -*-
import torch
import torch.autograd as autograd
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import numpy as np

# 對(duì)data求梯度, 用于反向傳播
data = Variable(torch.FloatTensor([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]), requires_grad=True)

# 多分類(lèi)標(biāo)簽 one-hot格式
label = Variable(torch.zeros((3, 3)))
label[0, 2] = 1
label[1, 1] = 1
label[2, 0] = 1
print(label)

# for batch loss = mean( -sum(Pj*logSj) )
# for one : loss = -sum(Pj*logSj)
loss = torch.mean(-torch.sum(label * torch.log(F.softmax(data, dim=1)), dim=1))

loss.backward()
print(loss, data.grad)

輸出:

tensor([[ 0., 0., 1.],
    [ 0., 1., 0.],
    [ 1., 0., 0.]])
# loss:損失 和 input's grad:輸入的梯度
tensor(1.4076) tensor([[ 0.0300, 0.0816, -0.1116],
    [ 0.0300, -0.2518, 0.2217],
    [-0.3033, 0.0816, 0.2217]])

注意

對(duì)于單輸入的loss 和 grad

data = Variable(torch.FloatTensor([[1.0, 2.0, 3.0]]), requires_grad=True)


label = Variable(torch.zeros((1, 3)))
#分別令不同索引位置label為1
label[0, 0] = 1
# label[0, 1] = 1
# label[0, 2] = 1
print(label)

# for batch loss = mean( -sum(Pj*logSj) )
# for one : loss = -sum(Pj*logSj)
loss = torch.mean(-torch.sum(label * torch.log(F.softmax(data, dim=1)), dim=1))

loss.backward()
print(loss, data.grad)

其輸出:

# 第一組:
lable: tensor([[ 1., 0., 0.]])
loss: tensor(2.4076) 
grad: tensor([[-0.9100, 0.2447, 0.6652]])

# 第二組:
lable: tensor([[ 0., 1., 0.]])
loss: tensor(1.4076) 
grad: tensor([[ 0.0900, -0.7553, 0.6652]])

# 第三組:
lable: tensor([[ 0., 0., 1.]])
loss: tensor(0.4076) 
grad: tensor([[ 0.0900, 0.2447, -0.3348]])

"""
解釋:
對(duì)于輸入數(shù)據(jù) tensor([[ 1., 2., 3.]]) softmax之后的結(jié)果如下
tensor([[ 0.0900, 0.2447, 0.6652]])
交叉熵求解梯度推導(dǎo)公式可知 s[0, 0]-1, s[0, 1]-1, s[0, 2]-1 是上面三組label對(duì)應(yīng)的輸入數(shù)據(jù)梯度
"""

pytorch提供的softmax, 和log_softmax 關(guān)系

# 官方提供的softmax實(shí)現(xiàn)
In[2]: import torch
 ...: import torch.autograd as autograd
 ...: from torch.autograd import Variable
 ...: import torch.nn.functional as F
 ...: import torch.nn as nn
 ...: import numpy as np
In[3]: data = Variable(torch.FloatTensor([[1.0, 2.0, 3.0]]), requires_grad=True)
In[4]: data
Out[4]: tensor([[ 1., 2., 3.]])
In[5]: e = torch.exp(data)
In[6]: e
Out[6]: tensor([[ 2.7183,  7.3891, 20.0855]])
In[7]: s = torch.sum(e, dim=1)
In[8]: s
Out[8]: tensor([ 30.1929])
In[9]: softmax = e/s
In[10]: softmax
Out[10]: tensor([[ 0.0900, 0.2447, 0.6652]])
In[11]: # 等同于 pytorch 提供的 softmax 
In[12]: org_softmax = F.softmax(data, dim=1)
In[13]: org_softmax
Out[13]: tensor([[ 0.0900, 0.2447, 0.6652]])
In[14]: org_softmax == softmax # 計(jì)算結(jié)果相同
Out[14]: tensor([[ 1, 1, 1]], dtype=torch.uint8)

# 與log_softmax關(guān)系
# log_softmax = log(softmax)
In[15]: _log_softmax = torch.log(org_softmax) 
In[16]: _log_softmax
Out[16]: tensor([[-2.4076, -1.4076, -0.4076]])
In[17]: log_softmax = F.log_softmax(data, dim=1)
In[18]: log_softmax
Out[18]: tensor([[-2.4076, -1.4076, -0.4076]])

官方提供的softmax交叉熵求解結(jié)果

# -*- coding: utf-8 -*-
import torch
import torch.autograd as autograd
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import numpy as np

data = Variable(torch.FloatTensor([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]), requires_grad=True)
log_softmax = F.log_softmax(data, dim=1)

label = Variable(torch.zeros((3, 3)))
label[0, 2] = 1
label[1, 1] = 1
label[2, 0] = 1
print("lable: ", label)

# 交叉熵的計(jì)算方式之一
loss_fn = torch.nn.NLLLoss() # reduce=True loss.sum/batch & grad/batch
# NLLLoss輸入是log_softmax, target是非one-hot格式的label
loss = loss_fn(log_softmax, torch.argmax(label, dim=1))
loss.backward()
print("loss: ", loss, "\ngrad: ", data.grad)

"""
# 交叉熵計(jì)算方式二
loss_fn = torch.nn.CrossEntropyLoss() # the target label is NOT an one-hotted
#CrossEntropyLoss適用于分類(lèi)問(wèn)題的損失函數(shù)
#input:沒(méi)有softmax過(guò)的nn.output, target是非one-hot格式label
loss = loss_fn(data, torch.argmax(label, dim=1))
loss.backward()
print("loss: ", loss, "\ngrad: ", data.grad)
"""
"""

輸出

lable: tensor([[ 0., 0., 1.],
    [ 0., 1., 0.],
    [ 1., 0., 0.]])
loss: tensor(1.4076) 
grad: tensor([[ 0.0300, 0.0816, -0.1116],
    [ 0.0300, -0.2518, 0.2217],
    [-0.3033, 0.0816, 0.2217]])

通過(guò)和示例的輸出對(duì)比, 發(fā)現(xiàn)兩者是一樣的

以上這篇PyTorch的SoftMax交叉熵?fù)p失和梯度用法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 超詳細(xì)講解python正則表達(dá)式

    超詳細(xì)講解python正則表達(dá)式

    這篇文章主要介紹了python正則表達(dá)式,利用正則表達(dá)式實(shí)現(xiàn)文本的查找和替換功能會(huì)相對(duì)于比較簡(jiǎn)單,效率也會(huì)更高。感興趣的小伙伴一起來(lái)學(xué)習(xí)學(xué)習(xí)吧
    2021-08-08
  • python實(shí)現(xiàn)隨機(jī)調(diào)用一個(gè)瀏覽器打開(kāi)網(wǎng)頁(yè)

    python實(shí)現(xiàn)隨機(jī)調(diào)用一個(gè)瀏覽器打開(kāi)網(wǎng)頁(yè)

    下面小編就為大家分享一篇python實(shí)現(xiàn)隨機(jī)調(diào)用一個(gè)瀏覽器打開(kāi)網(wǎng)頁(yè),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-04-04
  • python2.7 安裝pip的方法步驟(管用)

    python2.7 安裝pip的方法步驟(管用)

    這篇文章主要介紹了python2.7 安裝pip的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • Python使用socket的UDP協(xié)議實(shí)現(xiàn)FTP文件服務(wù)功能

    Python使用socket的UDP協(xié)議實(shí)現(xiàn)FTP文件服務(wù)功能

    這篇文章主要介紹了Python使用socket的UDP協(xié)議實(shí)現(xiàn)FTP文件服務(wù),本示例主要是用Python的socket,使用UDP協(xié)議實(shí)現(xiàn)一個(gè)FTP服務(wù)端、FTP客戶(hù)端,用來(lái)實(shí)現(xiàn)文件的傳輸,需要的朋友可以參考下
    2023-10-10
  • 淺談django 模型類(lèi)使用save()方法的好處與注意事項(xiàng)

    淺談django 模型類(lèi)使用save()方法的好處與注意事項(xiàng)

    這篇文章主要介紹了淺談django 模型類(lèi)使用save()方法的好處與注意事項(xiàng),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-03-03
  • Python3合并兩個(gè)有序數(shù)組代碼實(shí)例

    Python3合并兩個(gè)有序數(shù)組代碼實(shí)例

    這篇文章主要介紹了Python3合并兩個(gè)有序數(shù)組代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • 利用pyinstaller將py文件打包為exe的方法

    利用pyinstaller將py文件打包為exe的方法

    本篇文章主要介紹了利用pyinstaller將py文件打包為exe的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-05-05
  • python實(shí)現(xiàn)多人聊天服務(wù)器以及客戶(hù)端

    python實(shí)現(xiàn)多人聊天服務(wù)器以及客戶(hù)端

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)多人聊天服務(wù)器以及客戶(hù)端,帶圖形化界面,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • Python辦公自動(dòng)化之操控遠(yuǎn)程桌面和文件版本控制

    Python辦公自動(dòng)化之操控遠(yuǎn)程桌面和文件版本控制

    這篇文章主要為大家詳細(xì)介紹了Python辦公自動(dòng)化中操控遠(yuǎn)程桌面和文件版本控制的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下
    2024-01-01
  • 利用Python中xlwt模塊操作excel的示例詳解

    利用Python中xlwt模塊操作excel的示例詳解

    在開(kāi)發(fā)中,我們最常見(jiàn)的數(shù)據(jù)問(wèn)題之一,就是對(duì)數(shù)據(jù)進(jìn)行導(dǎo)出整理給運(yùn)營(yíng)人員,所以操作excel就顯得重中之重,在python中操作excel可以借助xlwt模塊。感興趣的可以跟隨小編一起學(xué)習(xí)一下這篇文章
    2022-01-01

最新評(píng)論