本文建立在理論推導之上,推導部分我通過一系列視頻呈現,感興趣請去我的主頁找『戴森與你聊:神經網絡小知識』這個合集即可,根據前面所做的推導,本文就通過代碼來實現一個簡單的三層全連接網絡。
#技術技能超級玩家#
本文將要實現的一個三層全連接簡單網絡
0.必要的庫
我們代碼基于Python環境,大家可以把下面的代碼寫入到一個jupyter notebook中,分節運行并調試。實現神經網絡的基本算法,需要用到一些庫,我們先把它們導入進來:
import numpy as np
import matplotlib.pyplot as plot
接下來進入正題!
1.給定輸入和輸出
X = np.array([[1,0,0,0],[1,0,1,1],[0,1,0,1],[1,1,1,0],[1,0,0,1]])
print('nInput shape:n',X.shape)
y = np.array([[1],[1],[0],[1],[0]])
print('nGround truth shape:n',y.shape)
注意: 在之前的推導中(視頻中)我們假設一個輸入是一個列向量,而這里使用的是矩陣,代表什么呢?在上面(3,4)所表示的輸入信號維度中,第一個3是指的樣本數目,而第二個4指的是每個樣本中的feature的數目。因此,這里的(3,4)意思就是,輸入是三個樣本,每個樣本用一個 1x4 的向量來表達。一定注意二者區別,這決定了后面所有矩陣運算時角標的順序(也就是矩陣相乘時候的順序)。 還要提醒各位注意觀察,樣本數目的多少,和后面的權重沒有關系!權重的數目只取決于每個樣本自身的維度。這其中有什么原因嗎?
2. 定義網絡結構和參數
假定使用以下結構的簡單全連接網絡,輸入層有4個單元,隱藏層3個單元,輸出層一個單元
numInputNeurons = X.shape[1]
numHiddenNeurons = 3
numOutputNeurons = 1
3. 初始化權重和偏置參數
注意: 權重編號規則,與推導過程中使用的下標編號規則不一致,比如對于權重矩陣,之前推導中我們約定的是先寫目標單元,再寫起始單元的順序,這里反過來了,大家可以考慮下為什么?
weightsInputHidden = np.random.uniform(size=(numInputNeurons,numHiddenNeurons))
print('nThe shape of weight matrix between the input layer and hidden layer is: ',weightsInputHidden.shape)
weightsHiddenOutput = np.random.uniform(size=(numHiddenNeurons,numOutputNeurons))
print('nThe shape of weight matrix between the hidden layer and output layer is: ',weightsHiddenOutput.shape)
biasHidden = np.random.uniform(size=(1,numHiddenNeurons))
print('nThe shape of bias matrix of hidden layer: ',biasHidden.shape)
biasOutput = np.random.uniform(size=(1,numOutputNeurons))
print('nThe shape of bias matrix of output layer is: ',biasOutput.shape)
4. 定義激活函數及其導數函數
前向和反向傳播都會用到Sigmoid函數以及它的導數,先定義它們:
def sigmoid(x):
return 1/(1 + np.exp(-x))
# Detailed definition of the derivative of sigmoid function
def derivative_sigmoid(x, original = False):
return x * (1 - x)
if(original == True):
return sigmoid(x) * (1 - sigmoid(x))
5. 正向傳播 Forward Propagation¶
5.1 InputLayer --> HiddenLayer
hiddenIn = np.dot(X, weightsInputHidden) + biasHidden
hiddenActivation = sigmoid(hiddenIn)
注意: 這里涉及到矩陣運算的順序,仔細分析一下。主要就是盯著維度的匹配!
- 如果輸入單元是行向量(本例中就是如此)且有j個元素,輸入層的維度就是 1xj,然后后面的矩陣計算就一定要也得到一個維度匹配的行向量;
- 如果輸入單元是列向量(前面推導中的情形),那么輸入層的維度就是jx1,后面的矩陣計算就要匹配列向量的維度
5.2 HiddenLayer --> OutputLayer
outputIn = np.dot(hiddenActivation, weightsHiddenOutput) + biasOutput
outputActivation = sigmoid(outputIn)print('nPrediction is: ', outputActivation)
6. 反向傳播 Back Propagation
誤差反傳是最重要的一步,分為以下幾個關鍵步驟:
6.1 成本函數和成本函數的導數
Error = np.square(y - outputActivation)/2
E = outputActivation - y
6.2 BP四個基本方程之:輸出層神經元誤差
derivativeHidden = derivative_sigmoid(hiddenActivation)
derivativeHidden.shapedeltaHidden = np.dot(deltaOutput, weightsHiddenOutput.T) * derivativeHiddendeltaHidden.sha# Learning rate
lr = 0.01n
6.3 BP四個基本方程之:中間層神經元誤差
derivativeHidden = derivative_sigmoid(hiddenActivation)
derivativeHidden.shapedeltaHidden = np.dot(deltaOutput, weightsHiddenOutput.T) * derivativeHiddendeltaHidden.shapedeltaHidden
6.4 BP四個基本方程之:權重和偏置的更新
# Learning rate
lr = 0.01
weightsHiddenOutput -= np.dot(hiddenActivation.T, deltaOutput) * lr # 3xN x Nx1 = 3x1
weightsInputHidden -= np.dot(X.T, deltaHidden) * lr # 4xN x Nx3 = 4x3
biasOutput -= np.sum(deltaOutput, axis=0) * lr
biasHidden -= np.sum(deltaHidden, axis=0) * lr
注意: 上面注意維度的匹配!網絡本身的參數維度和樣本數均無關,比如權重和偏置的維度,都不可能與樣本數有關系!這是檢驗我們有沒有做對的一個很有用的標準。
到這為止,對這個神經網絡的一次完整的前向傳播+反向傳播的流程算是進行完了!這是分解動作,也是完成了一次『訓練』,但是一個神經網絡必須經過多次訓練,才能夠較好的調整參數并完成任務,因此我們需要把這個訓練過程寫入一個循環中,反復進行!
上述過程的完整實現+訓練神經網絡
# Define Structure Parameters
numInputNeurons = X.shape[1]
numHiddenNeurons = 3
numOutputNeurons = 1
# Initialize weights and biases with random numbers
weightsInputHidden = np.random.uniform(size=(numInputNeurons,numHiddenNeurons))print('nThe shape of weight matrix between the input layer and hidden layer is: ',weightsInputHidden.shape)
weightsHiddenOutput = np.random.uniform(size=(numHiddenNeurons,numOutputNeurons))print('nThe shape of weight matrix between the hidden layer and output layer is: ',weightsHiddenOutput.shape)
biasHidden = np.random.uniform(size=(1,numHiddenNeurons))
print('nThe shape of bias matrix of hidden layer: ',biasHidden.shape)
biasOutput = np.random.uniform(size=(1,numOutputNeurons))
print('nThe shape of bias matrix of output layer is: ',biasOutput.shape)
# Define useful functionsdef sigmoid(x): return 1/(1 + np.exp(-x))
# Definition of the derivative of sigmoid function with switch between original and efficient
def derivative_sigmoid(x, original = False):
return x * (1 - x)
if(original == True):
return sigmoid(x) * (1 - sigmoid(x))
# Define training parameters
epochs = 8000
lr = 1
# Start training
for epoch in range(epochs):
# Forward Propagation
hiddenIn = np.dot(X, weightsInputHidden) + biasHidden # Nx4 x 4x3 + Nx3 = Nx3
hiddenActivation = sigmoid(hiddenIn) # Nx3
outputIn = np.dot(hiddenActivation, weightsHiddenOutput) + biasOutput # Nx3 x 3x1 + Nx1
outputActivation = sigmoid(outputIn) # Nx1
# Error
Error = np.square(y - outputActivation)/2 # Nx1
print('n Error in epoch ', epoch,' is: ', np.mean(Error))
# Back Propagation
E = outputActivation - y # Nx1
derivativeOutput = derivative_sigmoid(outputActivation) # Nx1
#Output --> Hidden
deltaOutput = E * derivativeOutput # Nx1 Hadamard Nx1 = Nx1
# Hidden --> Input
derivativeHidden = derivative_sigmoid(hiddenActivation) # Nx3
deltaHidden = np.dot(deltaOutput, weightsHiddenOutput.T) * derivativeHidden # Nx1 x 1x3 Hadamard Nx3
# Update weights
weightsHiddenOutput -= np.dot(hiddenActivation.T, deltaOutput) * lr # 3xN x Nx1 = 3x1
weightsInputHidden -= np.dot(X.T, deltaHidden) * lr # 4xN x Nx3 = 4x3
# Update biases
biasOutput -= np.sum(deltaOutput, axis=0) * lr
biasHidden -= np.sum(deltaHidden, axis=0) * lr
print('nTraining Accomplished!n', outputActivation)