吳恩達深度學習 第一課第四周課后編程作業 assignment4_1


Building your Deep Neural Network: Step by Step

本文作業是在jupyter notebook上一步一步做的,帶有一些過程中查找的資料等(出處已標明)並翻譯成了中文,如有錯誤,歡迎指正!

歡迎來到第四周作業(第二部分的第一部分)!您之前已經訓練了一個兩層的神經網絡(只有一個隱藏層)。這周,你將構建一個深度神經網絡,你想要多少層就有多少層!

•在本筆記本中,您將實現構建深度神經網絡所需的所有功能(函數)。
•在下一個作業中,你將使用這些函數來建立一個用於圖像分類深度神經網絡。

完成這項任務后,您將能夠:

•使用非線性單元,比如ReLU來改進你的模型
•構建更深層次的神經網絡(隱含層超過1層)
•實現一個易於使用的神經網絡類

符號:

 

 

就是上標的【l】代表第l層,上標的【i】代表第i個樣本,下標的 i 代表第 i 個條目

 

1 - Packages 包

讓我們首先導入在此任務中需要的所有包。

·numpy是使用Python進行科學計算的主要包。
·matplotlib是一個用Python繪制圖形的庫。
·dnn_utils為本筆記本提供了一些必要的函數。
·testCases提供了一些測試用例來評估函數的正確性
·seed(1)用於保持所有隨機函數調用的一致性。它將幫助我們批改你的作業。請不要換種子。

import numpy as np
import h5py #h5py是Python語言用來操作HDF5的模塊。
import matplotlib.pyplot as plt
from testCases_v2 import *
from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward

%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

%load_ext autoreload
%autoreload 2

np.random.seed(1)

python庫——h5py入門講解,來自,鏈接:https://blog.csdn.net/csdn15698845876/article/details/73278120

%load_ext autoreload是什么意思:在執行用戶代碼前,重新裝入 軟件的擴展和模塊。autoreload 意思是自動重新裝入。它后面可帶參數。參數意思你要查你自己的版本幫助文件。一般說:
無參:裝入所有模塊。
0:不執行 裝入命令。
1: 只裝入所有 %aimport 要裝模塊
2:裝入所有 %aimport 不包含的模塊。  

2 - Outline of the Assignment(作業大綱)

要構建神經網絡,您將實現幾個“輔助函數”。這些輔助函數將用於下一個任務,以建立一個兩層神經網絡一個L層神經網絡。您將實現的每個小助手函數都有詳細的說明,這些說明將指導您完成必要的步驟。這是這個作業的大綱,你會:

