【吳恩達課後編程作業】01 - 神經網絡和深度學習 - 第四周 - PA1&2 - 一步步搭建多層神經網絡以及應用
聲明
本文參考Kulbear 的 【Building your Deep Neural Network - Step by Step】和【Deep Neural Network - Application】,以及念師的【8. 多層神經網絡代碼實戰】,我基於以上的文章加以自己的理解發表這篇博客,力求讓大家以最輕鬆的姿態理解吳恩達的視頻,如有不妥的地方歡迎大家指正。
本文所使用的資料已上傳到百度網盤【點擊下載】,提取碼:xx1w,請在開始之前下載好所需資料,或者在本文底部copy資料代碼。
【博主使用的python版本:3.6.2】
開始之前
在正式開始之前,我們先來了解一下我們要做什麼。在本次教程中,我們要構建兩個神經網絡,一個是構建兩層的神經網絡,一個是構建多層的神經網絡,多層神經網絡的層數可以自己定義。本次的教程的難度有所提升,但是我會力求深入簡出。在這裏,我們簡單的講一下難點,本文會提到**[LINEAR-> ACTIVATION]轉發函數,比如我有一個多層的神經網絡,結構是輸入層->隱藏層->隱藏層->···->隱藏層->輸出層**,在每一層中,我會首先計算Z = np.dot(W,A) + b
,這叫做【linear_forward】,然後再計算A = relu(Z)
或者 A = sigmoid(Z)
,這叫做【linear_activation_forward】,合併起來就是這一層的計算方法,所以每一層的計算都有兩個步驟,先是計算Z,再計算A,你也可以參照下圖:
我們來說一下步驟:
-
初始化網絡參數
-
前向傳播
2.1 計算一層的中線性求和的部分
2.2 計算激活函數的部分(ReLU使用L-1次,Sigmod使用1次)
2.3 結合線性求和與激活函數
-
計算誤差
-
反向傳播
4.1 線性部分的反向傳播公式
4.2 激活函數部分的反向傳播公式
4.3 結合線性部分與激活函數的反向傳播公式
-
更新參數
請注意,對於每個前向函數,都有一個相應的後向函數。 這就是爲什麼在我們的轉發模塊的每一步都會在cache中存儲一些值,cache的值對計算梯度很有用, 在反向傳播模塊中,我們將使用cache來計算梯度。 現在我們正式開始分別構建兩層神經網絡和多層神經網絡。
準備軟件包
在開始我們需要準備一些軟件包:
import numpy as np
import h5py
import matplotlib.pyplot as plt
import testCases #參見資料包,或者在文章底部copy
from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward #參見資料包
import lr_utils #參見資料包,或者在文章底部copy
軟件包準備好了,我們開始構建初始化參數的函數。
爲了和我的數據匹配,你需要指定隨機種子
np.random.seed(1)
初始化參數
對於一個兩層的神經網絡結構而言,模型結構是線性->ReLU->線性->sigmod函數。
初始化函數如下:
def initialize_parameters(n_x,n_h,n_y):
"""
此函數是爲了初始化兩層網絡參數而使用的函數。
參數:
n_x - 輸入層節點數量
n_h - 隱藏層節點數量
n_y - 輸出層節點數量
返回:
parameters - 包含你的參數的python字典:
W1 - 權重矩陣,維度爲(n_h,n_x)
b1 - 偏向量,維度爲(n_h,1)
W2 - 權重矩陣,維度爲(n_y,n_h)
b2 - 偏向量,維度爲(n_y,1)
"""
W1 = np.random.randn(n_h, n_x) * 0.01
b1 = np.zeros((n_h, 1))
W2 = np.random.randn(n_y, n_h) * 0.01
b2 = np.zeros((n_y, 1))
#使用斷言確保我的數據格式是正確的
assert(W1.shape == (n_h, n_x))
assert(b1.shape == (n_h, 1))
assert(W2.shape == (n_y, n_h))
assert(b2.shape == (n_y, 1))
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
初始化完成我們來測試一下:
print("==============測試initialize_parameters==============")
parameters = initialize_parameters(3,2,1)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
測試結果:
==============測試initialize_parameters==============
W1 = [[ 0.01624345 -0.00611756 -0.00528172]
[-0.01072969 0.00865408 -0.02301539]]
b1 = [[ 0.]
[ 0.]]
W2 = [[ 0.01744812 -0.00761207]]
b2 = [[ 0.]]
兩層的神經網絡測試已經完畢了,那麼對於一個L層的神經網絡而言呢?初始化會是什麼樣的?
假設X(輸入數據)的維度爲(12288,209):
<tr>
<td> </td>
<td> W的維度 </td>
<td> b的維度 </td>
<td> 激活值的計算</td>
<td> 激活值的維度</td>
<tr>
<tr>
<td> 第 1 層 </td>
<td> $(n^{[1]},12288)$ </td>
<td> $(n^{[1]},1)$ </td>
<td> $Z^{[1]} = W^{[1]} X + b^{[1]} $ </td>
<td> $(n^{[1]},209)$ </td>
<tr>
<tr>
<td> 第 2 層 </td>
<td> $(n^{[2]}, n^{[1]})$ </td>
<td> $(n^{[2]},1)$ </td>
<td>$Z^{[2]} = W^{[2]} A^{[1]} + b^{[2]}$ </td>
<td> $(n^{[2]}, 209)$ </td>
<tr>
<tr>
<td> $\vdots$ </td>
<td> $\vdots$ </td>
<td> $\vdots$ </td>
<td> $\vdots$</td>
<td> $\vdots$ </td>
<tr>
當然,矩陣的計算方法還是要說一下的:
如果要計算 的話,計算方法是這樣的:
在實際中,也不需要你去做這麼複雜的運算,我們來看一下它是怎樣計算的吧:
def initialize_parameters_deep(layers_dims):
"""
此函數是爲了初始化多層網絡參數而使用的函數。
參數:
layers_dims - 包含我們網絡中每個圖層的節點數量的列表
返回:
parameters - 包含參數“W1”,“b1”,...,“WL”,“bL”的字典:
W1 - 權重矩陣,維度爲(layers_dims [1],layers_dims [1-1])
bl - 偏向量,維度爲(layers_dims [1],1)
"""
np.random.seed(3)
parameters = {}
L = len(layers_dims)
for l in range(1,L):
parameters["W" + str(l)] = np.random.randn(layers_dims[l], layers_dims[l - 1]) / np.sqrt(layers_dims[l - 1])
parameters["b" + str(l)] = np.zeros((layers_dims[l], 1))
#確保我要的數據的格式是正確的
assert(parameters["W" + str(l)].shape == (layers_dims[l], layers_dims[l-1]))
assert(parameters["b" + str(l)].shape == (layers_dims[l], 1))
return parameters
測試一下:
#測試initialize_parameters_deep
print("==============測試initialize_parameters_deep==============")
layers_dims = [5,4,3]
parameters = initialize_parameters_deep(layers_dims)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
測試結果:
==============測試initialize_parameters_deep==============
W1 = [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]
[-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]
[-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]
[-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]
b1 = [[ 0.]
[ 0.]
[ 0.]
[ 0.]]
W2 = [[-0.01185047 -0.0020565 0.01486148 0.00236716]
[-0.01023785 -0.00712993 0.00625245 -0.00160513]
[-0.00768836 -0.00230031 0.00745056 0.01976111]]
b2 = [[ 0.]
[ 0.]
[ 0.]]
我們分別構建了兩層和多層神經網絡的初始化參數的函數,現在我們開始構建前向傳播函數。
前向傳播函數
前向傳播有以下三個步驟
- LINEAR
- LINEAR - >ACTIVATION,其中激活函數將會使用ReLU或Sigmoid。
- [LINEAR - > RELU] ×(L-1) - > LINEAR - > SIGMOID(整個模型)
線性正向傳播模塊(向量化所有示例)使用公式(3)進行計算:
線性部分【LINEAR】
前向傳播中,線性部分計算如下:
def linear_forward(A,W,b):
"""
實現前向傳播的線性部分。
參數:
A - 來自上一層(或輸入數據)的激活,維度爲(上一層的節點數量,示例的數量)
W - 權重矩陣,numpy數組,維度爲(當前圖層的節點數量,前一圖層的節點數量)
b - 偏向量,numpy向量,維度爲(當前圖層節點數量,1)
返回:
Z - 激活功能的輸入,也稱爲預激活參數
cache - 一個包含“A”,“W”和“b”的字典,存儲這些變量以有效地計算後向傳遞
"""
Z = np.dot(W,A) + b
assert(Z.shape == (W.shape[0],A.shape[1]))
cache = (A,W,b)
return Z,cache
測試一下線性部分:
#測試linear_forward
print("==============測試linear_forward==============")
A,W,b = testCases.linear_forward_test_case()
Z,linear_cache = linear_forward(A,W,b)
print("Z = " + str(Z))
測試結果:
==============測試linear_forward==============
Z = [[ 3.26295337 -1.23429987]]
我們前向傳播的單層計算完成了一半啦!我們來開始構建後半部分,如果你不知道我在說啥,請往上翻到【開始之前】仔細看看吧~
線性激活部分【LINEAR - >ACTIVATION】
爲了更方便,我們將把兩個功能(線性和激活)分組爲一個功能(LINEAR-> ACTIVATION)。 因此,我們將實現一個執行LINEAR前進步驟,然後執行ACTIVATION前進步驟的功能。我們來看看這激活函數的數學實現吧~
- Sigmoid:
- ReLU:
我們爲了實現LINEAR->ACTIVATION這個步驟, 使用的公式是:,其中,函數g會是sigmoid() 或者是 relu(),當然,sigmoid()只在輸出層使用,現在我們正式構建前向線性激活部分。
def linear_activation_forward(A_prev,W,b,activation):
"""
實現LINEAR-> ACTIVATION 這一層的前向傳播
參數:
A_prev - 來自上一層(或輸入層)的激活,維度爲(上一層的節點數量,示例數)
W - 權重矩陣,numpy數組,維度爲(當前層的節點數量,前一層的大小)
b - 偏向量,numpy陣列,維度爲(當前層的節點數量,1)
activation - 選擇在此層中使用的激活函數名,字符串類型,【"sigmoid" | "relu"】
返回:
A - 激活函數的輸出,也稱爲激活後的值
cache - 一個包含“linear_cache”和“activation_cache”的字典,我們需要存儲它以有效地計算後向傳遞
"""
if activation == "sigmoid":
Z, linear_cache = linear_forward(A_prev, W, b)
A, activation_cache = sigmoid(Z)
elif activation == "relu":
Z, linear_cache = linear_forward(A_prev, W, b)
A, activation_cache = relu(Z)
assert(A.shape == (W.shape[0],A_prev.shape[1]))
cache = (linear_cache,activation_cache)
return A,cache
測試一下:
#測試linear_activation_forward
print("==============測試linear_activation_forward==============")
A_prev, W,b = testCases.linear_activation_forward_test_case()
A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "sigmoid")
print("sigmoid,A = " + str(A))
A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "relu")
print("ReLU,A = " + str(A))
測試結果:
==============測試linear_activation_forward==============
sigmoid,A = [[ 0.96890023 0.11013289]]
ReLU,A = [[ 3.43896131 0. ]]
我們把兩層模型需要的前向傳播函數做完了,那多層網絡模型的前向傳播是怎樣的呢?我們調用上面的那兩個函數來實現它,爲了在實現L層神經網絡時更加方便,我們需要一個函數來複制前一個函數(帶有RELU的linear_activation_forward)L-1次,然後用一個帶有SIGMOID的linear_activation_forward跟蹤它,我們來看一下它的結構是怎樣的:
在下面的代碼中,AL
表示. (也可稱作 Yhat
,數學表示爲 .)
多層模型的前向傳播計算模型代碼如下:
def L_model_forward(X,parameters):
"""
實現[LINEAR-> RELU] *(L-1) - > LINEAR-> SIGMOID計算前向傳播,也就是多層網絡的前向傳播,爲後面每一層都執行LINEAR和ACTIVATION
參數:
X - 數據,numpy數組,維度爲(輸入節點數量,示例數)
parameters - initialize_parameters_deep()的輸出
返回:
AL - 最後的激活值
caches - 包含以下內容的緩存列表:
linear_relu_forward()的每個cache(有L-1個,索引爲從0到L-2)
linear_sigmoid_forward()的cache(只有一個,索引爲L-1)
"""
caches = []
A = X
L = len(parameters) // 2
for l in range(1,L):
A_prev = A
A, cache = linear_activation_forward(A_prev, parameters['W' + str(l)], parameters['b' + str(l)], "relu")
caches.append(cache)
AL, cache = linear_activation_forward(A, parameters['W' + str(L)], parameters['b' + str(L)], "sigmoid")
caches.append(cache)
assert(AL.shape == (1,X.shape[1]))
return AL,caches
測試一下:
#測試L_model_forward
print("==============測試L_model_forward==============")
X,parameters = testCases.L_model_forward_test_case()
AL,caches = L_model_forward(X,parameters)
print("AL = " + str(AL))
print("caches 的長度爲 = " + str(len(caches)))
測試結果:
==============測試L_model_forward==============
AL = [[ 0.17007265 0.2524272 ]]
caches 的長度爲 = 2
計算成本
我們已經把這兩個模型的前向傳播部分完成了,我們需要計算成本(誤差),以確定它到底有沒有在學習,成本的計算公式如下:
def compute_cost(AL,Y):
"""
實施等式(4)定義的成本函數。
參數:
AL - 與標籤預測相對應的概率向量,維度爲(1,示例數量)
Y - 標籤向量(例如:如果不是貓,則爲0,如果是貓則爲1),維度爲(1,數量)
返回:
cost - 交叉熵成本
"""
m = Y.shape[1]
cost = -np.sum(np.multiply(np.log(AL),Y) + np.multiply(np.log(1 - AL), 1 - Y)) / m
cost = np.squeeze(cost)
assert(cost.shape == ())
return cost
測試一下:
#測試compute_cost
print("==============測試compute_cost==============")
Y,AL = testCases.compute_cost_test_case()
print("cost = " + str(compute_cost(AL, Y)))
測試結果:
==============測試compute_cost==============
cost = 0.414931599615
我們已經把誤差值計算出來了,現在開始進行反向傳播
反向傳播
反向傳播用於計算相對於參數的損失函數的梯度,我們來看看向前和向後傳播的流程圖:
流程圖有了,我們再來看一看對於線性的部分的公式:
我們需要使用來計算三個輸出 ,下面三個公式是我們要用到的:
與前向傳播類似,我們有需要使用三個步驟來構建反向傳播:
- LINEAR 後向計算
- LINEAR -> ACTIVATION 後向計算,其中ACTIVATION 計算Relu或者Sigmoid 的結果
- [LINEAR -> RELU] (L-1) -> LINEAR -> SIGMOID 後向計算 (整個模型)
線性部分【LINEAR backward】
我們來實現後向傳播線性部分:
def linear_backward(dZ,cache):
"""
爲單層實現反向傳播的線性部分(第L層)
參數:
dZ - 相對於(當前第l層的)線性輸出的成本梯度
cache - 來自當前層前向傳播的值的元組(A_prev,W,b)
返回:
dA_prev - 相對於激活(前一層l-1)的成本梯度,與A_prev維度相同
dW - 相對於W(當前層l)的成本梯度,與W的維度相同
db - 相對於b(當前層l)的成本梯度,與b維度相同
"""
A_prev, W, b = cache
m = A_prev.shape[1]
dW = np.dot(dZ, A_prev.T) / m
db = np.sum(dZ, axis=1, keepdims=True) / m
dA_prev = np.dot(W.T, dZ)
assert (dA_prev.shape == A_prev.shape)
assert (dW.shape == W.shape)
assert (db.shape == b.shape)
return dA_prev, dW, db
測試一下:
#測試linear_backward
print("==============測試linear_backward==============")
dZ, linear_cache = testCases.linear_backward_test_case()
dA_prev, dW, db = linear_backward(dZ, linear_cache)
print ("dA_prev = "+ str(dA_prev))
print ("dW = " + str(dW))
print ("db = " + str(db))
測試結果:
==============測試linear_backward==============
dA_prev = [[ 0.51822968 -0.19517421]
[-0.40506361 0.15255393]
[ 2.37496825 -0.89445391]]
dW = [[-0.10076895 1.40685096 1.64992505]]
db = [[ 0.50629448]]
線性激活部分【LINEAR -> ACTIVATION backward】
爲了幫助你實現linear_activation_backward,我們提供了兩個後向函數:
sigmoid_backward
:實現了sigmoid()函數的反向傳播,你可以這樣調用它:
dZ = sigmoid_backward(dA, activation_cache)
relu_backward
: 實現了relu()函數的反向傳播,你可以這樣調用它:
dZ = relu_backward(dA, activation_cache)
如果 是激活函數, 那麼sigmoid_backward
和 relu_backward
這樣計算:
.
我們先在正式開始實現後向線性激活:
def linear_activation_backward(dA,cache,activation="relu"):
"""
實現LINEAR-> ACTIVATION層的後向傳播。
參數:
dA - 當前層l的激活後的梯度值
cache - 我們存儲的用於有效計算反向傳播的值的元組(值爲linear_cache,activation_cache)
activation - 要在此層中使用的激活函數名,字符串類型,【"sigmoid" | "relu"】
返回:
dA_prev - 相對於激活(前一層l-1)的成本梯度值,與A_prev維度相同
dW - 相對於W(當前層l)的成本梯度值,與W的維度相同
db - 相對於b(當前層l)的成本梯度值,與b的維度相同
"""
linear_cache, activation_cache = cache
if activation == "relu":
dZ = relu_backward(dA, activation_cache)
dA_prev, dW, db = linear_backward(dZ, linear_cache)
elif activation == "sigmoid":
dZ = sigmoid_backward(dA, activation_cache)
dA_prev, dW, db = linear_backward(dZ, linear_cache)
return dA_prev,dW,db
測試一下:
#測試linear_activation_backward
print("==============測試linear_activation_backward==============")
AL, linear_activation_cache = testCases.linear_activation_backward_test_case()
dA_prev, dW, db = linear_activation_backward(AL, linear_activation_cache, activation = "sigmoid")
print ("sigmoid:")
print ("dA_prev = "+ str(dA_prev))
print ("dW = " + str(dW))
print ("db = " + str(db) + "\n")
dA_prev, dW, db = linear_activation_backward(AL, linear_activation_cache, activation = "relu")
print ("relu:")
print ("dA_prev = "+ str(dA_prev))
print ("dW = " + str(dW))
print ("db = " + str(db))
測試結果:
==============測試linear_activation_backward==============
sigmoid:
dA_prev = [[ 0.11017994 0.01105339]
[ 0.09466817 0.00949723]
[-0.05743092 -0.00576154]]
dW = [[ 0.10266786 0.09778551 -0.01968084]]
db = [[-0.05729622]]
relu:
dA_prev = [[ 0.44090989 -0. ]
[ 0.37883606 -0. ]
[-0.2298228 0. ]]
dW = [[ 0.44513824 0.37371418 -0.10478989]]
db = [[-0.20837892]]
我們已經把兩層模型的後向計算完成了,對於多層模型我們也需要這兩個函數來完成,我們來看一下流程圖:
在之前的前向計算中,我們存儲了一些包含包含(X,W,b和z)的cache,在犯下那個船舶中,我們將會使用它們來計算梯度值,所以,在L層模型中,我們需要從L層遍歷所有的隱藏層,在每一步中,我們需要使用那一層的cache值來進行反向傳播。
上面我們提到了,它屬於輸出層,,所以我們需要計算dAL,我們可以使用下面的代碼來計算它:
dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))
計算完了以後,我們可以使用此激活後的梯度dAL繼續向後計算,我們這就開始構建多層模型向後傳播函數:
def L_model_backward(AL,Y,caches):
"""
對[LINEAR-> RELU] *(L-1) - > LINEAR - > SIGMOID組執行反向傳播,就是多層網絡的向後傳播
參數:
AL - 概率向量,正向傳播的輸出(L_model_forward())
Y - 標籤向量(例如:如果不是貓,則爲0,如果是貓則爲1),維度爲(1,數量)
caches - 包含以下內容的cache列表:
linear_activation_forward("relu")的cache,不包含輸出層
linear_activation_forward("sigmoid")的cache
返回:
grads - 具有梯度值的字典
grads [“dA”+ str(l)] = ...
grads [“dW”+ str(l)] = ...
grads [“db”+ str(l)] = ...
"""
grads = {}
L = len(caches)
m = AL.shape[1]
Y = Y.reshape(AL.shape)
dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))
current_cache = caches[L-1]
grads["dA" + str(L)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, "sigmoid")
for l in reversed(range(L-1)):
current_cache = caches[l]
dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 2)], current_cache, "relu")
grads["dA" + str(l + 1)] = dA_prev_temp
grads["dW" + str(l + 1)] = dW_temp
grads["db" + str(l + 1)] = db_temp
return grads
測試一下:
#測試L_model_backward
print("==============測試L_model_backward==============")
AL, Y_assess, caches = testCases.L_model_backward_test_case()
grads = L_model_backward(AL, Y_assess, caches)
print ("dW1 = "+ str(grads["dW1"]))
print ("db1 = "+ str(grads["db1"]))
print ("dA1 = "+ str(grads["dA1"]))
測試結果:
==============測試L_model_backward==============
dW1 = [[ 0.41010002 0.07807203 0.13798444 0.10502167]
[ 0. 0. 0. 0. ]
[ 0.05283652 0.01005865 0.01777766 0.0135308 ]]
db1 = [[-0.22007063]
[ 0. ]
[-0.02835349]]
dA1 = [[ 0. 0.52257901]
[ 0. -0.3269206 ]
[ 0. -0.32070404]
[ 0. -0.74079187]]
更新參數
我們把向前向後傳播都完成了,現在我們就開始更新參數,當然,我們來看看更新參數的公式吧~
其中 是學習率。
def update_parameters(parameters, grads, learning_rate):
"""
使用梯度下降更新參數
參數:
parameters - 包含你的參數的字典
grads - 包含梯度值的字典,是L_model_backward的輸出
返回:
parameters - 包含更新參數的字典
參數[“W”+ str(l)] = ...
參數[“b”+ str(l)] = ...
"""
L = len(parameters) // 2 #整除
for l in range(L):
parameters["W" + str(l + 1)] = parameters["W" + str(l + 1)] - learning_rate * grads["dW" + str(l + 1)]
parameters["b" + str(l + 1)] = parameters["b" + str(l + 1)] - learning_rate * grads["db" + str(l + 1)]
return parameters
測試一下:
#測試update_parameters
print("==============測試update_parameters==============")
parameters, grads = testCases.update_parameters_test_case()
parameters = update_parameters(parameters, grads, 0.1)
print ("W1 = "+ str(parameters["W1"]))
print ("b1 = "+ str(parameters["b1"]))
print ("W2 = "+ str(parameters["W2"]))
print ("b2 = "+ str(parameters["b2"]))
測試結果:
==============測試update_parameters==============
W1 = [[-0.59562069 -0.09991781 -2.14584584 1.82662008]
[-1.76569676 -0.80627147 0.51115557 -1.18258802]
[-1.0535704 -0.86128581 0.68284052 2.20374577]]
b1 = [[-0.04659241]
[-1.28888275]
[ 0.53405496]]
W2 = [[-0.55569196 0.0354055 1.32964895]]
b2 = [[-0.84610769]]
至此爲止,我們已經實現該神經網絡中所有需要的函數。接下來,我們將這些方法組合在一起,構成一個神經網絡類,可以方便的使用。
搭建兩層神經網絡
一個兩層的神經網絡模型圖如下:
我們正式開始構建兩層的神經網絡:
def two_layer_model(X,Y,layers_dims,learning_rate=0.0075,num_iterations=3000,print_cost=False,isPlot=True):
"""
實現一個兩層的神經網絡,【LINEAR->RELU】 -> 【LINEAR->SIGMOID】
參數:
X - 輸入的數據,維度爲(n_x,例子數)
Y - 標籤,向量,0爲非貓,1爲貓,維度爲(1,數量)
layers_dims - 層數的向量,維度爲(n_y,n_h,n_y)
learning_rate - 學習率
num_iterations - 迭代的次數
print_cost - 是否打印成本值,每100次打印一次
isPlot - 是否繪製出誤差值的圖譜
返回:
parameters - 一個包含W1,b1,W2,b2的字典變量
"""
np.random.seed(1)
grads = {}
costs = []
(n_x,n_h,n_y) = layers_dims
"""
初始化參數
"""
parameters = initialize_parameters(n_x, n_h, n_y)
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
"""
開始進行迭代
"""
for i in range(0,num_iterations):
#前向傳播
A1, cache1 = linear_activation_forward(X, W1, b1, "relu")
A2, cache2 = linear_activation_forward(A1, W2, b2, "sigmoid")
#計算成本
cost = compute_cost(A2,Y)
#後向傳播
##初始化後向傳播
dA2 = - (np.divide(Y, A2) - np.divide(1 - Y, 1 - A2))
##向後傳播,輸入:“dA2,cache2,cache1”。 輸出:“dA1,dW2,db2;還有dA0(未使用),dW1,db1”。
dA1, dW2, db2 = linear_activation_backward(dA2, cache2, "sigmoid")
dA0, dW1, db1 = linear_activation_backward(dA1, cache1, "relu")
##向後傳播完成後的數據保存到grads
grads["dW1"] = dW1
grads["db1"] = db1
grads["dW2"] = dW2
grads["db2"] = db2
#更新參數
parameters = update_parameters(parameters,grads,learning_rate)
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
#打印成本值,如果print_cost=False則忽略
if i % 100 == 0:
#記錄成本
costs.append(cost)
#是否打印成本值
if print_cost:
print("第", i ,"次迭代,成本值爲:" ,np.squeeze(cost))
#迭代完成,根據條件繪製圖
if isPlot:
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
#返回parameters
return parameters
我們現在開始加載數據集,圖像數據集的處理可以參照:【中文】【吳恩達課後編程作業】Course 1 - 神經網絡和深度學習 - 第二週作業,就連數據集也是一樣的。
train_set_x_orig , train_set_y , test_set_x_orig , test_set_y , classes = lr_utils.load_dataset()
train_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
test_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
train_x = train_x_flatten / 255
train_y = train_set_y
test_x = test_x_flatten / 255
test_y = test_set_y
數據集加載完成,開始正式訓練:
n_x = 12288
n_h = 7
n_y = 1
layers_dims = (n_x,n_h,n_y)
parameters = two_layer_model(train_x, train_set_y, layers_dims = (n_x, n_h, n_y), num_iterations = 2500, print_cost=True,isPlot=True)
訓練結果:
第 0 次迭代,成本值爲: 0.69304973566
第 100 次迭代,成本值爲: 0.646432095343
第 200 次迭代,成本值爲: 0.632514064791
第 300 次迭代,成本值爲: 0.601502492035
第 400 次迭代,成本值爲: 0.560196631161
第 500 次迭代,成本值爲: 0.515830477276
第 600 次迭代,成本值爲: 0.475490131394
第 700 次迭代,成本值爲: 0.433916315123
第 800 次迭代,成本值爲: 0.40079775362
第 900 次迭代,成本值爲: 0.358070501132
第 1000 次迭代,成本值爲: 0.339428153837
第 1100 次迭代,成本值爲: 0.30527536362
第 1200 次迭代,成本值爲: 0.274913772821
第 1300 次迭代,成本值爲: 0.246817682106
第 1400 次迭代,成本值爲: 0.198507350375
第 1500 次迭代,成本值爲: 0.174483181126
第 1600 次迭代,成本值爲: 0.170807629781
第 1700 次迭代,成本值爲: 0.113065245622
第 1800 次迭代,成本值爲: 0.0962942684594
第 1900 次迭代,成本值爲: 0.0834261795973
第 2000 次迭代,成本值爲: 0.0743907870432
第 2100 次迭代,成本值爲: 0.0663074813227
第 2200 次迭代,成本值爲: 0.0591932950104
第 2300 次迭代,成本值爲: 0.0533614034856
第 2400 次迭代,成本值爲: 0.0485547856288
迭代完成之後我們就可以進行預測了,預測函數如下:
def predict(X, y, parameters):
"""
該函數用於預測L層神經網絡的結果,當然也包含兩層
參數:
X - 測試集
y - 標籤
parameters - 訓練模型的參數
返回:
p - 給定數據集X的預測
"""
m = X.shape[1]
n = len(parameters) // 2 # 神經網絡的層數
p = np.zeros((1,m))
#根據參數前向傳播
probas, caches = L_model_forward(X, parameters)
for i in range(0, probas.shape[1]):
if probas[0,i] > 0.5:
p[0,i] = 1
else:
p[0,i] = 0
print("準確度爲: " + str(float(np.sum((p == y))/m)))
return p
預測函數構建好了我們就開始預測,查看訓練集和測試集的準確性:
predictions_train = predict(train_x, train_y, parameters) #訓練集
predictions_test = predict(test_x, test_y, parameters) #測試集
預測結果:
準確度爲: 1.0
準確度爲: 0.72
這樣看來,我的測試集的準確度要比上一次(【中文】【吳恩達課後編程作業】Course 1 - 神經網絡和深度學習 - 第二週作業)高一些,上次的是70%,這次是72%,那如果我使用更多層的聖經網絡呢?
搭建多層神經網絡
我們首先來看看多層的網絡的結構吧~
def L_layer_model(X, Y, layers_dims, learning_rate=0.0075, num_iterations=3000, print_cost=False,isPlot=True):
"""
實現一個L層神經網絡:[LINEAR-> RELU] *(L-1) - > LINEAR-> SIGMOID。
參數:
X - 輸入的數據,維度爲(n_x,例子數)
Y - 標籤,向量,0爲非貓,1爲貓,維度爲(1,數量)
layers_dims - 層數的向量,維度爲(n_y,n_h,···,n_h,n_y)
learning_rate - 學習率
num_iterations - 迭代的次數
print_cost - 是否打印成本值,每100次打印一次
isPlot - 是否繪製出誤差值的圖譜
返回:
parameters - 模型學習的參數。 然後他們可以用來預測。
"""
np.random.seed(1)
costs = []
parameters = initialize_parameters_deep(layers_dims)
for i in range(0,num_iterations):
AL , caches = L_model_forward(X,parameters)
cost = compute_cost(AL,Y)
grads = L_model_backward(AL,Y,caches)
parameters = update_parameters(parameters,grads,learning_rate)
#打印成本值,如果print_cost=False則忽略
if i % 100 == 0:
#記錄成本
costs.append(cost)
#是否打印成本值
if print_cost:
print("第", i ,"次迭代,成本值爲:" ,np.squeeze(cost))
#迭代完成,根據條件繪製圖
if isPlot:
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
return parameters
我們現在開始加載數據集,圖像數據集的處理可以參照:【中文】【吳恩達課後編程作業】Course 1 - 神經網絡和深度學習 - 第二週作業,就連數據集也是一樣的。
train_set_x_orig , train_set_y , test_set_x_orig , test_set_y , classes = lr_utils.load_dataset()
train_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
test_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
train_x = train_x_flatten / 255
train_y = train_set_y
test_x = test_x_flatten / 255
test_y = test_set_y
數據集加載完成,開始正式訓練:
layers_dims = [12288, 20, 7, 5, 1] # 5-layer model
parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 2500, print_cost = True,isPlot=True)
訓練結果:
第 0 次迭代,成本值爲: 0.715731513414
第 100 次迭代,成本值爲: 0.674737759347
第 200 次迭代,成本值爲: 0.660336543362
第 300 次迭代,成本值爲: 0.646288780215
第 400 次迭代,成本值爲: 0.629813121693
第 500 次迭代,成本值爲: 0.606005622927
第 600 次迭代,成本值爲: 0.569004126398
第 700 次迭代,成本值爲: 0.519796535044
第 800 次迭代,成本值爲: 0.464157167863
第 900 次迭代,成本值爲: 0.408420300483
第 1000 次迭代,成本值爲: 0.373154992161
第 1100 次迭代,成本值爲: 0.30572374573
第 1200 次迭代,成本值爲: 0.268101528477
第 1300 次迭代,成本值爲: 0.238724748277
第 1400 次迭代,成本值爲: 0.206322632579
第 1500 次迭代,成本值爲: 0.179438869275
第 1600 次迭代,成本值爲: 0.157987358188
第 1700 次迭代,成本值爲: 0.142404130123
第 1800 次迭代,成本值爲: 0.128651659979
第 1900 次迭代,成本值爲: 0.112443149982
第 2000 次迭代,成本值爲: 0.0850563103497
第 2100 次迭代,成本值爲: 0.0575839119861
第 2200 次迭代,成本值爲: 0.044567534547
第 2300 次迭代,成本值爲: 0.038082751666
第 2400 次迭代,成本值爲: 0.0344107490184
訓練完成,我們看一下預測:
pred_train = predict(train_x, train_y, parameters) #訓練集
pred_test = predict(test_x, test_y, parameters) #測試集
預測結果:
準確度爲: 0.9952153110047847
準確度爲: 0.78
就準確度而言,從70%到72%再到78%,可以看到的是準確度在一點點增加,當然,你也可以手動的去調整layers_dims,準確度可能又會提高一些。
分析
我們可以看一看有哪些東西在L層模型中被錯誤地標記了,導致準確率沒有提高。
def print_mislabeled_images(classes, X, y, p):
"""
繪製預測和實際不同的圖像。
X - 數據集
y - 實際的標籤
p - 預測
"""
a = p + y
mislabeled_indices = np.asarray(np.where(a == 1))
plt.rcParams['figure.figsize'] = (40.0, 40.0) # set default size of plots
num_images = len(mislabeled_indices[0])
for i in range(num_images):
index = mislabeled_indices[1][i]
plt.subplot(2, num_images, i + 1)
plt.imshow(X[:,index].reshape(64,64,3), interpolation='nearest')
plt.axis('off')
plt.title("Prediction: " + classes[int(p[0,index])].decode("utf-8") + " \n Class: " + classes[y[0,index]].decode("utf-8"))
print_mislabeled_images(classes, test_x, test_y, pred_test)
運行結果:
分析一下我們就可以得知原因了:
模型往往表現欠佳的幾種類型的圖像包括:
- 貓身體在一個不同的位置
- 貓出現在相似顏色的背景下
- 不同的貓的顏色和品種
- 相機角度
- 圖片的亮度
- 比例變化(貓的圖像非常大或很小)
【選做】
我們使用自己圖片試試?
我們把一張圖片放在一個特定位置,然後識別它。
## START CODE HERE ##
my_image = "my_image.jpg" # change this to the name of your image file
my_label_y = [1] # the true class of your image (1 -> cat, 0 -> non-cat)
## END CODE HERE ##
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((num_px*num_px*3,1))
my_predicted_image = predict(my_image, my_label_y, parameters)
plt.imshow(image)
print ("y = " + str(np.squeeze(my_predicted_image)) + ", your L-layer model predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.")
運行結果:
準確度: 1.0
y = 1.0, your L-layer model predicts a "cat" picture.
相關庫代碼
lr_utils.py
# lr_utils.py
import numpy as np
import h5py
def load_dataset():
train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")
train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features
train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels
test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r")
test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features
test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels
classes = np.array(test_dataset["list_classes"][:]) # the list of classes
train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes
dnn_utils.py
# dnn_utils.py
import numpy as np
def sigmoid(Z):
"""
Implements the sigmoid activation in numpy
Arguments:
Z -- numpy array of any shape
Returns:
A -- output of sigmoid(z), same shape as Z
cache -- returns Z as well, useful during backpropagation
"""
A = 1/(1+np.exp(-Z))
cache = Z
return A, cache
def sigmoid_backward(dA, cache):
"""
Implement the backward propagation for a single SIGMOID unit.
Arguments:
dA -- post-activation gradient, of any shape
cache -- 'Z' where we store for computing backward propagation efficiently
Returns:
dZ -- Gradient of the cost with respect to Z
"""
Z = cache
s = 1/(1+np.exp(-Z))
dZ = dA * s * (1-s)
assert (dZ.shape == Z.shape)
return dZ
def relu(Z):
"""
Implement the RELU function.
Arguments:
Z -- Output of the linear layer, of any shape
Returns:
A -- Post-activation parameter, of the same shape as Z
cache -- a python dictionary containing "A" ; stored for computing the backward pass efficiently
"""
A = np.maximum(0,Z)
assert(A.shape == Z.shape)
cache = Z
return A, cache
def relu_backward(dA, cache):
"""
Implement the backward propagation for a single RELU unit.
Arguments:
dA -- post-activation gradient, of any shape
cache -- 'Z' where we store for computing backward propagation efficiently
Returns:
dZ -- Gradient of the cost with respect to Z
"""
Z = cache
dZ = np.array(dA, copy=True) # just converting dz to a correct object.
# When z <= 0, you should set dz to 0 as well.
dZ[Z <= 0] = 0
assert (dZ.shape == Z.shape)
return dZ
testCase.py
#testCase.py
import numpy as np
def linear_forward_test_case():
np.random.seed(1)
A = np.random.randn(3,2)
W = np.random.randn(1,3)
b = np.random.randn(1,1)
return A, W, b
def linear_activation_forward_test_case():
np.random.seed(2)
A_prev = np.random.randn(3,2)
W = np.random.randn(1,3)
b = np.random.randn(1,1)
return A_prev, W, b
def L_model_forward_test_case():
np.random.seed(1)
X = np.random.randn(4,2)
W1 = np.random.randn(3,4)
b1 = np.random.randn(3,1)
W2 = np.random.randn(1,3)
b2 = np.random.randn(1,1)
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return X, parameters
def compute_cost_test_case():
Y = np.asarray([[1, 1, 1]])
aL = np.array([[.8,.9,0.4]])
return Y, aL
def linear_backward_test_case():
np.random.seed(1)
dZ = np.random.randn(1,2)
A = np.random.randn(3,2)
W = np.random.randn(1,3)
b = np.random.randn(1,1)
linear_cache = (A, W, b)
return dZ, linear_cache
def linear_activation_backward_test_case():
np.random.seed(2)
dA = np.random.randn(1,2)
A = np.random.randn(3,2)
W = np.random.randn(1,3)
b = np.random.randn(1,1)
Z = np.random.randn(1,2)
linear_cache = (A, W, b)
activation_cache = Z
linear_activation_cache = (linear_cache, activation_cache)
return dA, linear_activation_cache
def L_model_backward_test_case():
np.random.seed(3)
AL = np.random.randn(1, 2)
Y = np.array([[1, 0]])
A1 = np.random.randn(4,2)
W1 = np.random.randn(3,4)
b1 = np.random.randn(3,1)
Z1 = np.random.randn(3,2)
linear_cache_activation_1 = ((A1, W1, b1), Z1)
A2 = np.random.randn(3,2)
W2 = np.random.randn(1,3)
b2 = np.random.randn(1,1)
Z2 = np.random.randn(1,2)
linear_cache_activation_2 = ( (A2, W2, b2), Z2)
caches = (linear_cache_activation_1, linear_cache_activation_2)
return AL, Y, caches
def update_parameters_test_case():
np.random.seed(2)
W1 = np.random.randn(3,4)
b1 = np.random.randn(3,1)
W2 = np.random.randn(1,3)
b2 = np.random.randn(1,1)
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
np.random.seed(3)
dW1 = np.random.randn(3,4)
db1 = np.random.randn(3,1)
dW2 = np.random.randn(1,3)
db2 = np.random.randn(1,1)
grads = {"dW1": dW1,
"db1": db1,
"dW2": dW2,
"db2": db2}
return parameters, grads