# 8BPC 神經網路整理報告 本次作業要用多層感知器Multilayer Perceptron(MLP)去學習解決8-bits parity check的問題。 --- 使用到的函數有Linear(x), ReLU(x), Sigmoid(x) 和 Tanh(x) ### Linear(x) ```python= class Linear: def __init__(self, m, n): self.W, self.b = np.random.randn(m,n), np.random.randn(1,n) self.dW, self.db = None, None def forward(self, x): self.x = x out = np.dot(x, self.W) + self.b return out def backward(self, dout): dx = np.dot(dout, self.W.T) self.dW = np.dot(self.x.T, dout) self.db = np.sum(dout, axis = 0) return dx ``` ### ReLU(x) ```python= class ReLU: def __init__(self): pass def forward(self, x): self.mask = (x <= 0) out = x out[out <= 0] = 0 return out def backward(self, dout): dx = dout dx[self.mask] = 0 return dx ``` ### Sigmoid(x) ```python= class Sigmoid: def __init__(self): pass def forward(self, x): out = 1/(1 + np.exp(-x)) self.o = out return out def backward(self, dout): dx = dout * self.o * (1 - self.o) return dx ``` ### Tanh(x) ```python= class Tanh: def __init__(self): pass def forward(self, x): out = ((1 - np.exp(-x)) / (1 + np.exp(-x))) self.o = out return out def backward(self, dout): dx = dout * (1 - self.o * self.o) return dx ``` --- 總共開了5層,每一層使用不同的函式 ```python= class FiveLayer: def __init__(self, m, n, o, p, q, r): self.linear1 = Linear(m, n) self.act1 = ReLU() self.linear2 = Linear(n, o) self.act2 = Sigmoid() self.linear3 = Linear(o, p) self.act3 = ReLU() self.linear4 = Linear(p, q) self.act4 = Tanh() self.linear5 = Linear(q, r) self.act5 = Sigmoid() self.loss = Loss() self.last_dW1, self.last_db1 = 0, 0 self.last_dW2, self.last_db2 = 0, 0 self.last_dW3, self.last_db3 = 0, 0 self.last_dW4, self.last_db4 = 0, 0 self.last_dW5, self.last_db5 = 0, 0 ``` ## 跑程式 --- 分別使用了二、三、四、五層網路做學習測試 兩層網路的學習成果 loss = 27 ![](https://i.imgur.com/UdkxNPa.png) 三層網路的學習成果 loss = 128 ![](https://i.imgur.com/wRVdrB4.png) 四層網路的學習成果 loss = 34 ![](https://i.imgur.com/e0eamHL.png) 五層網路的學習成果 loss = 7 ![](https://i.imgur.com/2ptNefx.png) ## 結論 做了二到五層的測試,每次數據浮動都偏大,以上的測試結果都是跑程式好幾次之下,數據最好的一次。在三層網路的測試中,每次都是loss=128,沒有變化。第三層網路使用的是ReLU函式,嘗試換成使用Sigmoid之後,loss=11(如下圖)。之後試著把第四層改用ReLU,同樣出現loss=128,判斷ReLU無法用在最後一層。 ![](https://i.imgur.com/sMPJQjm.png) 經過不同層數的學習實驗,可以說越多層不見得功效越好,還是要看你當中使用的函數的順序以及適當性,如果追求數據完美,就要經過多方面的嘗試才能得到。