•初始化一個二層網絡和一個L層神經網絡的參數
•實現轉發模塊(下圖中用紫色顯示)。

  ◾完成一層的線性部分的向前傳播步驟(得到Z [l]

  ◾我們給你激活函數(relu /sigmoid)

  ◾將前兩步驟組合成一個新的函數【線性- >激活轉發】

  ◾堆棧(線性- > RELU)提出時間 L - 1 函數(通過L - 1層1)並添加一個(線性- >sigmoid),最后(最后一層L)。這將為您提供一個新的L_model_forward函數。

•計算損失。

•實現反向傳播模塊(下圖中用紅色表示)。

  ◾完成一層的向后傳播的線性部分的步驟。

  ◾我們給你激活函數的梯度(relu_backward / sigmoid_backward)

  ◾將前兩步驟組合成一個新的線性- >激活 反向功能。

  ◾堆棧(線性- > RELU)向后  並添加l - 1倍(線性- >乙狀結腸)向后一個新的L_model_backward函數

•最后更新參數。

 

 

 **Figure 1**

 

注意,對於每個前向函數,都有一個對應的后向函數。這就是為什么在向前(前向)模塊的每一步都要在緩存中存儲一些值。緩存的值對於計算梯度很有用。在反向傳播模塊中,您將使用緩存計算梯度。這個作業將確切地告訴你如何執行這些步驟中的每一步。

 

 

3 - Initialization 初始化

您將編寫兩個幫助函數初始化模型的參數。第一個函數將用於初始化一個兩層模型的參數。第二種方法將這個初始化過程推廣到L層。

3.1 - 2-layer Neural Network(2層神經網絡)

練習:創建並初始化兩層神經網絡的參數。

說明:

•模型結構為:LINEAR -> RELU -> LINEAR -> SIGMOID。
•對權重矩陣使用隨機初始化。使用np.random.randn(shape)*0.01表示正確的形狀。
•對偏差使用零初始化。使用np.zeros(形狀)。

 1 # GRADED FUNCTION: initialize_parameters
 2 
 3 def initialize_parameters(n_x, n_h, n_y):
 4     """
 5     Argument:
 6     n_x -- size of the input layer
 7     n_h -- size of the hidden layer
 8     n_y -- size of the output layer
 9     
10     Returns:
11     parameters -- python dictionary containing your parameters:
12                     W1 -- weight matrix of shape (n_h, n_x)
13                     b1 -- bias vector of shape (n_h, 1)
14                     W2 -- weight matrix of shape (n_y, n_h)
15                     b2 -- bias vector of shape (n_y, 1)
16     """
17     
18     np.random.seed(1)
19     
20     ### START CODE HERE ### (≈ 4 lines of code)
21     W1 = np.random.randn(n_h, n_x)*0.01
22     b1 = np.zeros((n_h, 1))
23     W2 = np.random.randn(n_y, n_h)*0.01
24     b2 = np.zeros((n_y, 1))
25     ### END CODE HERE ###
26     
27     assert(W1.shape == (n_h, n_x))
28     assert(b1.shape == (n_h, 1))
29     assert(W2.shape == (n_y, n_h))
30     assert(b2.shape == (n_y, 1))
31     
32     parameters = {"W1": W1,
33                   "b1": b1,
34                   "W2": W2,
35                   "b2": b2}
36     
37     return parameters    
# GRADED FUNCTION: initialize_parameters
parameters = initialize_parameters(2,2,1)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

結果:

 

 

 3.2 - L-layer Neural Network L層的神經網絡

更深的L層神經網絡的初始化更加復雜,因為有更多的權值矩陣偏差向量。在完成initialize_parameters_deep時,應該確保各層之間的維度匹配。回想一下,n [l]是 l 層中的單元數。例如,如果我們的輸入X的大小是(12288,209)(m=209個例子)那么:

 

 

 記住,當我們用python計算WX+b時,它執行廣播機制 。例如,如果:

 

 

 

 

 

 

 

 

練習:實現L層神經網絡的初始化。

說明:

•The model’s structure is [LINEAR -> RELU] × (L-1) -> LINEAR -> SIGMOID. I.e., it has L−1 layers using a ReLU activation function followed by an output layer with a sigmoid activation function.
•對權重矩陣使用隨機初始化。使用np.random.rand(shape) * 0.01。

•對偏差使用零初始化。使用np.zeros(形狀)。

•我們將存儲n[l],不同層的單位數量,在一個變量layer_dims中。例如,上周的“平面數據分類模型”的layer_dims應該是[2,4,1]:有兩個輸入,一個隱含層有4個隱含單元,一個輸出層有1個輸出單元。即W1的形狀為(4,2),b1為(4,1),W2為(1,4),b2為(1,1)。現在你可以將它推廣到L層!

•這是L=1(一層神經網絡)的實現。它會啟發你實現一般情況(l層神經網絡)。

if L == 1:
      parameters["W" + str(L)] = np.random.randn(layer_dims[1], layer_dims[0]) * 0.01
      parameters["b" + str(L)] = np.zeros((layer_dims[1], 1))
# GRADED FUNCTION: initialize_parameters_deep

def initialize_parameters_deep(layer_dims):
    """
    Arguments:
    layer_dims -- python array (list) containing the dimensions of each layer in our network
    
    Returns:
    parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
                    Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1])
                    bl -- bias vector of shape (layer_dims[l], 1)
    """
    
    np.random.seed(3)
    parameters = {}
    L = len(layer_dims)            # number of layers in the network

    for l in range(1, L):
        ### START CODE HERE ### (≈ 2 lines of code)
        parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) * 0.01
        parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))
        ### END CODE HERE ###
        
        assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1]))
        assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))

        
    return parameters
# GRADED FUNCTION: initialize_parameters_deep
parameters = initialize_parameters_deep([5,4,3])
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

結果:

 

 

 

 

 

4 - Forward propagation module 前向傳播模塊

4.1 - Linear Forward 線性向前

現在您已經初始化了參數,您將實現向前傳播模塊。您將從實現一些基本功能開始,稍后在實現模型時將使用這些功能。您將按此順序完成三個功能:

•線性
•線性->激活,其中激活為ReLU或Sigmoid。
•[LINEAR -> RELU] * (L-1) -> LINEAR -> SIGMOID(全模型)

線性向前模塊(對所有例子進行矢量化)計算如下方程:Z [l] =W [l] A [l−1]+b [l]              (4)      這里 A [0] =X

