Python實現(xiàn)softmax反向傳播的示例代碼
概念
softmax函數(shù)是常用的輸出層函數(shù),常用來解決互斥標簽的多分類問題。當然由于他是非線性函數(shù),也可以作為隱藏層函數(shù)使用
反向傳播求導
可以看到,softmax 計算了多個神經(jīng)元的輸入,在反向傳播求導時,需要考慮對不同神經(jīng)元的參數(shù)求導。
分兩種情況考慮:
- 當求導的參數(shù)位于分子時
- 當求導的參數(shù)位于分母時

當求導的參數(shù)位于分子時:

當求導的參數(shù)位于分母時(ez2 or ez3這兩個是對稱的,求導結果是一樣的):


代碼
import torch
import math
def my_softmax(features):
_sum = 0
for i in features:
_sum += math.e ** i
return torch.Tensor([ math.e ** i / _sum for i in features ])
def my_softmax_grad(outputs):
n = len(outputs)
grad = []
for i in range(n):
temp = []
for j in range(n):
if i == j:
temp.append(outputs[i] * (1- outputs[i]))
else:
temp.append(-outputs[j] * outputs[i])
grad.append(torch.Tensor(temp))
return grad
if __name__ == '__main__':
features = torch.randn(10)
features.requires_grad_()
torch_softmax = torch.nn.functional.softmax
p1 = torch_softmax(features,dim=0)
p2 = my_softmax(features)
print(torch.allclose(p1,p2))
n = len(p1)
p2_grad = my_softmax_grad(p2)
for i in range(n):
p1_grad = torch.autograd.grad(p1[i],features, retain_graph=True)
print(torch.allclose(p1_grad[0], p2_grad[i]))到此這篇關于Python實現(xiàn)softmax反向傳播的示例代碼的文章就介紹到這了,更多相關Python softmax 反向傳播內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python利用xlwt/openpyxl/xlutils實現(xiàn)寫入Excel數(shù)據(jù)
這篇文章主要為大家詳細介紹了Python如何利用xlwt/openpyxl/xlutils這些第三方庫實現(xiàn)寫入Excel數(shù)據(jù)功能,感興趣的小伙伴可以跟隨小編一起學習一下2024-11-11
Python爬蟲教程之利用正則表達式匹配網(wǎng)頁內(nèi)容
這篇文章主要給大家介紹了關于Python爬蟲教程之利用正則表達式匹配網(wǎng)頁內(nèi)容的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12
python XlsxWriter模塊創(chuàng)建aexcel表格的實例講解
今天小編就為大家分享一篇python XlsxWriter模塊創(chuàng)建aexcel表格的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05

