pyTorch深度學習多層感知機的實現

2022-09-25 02:00:08 字數 1483 閱讀 4448

目錄

前兩節實現的linear model 和 softmax model 是單層神經網路,只包含乙個輸入層和乙個輸出層,因為輸入層不對資料進行transformation,所以只算一層輸出層。

多層感知機(mutilayer preceptron)加入了隱藏層,將神經網路的層級加深,因為線性層的串聯結果還是線性層,所以必須在每個隱藏層之後新增啟用函式,即增加model的非線性能力,使得model的function set變大。

relu,sigmoid, tanh是三個常見的啟用函式,分別做出它們的函式影象以及導數影象。

#畫圖使用

def xyplot(x,y,name,size):

plt.figure(figsize=size)

plt.plot(x.detach().numpy(),y.detach().numpy())

plt.xlwww.cppcns.comabel('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')

其它兩個啟用函式的影象畫法類似,分別為x.sigmoid(),x.tanh()

實際上多層感知機不過是在linear變換之後新增relu操作,在output layer進行softmax操作

def relu(x):

return torch.max(input=x,others,other=torch.tensor(0.0))

max這個方法除了返回tensor中的最大值,還有和maximum函式一樣的作用,將input和other進行element-wise的比較,返回二者中的最大值,shape不變。

www.cppcns.com

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(irfplwgen_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

這裡就不從零開始實現了,因為softmax和linear model手寫過以後,這個只是增加了乙個矩陣乘法和乙個relu操作

深度學習入門07 多層感知機

異或門可以通過其他閘電路進行表示,我們可以通過組合與門 與非門 或門實現異或門的邏輯功能 在大學的 數字電子技術基礎 這門課中,這個是非常基礎的知識哦 在已知與門 與非門 或門的邏輯功能 真值表 的情況下,如何使用這些邏輯門組合出異或門的邏輯功能呢?我們在這裡給大家提供一種思路,按照下面組合的方式將...

《動手學深度學習》多層感知機

多層感知機含有乙個隱藏層,以下是一種含單隱藏層的多層感知機的設計,其輸出o r n q boldsymbol in mathbb o rn q 的公式為 h x wh b h,o hwo bo begin boldsymbol boldsymbol boldsymbol h boldsymbol h...

深度學習試驗之 多層感知器

mlp structure input layer 28 28 hidden layer 100 output layer 10 dataset mnist programming matlab pre processing of raw data 原始影象歸一化 原始影象規格化,規格化的具體方式為...