練習:建立正向傳播的線性部分。

提示:該單位的數學表示為Z[l]=W[l]A[l−1]+b[l]。您可能還會發現np.dot()很有用。如果尺寸不匹配,打印W的形狀可能會有所幫助。

# GRADED FUNCTION: linear_forward

def linear_forward(A, W, b):
    """
    Implement the linear part of a layer's forward propagation.

    Arguments:
    A -- activations from previous layer (or input data): (size of previous layer, number of examples)
    W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
    b -- bias vector, numpy array of shape (size of the current layer, 1)

    Returns:
    Z -- the input of the activation function, also called pre-activation parameter 
    cache -- a python dictionary containing "A", "W" and "b" ; stored for computing the backward pass efficiently
    """
    
    ### START CODE HERE ### (≈ 1 line of code)
    Z = np.dot(W, A) + b
    ### END CODE HERE ###
    
    assert(Z.shape == (W.shape[0], A.shape[1]))
    cache = (A, W, b)
    
    return Z, cache
# GRADED FUNCTION: linear_forward
A, W, b = linear_forward_test_case()

Z, linear_cache = linear_forward(A, W, b)
print("Z = " + str(Z))

結果:

 

 

 

 

4.2 - Linear-Activation Forward 正向線性激活

在本筆記本中,您將使用兩個激活函數:

Sigmoid:σ(Z) =σ(WA + b) = 。我們已經提供了sigmoid函數。這個函數返回兩個項:激活值“a”包含“Z”的“緩存”(我們將把它輸入到相應的向后函數)。要使用它,你可以打稱呼:

A, activation_cache = sigmoid(Z)

ReLU:ReLu的數學公式為A= ReLu (Z)=max(0,Z)。我們為您提供了relu功能。這個函數返回兩個項:激活值“A”包含“Z”的“緩存”(我們將把它輸入到相應的向后函數)。要使用它,你可以打稱:

A, activation_cache = relu(Z)

為了更方便,將兩個函數(線性和激活)組合為一個函數(線性->激活)。因此,您將實現一個函數,它執行線性向前步驟,然后執行激活向前步驟。

Exercise:實現線性->激活層的正向傳播。數學關系為:A[l]=g(Z[l])=g(W[l]A[l−1]+b[l]),其中活化“g”可以是sigmoid()或relu()。使用linear_forward()和正確的激活函數。

 1 # GRADED FUNCTION: linear_activation_forward
 2 
 3 def linear_activation_forward(A_prev, W, b, activation):
 4     """
 5     Implement the forward propagation for the LINEAR->ACTIVATION layer
 6 
 7     Arguments:
 8     A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)
 9     W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
10     b -- bias vector, numpy array of shape (size of the current layer, 1)
11     activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"
12 
13     Returns:
14     A -- the output of the activation function, also called the post-activation value 
15     cache -- a python dictionary containing "linear_cache" and "activation_cache";
16              stored for computing the backward pass efficiently
17     """
18     
19     if activation == "sigmoid":
20         # Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
21         ### START CODE HERE ### (≈ 2 lines of code)
22         Z, linear_cache = linear_forward(A_prev, W, b) #前面linear_forward已經寫好了
23         A, activation_cache = sigmoid(Z)
24         ### END CODE HERE ###
25     
26     elif activation == "relu":
27         # Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
28         ### START CODE HERE ### (≈ 2 lines of code)
29         Z, linear_cache = linear_forward(A_prev, W, b)
30         A, activation_cache = relu(Z)
31         ### END CODE HERE ###
32     
33     assert (A.shape == (W.shape[0], A_prev.shape[1]))
34     cache = (linear_cache, activation_cache)
35 
36     return A, cache
# GRADED FUNCTION: linear_activation_forward
A_prev, W, b = linear_activation_forward_test_case()

A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "sigmoid")
print("With sigmoid: A = " + str(A))

A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "relu")
print("With ReLU: A = " + str(A))

結果:

 

 

注:在深度學習中,“[LINEAR->ACTIVATION]”計算在神經網絡中被視為單層,而不是兩層。

d) L-Layer Model 層數為L 的模型

在實現L層神經網絡時,為了更加方便,您將需要一個函數復制前一個(RELU的linear_activation_forward) L−1倍,然后再使用一個SIGMOID的linear_activation_forward。

 

 

**Figure 2** : *[LINEAR -> RELU]

練習:實現上述模型的正向傳播。

