1 簡介
如下圖所示,NN 是感知機的升級版,由輸入層,若干隱藏層,輸出層組成。其主要包含前向傳播,反向傳播等過程,下文會逐一分享。
2 前向傳播
2.1 FP流程
與感知機類似,從輸入層到輸出層逐層計算,最後利用損失函數計算擬合誤差。其中,核心就是神經元節點的權值計算,公式如下。
其中, 表示第 層的第 個神經元的輸入; 表示第 層的第 個神經元的輸出; 表示第 層的第 個神經元指向第 層的第 個神經元的權值; 表示第 層的第 個神經元的偏移量, 表示激活函數。
2.2 激活函數
激活函數就是非線性處理單元,常用的有 sigmoid, ReLU, tanh, Leaky ReLU, Softmax等。下表給出了激活函數的曲線圖,等式,梯度值。
2.3 損失函數
損失函數,別名代價函數,目標函數,誤差函數。主要用來度量網絡實際輸出與期望輸出之間的誤差,以便指導網絡的參數學習。針對迴歸問題,一般採用平方損失等;針對分類問題,一般採用對數損失,交叉熵等。不同的損失函數會影響網絡的訓練速度與泛化能力。
-
迴歸問題
平方損失:
絕對值損失:
均方誤差損失: -
二分類問題
例:對於樣本(x,y),x爲樣本,y爲對應的標籤,在二分類問題中,其取值的集合可能爲{0,1}。假設某個樣本的真實標籤爲y,該樣本的 y=1 的概率爲 ,則該樣本的交叉熵損失函數爲:。 -
多分類問題
交叉熵與Softmax結合,如下圖所示。
3 反向傳播
3.1 BP流程
與前向傳播相反,從輸出層回溯到輸入層,根據不同參數的影響更新 NN 的權重與偏移量,最終實現誤差值的最小化。其中,核心就是如何計算不同參數對 NN的影響以及如何更新參數實現誤差最小化。常用的方法是梯度下降算法。下圖舉例說明了此過程。
3.2 梯度下降
梯度下降法是最小化損失函數的一種常用的一階優化方法,前提是凸函數,否則會陷入局部最小值。參數更新公式如下。
其中, 是學習率,值越大學習速度越快,當然不能過大,否則會跳過最優值;過小則訓練成本過高,甚至無法收斂。
3.3 梯度下降訓練策略
常用的有批次梯度下降BGD,隨機梯度下降SGD,小批次梯度下降Mini-batch GD。三者對比圖如下。
-
BGD
利用全部訓練集計算損失函數的梯度來執行一次參數更新。缺點是更新較慢,不能在線更新網絡,對非凸函數一般只能收斂到局部最小值。 -
SGD
對每一個訓練樣本點執行參數更新。優點是速度快,可在線學習;缺點是精度一般,損失函數下降過程波動較大。 -
Mini-batch GD
每n個訓練樣本點執行一次參數更新。優點是平穩收斂,速度快。batch大小一般取32,64,128,256等。
3.4 梯度下降優化算法
梯度下降優化算法一般包括如下幾種,比較常用的是 SGD+Momentum 以及 Adam。
- SGD+Momentum方法最基本,調參較難
- RMSprop和Adadelta是AdaGrad改進方法
- RMSprop、Adadelta和Adam方法性能相近
- Adadelta方法無需設置學習率參數
- NAG方法在RNN網絡中效果顯著
下面介紹一下常用的 SGD+Momentum 以及 Adam。
-
SGD+Momentum
動量用來加速SGD,即將過去更新矢量的一部分加到當前矢量更新,公式如下。
-
Adam
Adam 是一種爲每一個參數計算自適應學習率的方法,即存儲了過去梯度平方的指數衰減均值 ,同時存儲了過去梯度的指數衰減均值 ,類似動量。公式如下。
Adam更新規則如下:
其中,
4 實例
題目:利用NN實現MNIST手寫數字識別。
import numpy as np
from sklearn.datasets import load_digits
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report,confusion_matrix
import matplotlib.pyplot as plt
# 載入數據
digits = load_digits()
print(digits.images.shape)
# 顯示圖片
plt.imshow(digits.images[0],cmap='gray')
plt.show()
(1797, 8, 8)
# 數據
X = digits.data
# 標籤
y = digits.target
print(X.shape)
print(y.shape)
(1797, 64)
(1797,)
# 定義一個NN:64-100-10
# 定義輸入層到隱藏層之間的權值矩陣
V = np.random.random((64,100))*2-1
# 定義隱藏層到輸出層之間的權值矩陣
W = np.random.random((100,10))*2-1
# 數據切分:1/4爲測試集,3/4爲訓練集
X_train,X_test,y_train,y_test = train_test_split(X,y)
# 標籤二值化
labels_train = LabelBinarizer().fit_transform(y_train)
print(y_train[:5])
print(labels_train[:5])
[1 5 5 5 1]
[[0 1 0 0 0 0 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0]
[0 1 0 0 0 0 0 0 0 0]]
# 激活函數
def sigmoid(x):
return 1/(1+np.exp(-x))
# 激活函數的導數,注意此處x=y
def dsigmoid(x):
return x*(1-x)
# 訓練模型
def train(X,y,steps=10000,lr=0.11):
global V,W
for n in range(steps+1):
# 隨機選取一個數據
i = np.random.randint(X.shape[0])
# 獲取一個數據
x = X[i]
x = np.atleast_2d(x) # 變成2維作矩陣運算
# 計算隱藏層的輸出
L1 = sigmoid(np.dot(x,V))
# 計算輸出的輸出
L2 = sigmoid(np.dot(L1,W))
# 計算L2_delta,L1_delta
L2_delta = (y[i]-L2)*dsigmoid(L2)
L1_delta = L2_delta.dot(W.T)*dsigmoid(L1)
# 更新權值
W += lr*L1.T.dot(L2_delta)
V += lr*x.T.dot(L1_delta)
# 每訓練1000次預測一次準確率
if n%1000==0:
output = predict(X_test)
predictions = np.argmax(output,axis=1)
acc = np.mean(np.equal(predictions,y_test))
print('steps:',n,'accuracy:',acc)
# 模型預測
def predict(x):
# 計算隱藏層的輸出
L1 = sigmoid(np.dot(x,V))
# 計算輸出的輸出
L2 = sigmoid(np.dot(L1,W))
return L2
train(X_train,labels_train,30000)
steps: 0 accuracy: 0.08444444444444445
steps: 1000 accuracy: 0.52
steps: 2000 accuracy: 0.64
steps: 3000 accuracy: 0.7222222222222222
steps: 4000 accuracy: 0.7955555555555556
steps: 5000 accuracy: 0.8266666666666667
steps: 6000 accuracy: 0.84
steps: 7000 accuracy: 0.8444444444444444
steps: 8000 accuracy: 0.8555555555555555
steps: 9000 accuracy: 0.8577777777777778
steps: 10000 accuracy: 0.9488888888888889
steps: 11000 accuracy: 0.94
steps: 12000 accuracy: 0.9444444444444444
steps: 13000 accuracy: 0.9622222222222222
steps: 14000 accuracy: 0.9755555555555555
steps: 15000 accuracy: 0.9511111111111111
steps: 16000 accuracy: 0.9688888888888889
steps: 17000 accuracy: 0.9711111111111111
steps: 18000 accuracy: 0.9688888888888889
steps: 19000 accuracy: 0.9755555555555555
steps: 20000 accuracy: 0.9688888888888889
steps: 21000 accuracy: 0.9622222222222222
steps: 22000 accuracy: 0.9666666666666667
steps: 23000 accuracy: 0.9688888888888889
steps: 24000 accuracy: 0.9755555555555555
steps: 25000 accuracy: 0.9733333333333334
steps: 26000 accuracy: 0.9733333333333334
steps: 27000 accuracy: 0.98
steps: 28000 accuracy: 0.9711111111111111
steps: 29000 accuracy: 0.9644444444444444
steps: 30000 accuracy: 0.98
# 查看準確率,召回率,F1
output = predict(X_test)
predictions = np.argmax(output,axis=1)
print(classification_report(predictions,y_test))
precision recall f1-score support
0 1.00 1.00 1.00 43
1 1.00 0.94 0.97 48
2 1.00 0.98 0.99 54
3 0.95 0.98 0.97 43
4 0.96 1.00 0.98 43
5 1.00 0.98 0.99 48
6 1.00 0.98 0.99 41
7 1.00 0.98 0.99 53
8 0.89 0.98 0.93 43
9 1.00 1.00 1.00 34