pyTorch深度學(xué)習(xí)多層感知機(jī)的實(shí)現(xiàn)
激活函數(shù)
前兩節(jié)實(shí)現(xiàn)的傳送門
pyTorch深度學(xué)習(xí)softmax實(shí)現(xiàn)解析
pyTorch深入學(xué)習(xí)梯度和Linear Regression實(shí)現(xiàn)析
前兩節(jié)實(shí)現(xiàn)的linear model 和 softmax model 是單層神經(jīng)網(wǎng)絡(luò),只包含一個(gè)輸入層和一個(gè)輸出層,因?yàn)檩斎雽硬粚?shù)據(jù)進(jìn)行transformation,所以只算一層輸出層。
多層感知機(jī)(mutilayer preceptron)加入了隱藏層,將神經(jīng)網(wǎng)絡(luò)的層級加深,因?yàn)榫€性層的串聯(lián)結(jié)果還是線性層,所以必須在每個(gè)隱藏層之后添加激活函數(shù),即增加model的非線性能力,使得model的function set變大。
ReLU,Sigmoid, tanh是三個(gè)常見的激活函數(shù),分別做出它們的函數(shù)圖像以及導(dǎo)數(shù)圖像。
#畫圖使用 def xyplot(x,y,name,size): plt.figure(figsize=size) plt.plot(x.detach().numpy(),y.detach().numpy()) plt.xlabel('x') plt.ylabel(name+'(x)') plt.show()
#relu x = torch.arange(-8,8,0.01,requires_grad=True) y = x.relu() xyplot(x,y,'relu')
y.sum().backward() xyplot(x,x.grad,'grad of relu')
其它兩個(gè)激活函數(shù)的圖像畫法類似,分別為x.sigmoid(),x.tanh()
多層感知機(jī)的PyTorch實(shí)現(xiàn)
實(shí)際上多層感知機(jī)不過是在linear變換之后添加relu操作,在output layer進(jìn)行softmax操作
def relu(x): return torch.max(input=x,others,other=torch.tensor(0.0))
max這個(gè)方法除了返回tensor中的最大值,還有和maximum函數(shù)一樣的作用,將input和other進(jìn)行element-wise的比較,返回二者中的最大值,shape不變。
class MulPeceptron(nn.Module): def __init__(self,in_features,out_features): super().__init__() self.fc = nn.Linear(in_features=in_features,out_features=256) self.out = nn.Linear(in_features=256,out_features=out_features) def forward(self,t): t = t.flatten(start_dim=1) t = self.fc(t) t = F.relu(t) t = self.out(t) return t
這里就不從零開始實(shí)現(xiàn)了,因?yàn)閟oftmax和linear model手寫過以后,這個(gè)只是增加了一個(gè)矩陣乘法和一個(gè)ReLU操作
以上就是pytorch深度學(xué)習(xí)多層感知機(jī)的實(shí)現(xiàn)的詳細(xì)內(nèi)容,更多關(guān)于pytorch實(shí)現(xiàn)多層感知機(jī)的資料請關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。