指令:在下面的代碼中,變量AL將表示A [L]=σ(Z[L])=σ(W[L]A[L−1]+b[L]).有時候這也叫Yhat

提示:

•使用之前編寫的函數
•使用for循環復制[LINEAR->RELU] (L-1)次
•不要忘記跟蹤“緩存”列表中的緩存。要向列表添加新值c,可以使用list.append(c)

 1 # GRADED FUNCTION: L_model_forward
 2 
 3 def L_model_forward(X, parameters):
 4     """
 5     Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation
 6     
 7     Arguments:
 8     X -- data, numpy array of shape (input size, number of examples)
 9     parameters -- output of initialize_parameters_deep()
10     
11     Returns:
12     AL -- last post-activation value
13     caches -- list of caches containing:
14                 every cache of linear_relu_forward() (there are L-1 of them, indexed from 0 to L-2)
15                 the cache of linear_sigmoid_forward() (there is one, indexed L-1)
16     """
17 
18     caches = []
19     A = X
20     L = len(parameters) // 2                  # number of layers in the neural network
21     
22     # Implement [LINEAR -> RELU]*(L-1). Add "cache" to the "caches" list.
23     for l in range(1, L):
24         A_prev = A 
25         ### START CODE HERE ### (≈ 2 lines of code)
26         A, cache = linear_activation_forward(A_prev, parameters['W' + str(l)], parameters['b'+str(l)], activation = "relu")
27         caches.append(cache)
28 
29         ### END CODE HERE ###
30     
31     # Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list.
32     ### START CODE HERE ### (≈ 2 lines of code)
33     AL, cache = linear_activation_forward(A, parameters['W'+str(L)], parameters['b'+str(L)], activation = "sigmoid")
34     caches.append(cache)
35     ### END CODE HERE ###
36     
37     assert(AL.shape == (1,X.shape[1]))
38             
39     return AL, caches
# GRADED FUNCTION: L_model_forward
X, parameters = L_model_forward_test_case()
AL, caches = L_model_forward(X, parameters)
print("AL = " + str(AL))
print("Length of caches list = " + str(len(caches)))

結果:

 

太棒了!現在您有了一個完全的正向傳播,它接受輸入X並輸出包含您的預測的行向量a [L]。它還記錄了“緩存”中的所有中間值。使用A[L],您可以計算您的預測的成本。

 

 

5- Cost function 成本函數

現在您將實現向前和向后傳播。你需要計算成本,因為你想檢查你的模型是否真的在學習。

練習:計算交叉熵代價J,公式如下:

 

 1 # GRADED FUNCTION: compute_cost
 2 
 3 def compute_cost(AL, Y):
 4     """
 5     Implement the cost function defined by equation (7).
 6 
 7     Arguments:
 8     AL -- probability vector corresponding to your label predictions, shape (1, number of examples)
 9     Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)
10 
11     Returns:
12     cost -- cross-entropy cost
13     """
14     
15     m = Y.shape[1]
16 
17     # Compute loss from aL and y.
18     ### START CODE HERE ### (≈ 1 lines of code)
19     cost = (-1 / m) * np.sum(Y * np.log(AL) + (1 - Y) * np.log(1 - AL), axis = 1, keepdims = True)
20     ### END CODE HERE ###
21     
22     cost = np.squeeze(cost)      # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).
23     assert(cost.shape == ())
24     
25     return cost
# GRADED FUNCTION: compute_cost
Y, AL = compute_cost_test_case()

print("cost = " + str(compute_cost(AL, Y)))

結果:

 

 

 

6 - Backward propagation module 反向傳播模塊

與前向傳播一樣,您將實現用於后向傳播的輔助函數。記住,反向傳播是用來計算關於參數的損失函數的梯度

提示

 

 **Figure 3** : Forward and Backward propagation for *LINEAR->RELU->LINEAR->SIGMOID*

*紫色塊表示正向傳播紅色塊表示反向傳播

 

 

現在,與前向傳播類似,您將通過三個步驟構建向后傳播:

•線性向后
•線性->激活逆向,激活計算ReLU或Sigmoid激活的導數
•[LINEAR -> RELU] * (L-1) -> LINEAR -> SIGMOID - backward(整個模型)

6.1 - Linear backward 線性向后

對於第 l 層,線性部分就是:Z [l] =W [l] A [l−1] +b [l] (然后是激活)

假設已經求出了導數

 **Figure 4**

