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

當(dāng)求導(dǎo)的參數(shù)位于分子時(shí):

當(dāng)求導(dǎo)的參數(shù)位于分母時(shí)(ez2 or ez3這兩個是對稱的,求導(dǎo)結(jié)果是一樣的):


代碼
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]))到此這篇關(guān)于Python實(shí)現(xiàn)softmax反向傳播的示例代碼的文章就介紹到這了,更多相關(guān)Python softmax 反向傳播內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python利用xlwt/openpyxl/xlutils實(shí)現(xiàn)寫入Excel數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了Python如何利用xlwt/openpyxl/xlutils這些第三方庫實(shí)現(xiàn)寫入Excel數(shù)據(jù)功能,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11
Python爬蟲教程之利用正則表達(dá)式匹配網(wǎng)頁內(nèi)容
這篇文章主要給大家介紹了關(guān)于Python爬蟲教程之利用正則表達(dá)式匹配網(wǎng)頁內(nèi)容的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
python XlsxWriter模塊創(chuàng)建aexcel表格的實(shí)例講解
今天小編就為大家分享一篇python XlsxWriter模塊創(chuàng)建aexcel表格的實(shí)例講解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05
python項(xiàng)目--使用Tkinter的日歷GUI應(yīng)用程序
在 Python 中,我們可以使用 Tkinter 制作 GUI。如果你非常有想象力和創(chuàng)造力,你可以用 Tkinter 做出很多有趣的東西,希望本篇文章能夠幫到你2021-08-08
Python利用yarl實(shí)現(xiàn)輕松操作url
在諸如網(wǎng)絡(luò)爬蟲、web應(yīng)用開發(fā)等場景中,我們需要利用Python完成大量的url解析、生成等操作。本文為大家介紹了Pythonyarl操作url的方法,需要的可以了解一下2022-10-10

