CS231n作業筆記2.1:兩層全連線神經網路的分層實現
阿新 • • 發佈:2018-12-30
CS231n簡介
作業筆記
1. 神經網路的分層實現
- 全連線前向傳播:
out = x.reshape([x.shape[0],-1]).dot(w)+b
- 全連線後向傳播:
x, w, b = cache
dx, dw, db = None, None, None
dw = x.reshape([x.shape[0],-1]).T.dot(dout)
db = np.sum(dout,axis = 0)
dx = dout.dot(w.T).reshape(x.shape)
- ReLU的前向傳播:
out = x*(x>0)
- ReLU的後向傳播:
dx = dout * (x>0)
2. 兩層全連線神經網路的打包實現
把上訴神經層串聯起來,構造兩層全連線神經網路。
2.1. 引數初始化
使用numpy.random.randn函式,用於服從標準分佈的隨機引數。注意:不要使用numpy.random.rand函式(用於生成[0,1)內的平均分佈);也可以使用numpy.random.normal函式。
self.params['W1'] = np.random.randn(input_dim,hidden_dim)*weight_scale
self.params['b1'] = np.zeros(hidden_dim)
self .params['W2'] = np.random.randn(hidden_dim,num_classes)*weight_scale
self.params['b2'] = np.zeros(num_classes)
2.2. 計算loss以及gradient
此函式用於計算loss,以及各個引數的梯度。大致上就是把上訴兩個神經層以及最後一層softmax按照一定的形式串聯起來。
注意:對於全連線神經網路,bias部分不進行正則化。因為bias不與資料相乘,所以不具有控制資料各個維度對最後影響大小的作用。(然而如果歸一化做的好,對bias做正則化,不會使得效果變差,原因可能是因為bias比weight的數目少太多,模型能夠支援對於bias的變化以獲得更好的準確率)[參考資料: Neural Networks Part 2: Setting up the Data and the Loss]
1.計算score
scores = None
W1,b1,W2,b2 = self.params['W1'],self.params['b1'],self.params['W2'],self.params['b2']
fc1_out,fc1_cache = affine_forward(X,W1,b1)
relu_out,relu_cache = relu_forward(fc1_out)
fc2_out,fc2_cache = affine_forward(relu_out,W2,b2)
scores = fc2_out
2.計算loss以及梯度
loss, grads = 0, {}
loss,dscores = softmax_loss(scores,y)
loss += 0.5*self.reg*(np.sum(W1**2)+np.sum(W2**2))
drelu_out,dW2,db2 = affine_backward(dscores,fc2_cache)
dfc1_out = relu_backward(drelu_out,relu_cache)
_,dW1,db1 = affine_backward(dfc1_out,fc1_cache)
dW1 += self.reg*W1
#db1 += self.reg*b1
dW2 += self.reg*W2
#db2 += self.reg*b2
grads['W1'],grads['b1'],grads['W2'],grads['b2'] = dW1,db1,dW2,db2