使用輸入dZ [l]計算三個輸出(dW [l]、db [l]、dA [l])。以下是你需要的公式:

 

  練習:使用上面的3個公式來實現linear_backward()。

 1 # GRADED FUNCTION: linear_backward
 2 
 3 def linear_backward(dZ, cache):
 4     """
 5     Implement the linear portion of backward propagation for a single layer (layer l)
 6 
 7     Arguments:
 8     dZ -- Gradient of the cost with respect to the linear output (of current layer l)
 9     cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer
10 
11     Returns:
12     dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
13     dW -- Gradient of the cost with respect to W (current layer l), same shape as W
14     db -- Gradient of the cost with respect to b (current layer l), same shape as b
15     """
16     A_prev, W, b = cache
17     m = A_prev.shape[1]
18     
19     ### START CODE HERE ### (≈ 3 lines of code)
20     dW = 1 / m * np.dot(dZ, A_prev.T)
21     db = 1 / m * np.sum(dZ, axis = 1, keepdims = True)
22     dA_prev = np.dot(W.T, dZ)
23     ### END CODE HERE ###
24     
25     assert (dA_prev.shape == A_prev.shape)
26     assert (dW.shape == W.shape)
27     assert (db.shape == b.shape)
28     
29     return dA_prev, dW, db
# GRADED FUNCTION: linear_backward
# Set up some test inputs
dZ, linear_cache = 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))

結果:

 

6.2 - Linear-Activation backward 向后的線性激活

接下來,您將創建一個合並兩個輔助函數的函數:linear_backward和激活linear_activation_backward的后退步驟

為了幫助你實現linear_activation_backward,我們提供了兩個向后的函數:

  sigmoid_backward:實現了SIGMOID單元的向后傳播。你可以這樣叫它:
    dZ = sigmoid_backward(dA, activation_cache)

  relu_backward:實現RELU單元的向后傳播。你可以這樣叫它:
    dZ = relu_backward(dA, activation_cache)

如果g(.)是激活函數,則sigmoid_backward和relu_backward 計算的就是:

 

 

練習:實現線性>激活層的反向傳播

# GRADED FUNCTION: linear_activation_backward

def linear_activation_backward(dA, cache, activation):
    """
    Implement the backward propagation for the LINEAR->ACTIVATION layer.
    
    Arguments:
    dA -- post-activation gradient for current layer l 
    cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently
    activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"
    
    Returns:
    dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
    dW -- Gradient of the cost with respect to W (current layer l), same shape as W
    db -- Gradient of the cost with respect to b (current layer l), same shape as b
    """
    linear_cache, activation_cache = cache
    
    if activation == "relu":
        ### START CODE HERE ### (≈ 2 lines of code)
        dZ = relu_backward(dA, activation_cache)
        dA_prev, dW, db = linear_backward(dZ, linear_cache)
        ### END CODE HERE ###
        
    elif activation == "sigmoid":
        ### START CODE HERE ### (≈ 2 lines of code)
        dZ = sigmoid_backward(dA, activation_cache)
        dA_prev, dW, db = linear_backward(dZ, linear_cache)
        ### END CODE HERE ###
    
    return dA_prev, dW, db
# GRADED FUNCTION: linear_activation_backward
AL, linear_activation_cache = 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))

結果:

 

 

 

6.3 - L-Model Backward 有L層的向后模型

現在您將為整個網絡實現反向函數。回想一下,在實現L_model_forward函數時,在每次迭代中存儲一個包含(X、W、b和z)的緩存。因此,在L_model_backward函數中,您將從層L開始向后迭代所有隱藏層。在每一步中,您將使用層 l 的緩存值反向傳播到層 l。下面的圖5顯示了反向傳遞。

 

 

 **Figure 5** : Backward pass

**初始化反向傳播**:要通過這個網絡反向傳播,我們知道輸出是,A [L] =σ(Z [L] ). 因此,您的代碼需要計算dAL = 要做到這一點,使用這個公式(由微積分推導,你不需要深入的知識):

 

 

dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) # derivative of cost with respect to AL

 

然后你可以使用激活后梯度dAL繼續向后移動。如圖5所示,現在可以將dAL輸入到您實現的LINEAR->SIGMOID向后函數中(它將使用L_model_forward函數存儲的緩存值)。在此之后,您將必須使用一個for循環來使用LINEAR->RELU backward函數迭代所有其他層。應該將每個dA、dW和db存儲在梯度字典中。為此,使用以下公式:

 

 

例如,對於l=3,這將在梯度[“dW3”]中存儲dW [l]

練習:實現[LINEAR->RELU] * (L-1) -> LINEAR-> SIGMOID模型的反向傳播。

 1 # GRADED FUNCTION: L_model_backward
 2 
 3 def L_model_backward(AL, Y, caches):
 4     """
 5     Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group
 6     
 7     Arguments:
 8     AL -- probability vector, output of the forward propagation (L_model_forward())
 9     Y -- true "label" vector (containing 0 if non-cat, 1 if cat)
10     caches -- list of caches containing:
11                 every cache of linear_activation_forward() with "relu" (it's caches[l], for l in range(L-1) i.e l = 0...L-2)
12                 the cache of linear_activation_forward() with "sigmoid" (it's caches[L-1])
13     
14     Returns:
15     grads -- A dictionary with the gradients
16              grads["dA" + str(l)] = ...
17              grads["dW" + str(l)] = ...
18              grads["db" + str(l)] = ...
19     """
20     grads = {}
21     L = len(caches) # the number of layers 求出層數 前L-2個是“relu”,第L-1層是“sigmoid”
22     m = AL.shape[1] #樣本數
23     Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL 使Y和AL的形狀一樣
24 
25     # Initializing the backpropagation
26     ### START CODE HERE ### (1 line of code)
27     dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) 
28     ### END CODE HERE ###
29     
30     # Lth layer (SIGMOID -> LINEAR) gradients. Inputs: "AL, Y, caches". Outputs: "grads["dAL"], grads["dWL"], grads["dbL"]
31     #這邊是第L層,就是最后一層,使用的是sigmiod激活函數
32     ### START CODE HERE ### (approx. 2 lines)
33     current_cache = caches[L - 1]
34     grads["dA" + str(L)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, activation = "sigmoid")
35     ### END CODE HERE ###
36     
37     for l in reversed(range(L - 1)):
38         # lth layer: (RELU -> LINEAR) gradients.
39         # Inputs: "grads["dA" + str(l + 2)], caches". Outputs: "grads["dA" + str(l + 1)] , grads["dW" + str(l + 1)] , grads["db" + str(l + 1)] 
40         ### START CODE HERE ### (approx. 5 lines)
41         current_cache = caches[l]
42         dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 2)], current_cache, activation = "relu")
43         grads["dA" + str(l + 1)] = dA_prev_temp
44         grads["dW" + str(l + 1)] = dW_temp
45         grads["db" + str(l + 1)] = db_temp
46         ### END CODE HERE ###
47 
48     return grads
# GRADED FUNCTION: L_model_backward
AL, Y_assess, caches = 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"]))

結果:

 

 

 

6.4 - Update Parameters 更新參數

在本節中,你將使用梯度下降更新模型的參數:

 

 

 

這是 α 是學習速率,計算更新后的參數后,將它們存儲在參數字典中。

練習:實現update_parameters()來使用梯度下降更新參數

說明:對於l=1,2,…,l,每個W [l]和b [l]使用梯度下降更新參數。

 1 # GRADED FUNCTION: update_parameters
 2 
 3 def update_parameters(parameters, grads, learning_rate):
 4     """
 5     Update parameters using gradient descent
 6     
 7     Arguments:
 8     parameters -- python dictionary containing your parameters 
 9     grads -- python dictionary containing your gradients, output of L_model_backward
10     
11     Returns:
12     parameters -- python dictionary containing your updated parameters 
13                   parameters["W" + str(l)] = ... 
14                   parameters["b" + str(l)] = ...
15     """
16     
17     L = len(parameters) // 2 # number of layers in the neural network 因為這里參數是成對出現的eg:W1,b1
18     
19     # Update rule for each parameter. Use a for loop.
20     ### START CODE HERE ### (≈ 3 lines of code)
21     for l in range(L):
22         parameters["W" + str(l+1)] = parameters["W" + str(l+1)] - learning_rate * grads["dW" + str(l + 1)]
23         parameters["b" + str(l+1)] = parameters["b" + str(l+1)] - learning_rate * grads["db" + str(l + 1)]
24     ### END CODE HERE ###
25         
26     return parameters
# GRADED FUNCTION: update_parameters
parameters, grads = 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"]))

結果:

 

 

 

7 - Conclusion 結論

祝賀您實現了構建深度神經網絡所需的所有功能!

我們知道這是一個漫長的任務,但如果繼續前進,情況只會越來越好。作業的下一部分比較容易。

在下一個作業中,你將把所有這些放在一起建立兩個模型:

  A two-layer neural network

  An L-layer neural network

實際上,您將使用這些模型來分類貓和非貓的圖像!

Z [l=W [l[l1+[l (4)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM