吴恩达深度学习课程-Course 1 神经网络与深度学习 第四周 深层神经网络编程作业(第一部分)

第一部分

引入

构建您的深度神经网络:循序渐进

欢迎来到您的第 4 周作业(第 1 部分,共 2 部分)! 您之前已经训练了一个 2 层神经网络(具有单个隐藏层)。 本周,您将构建一个深度神经网络,层数不限!

  • 在本笔记本中,您将实现构建深度神经网络所需的所有功能
  • 在下一个作业中,您将使用这些函数来构建用于图像分类的深度神经网络。

完成此任务后,您将能够:

  • 使用像 ReLU 这样的非线性单元来改进你的模型
  • 构建更深的神经网络(具有 1 个以上的隐藏层)
  • 实现一个易于使用的神经网络类

Notation:

  • 上标 [ l ] [l] [l] 表示与 l t h l^{th} lth 层相关的数量.
    • 举例: a [ L ] a^{[L]} a[L] 是第 L t h L^{th} Lth 层的激活. W [ L ] W^{[L]} W[L] b [ L ] b^{[L]} b[L] 是第 L t h L^{th} Lth层的参数.
  • 上标 ( i ) (i) (i) 表示与第 i t h i^{th} ith 样本相关的数量.
    • 举例: x ( i ) x^{(i)} x(i) 是第 i t h i^{th} ith 个训练样本.
  • 下标 i i i表示向量的第 i t h i^{th} ith 项.
    • 举例: a i [ l ] a^{[l]}_i ai[l] 表示第 l t h l^{th} lth层激活的第 i t h i^{th} ith项.

让我们开始吧!

1 - 导入所需包

让我们首先导入您在此任务中需要的所有包。

  • numpy 是使用 Python 进行科学计算的主要包。
  • matplotlib 是一个用 Python 绘制图形的库。
  • dnn_utils 为这个笔记本提供了一些必要的功能。
  • testCases 提供了一些测试用例来评估你的函数的正确性
  • np.random.seed(1) 用于保持所有随机函数调用的一致性。 它将帮助我们为您的工作评分。 请不要改变种子。
import numpy as np
import h5py
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) # 设置图的默认大小
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

%load_ext autoreload
%autoreload 2

np.random.seed(1)

2 - 作业大纲

要构建您的神经网络,您将实现几个“辅助函数”。 这些辅助函数将在下一个作业中用于构建两层神经网络和 L 层神经网络。 您将实现的每个小辅助函数都有详细的说明,将引导您完成必要的步骤。 这是此作业的大纲,您将:

  • 初始化两层网络𝐿 层神经网络的参数。
  • 实现前向传播模块(下图中紫色部分)。
    • 完成层前向传播步骤的 LINEAR 部分(产生 𝑍[𝑙])。
    • 我们为您提供 ACTIVATION 函数(relu/sigmoid)。
    • 将前两步组合成一个新的[LINEAR->ACTIVATION]前向函数。
    • 堆叠 [LINEAR->RELU] 前向函数 L-1 次(对于第 1 层到 L-1 层)并在末尾添加 [LINEAR->SIGMOID](对于最后一层 𝐿)。 这为您提供了一个新的 L_model_forward 函数
  • 计算损失
  • 实现反向传播模块(下图中用红色表示)。
    • 完成层的反向传播步骤的 LINEAR 部分。
    • 我们给你ACTIVATE函数的梯度(relu_backward/sigmoid_backward)
    • 前面的两步合并成一个新的[LINEAR->ACTIVATION]向后函数。
    • 将 [LINEAR->RELU] 向后堆叠 L-1 次并在新的 L_model_backward 函数中向后添加
      [LINEAR->SIGMOID]
  • 最后更新参数

请注意,对于每个前向函数,都有一个相应的后向函数。 这就是为什么在转发模块的每一步你都会在缓存中存储一​​些值。 缓存值可用于计算梯度。 在反向传播模块中,您将使用缓存来计算梯度。 此作业将准确地向您展示如何执行每个步骤。

3 - 初始化

您将编写两个辅助函数来初始化模型的参数。 第一个函数将用于初始化两层模型的参数。 第二个将把这个初始化过程推广到 𝐿L 层。

3.1 - 2 层神经网络

练习】:创建并初始化 2 层神经网络的参数。

指示】:

模型的结构是:LINEAR -> RELU -> LINEAR -> SIGMOID。

权重矩阵使用随机初始化。 使用具有正确形状的 np.random.randn(shape)*0.01

偏差使用零初始化。 使用 np.zeros(shape)

# GRADED FUNCTION: initialize_parameters

def initialize_parameters(n_x, n_h, n_y):
    """
    初始化2层神经网络的参数
    参数:
    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)的偏差向量
    """
    
    np.random.seed(1)
    
    ### START CODE HERE ### (≈ 4 lines of code)
    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))
    ### END CODE HERE ###
    
    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    
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 层神经网络

更深的 L 层神经网络的初始化更加复杂,因为有更多的权重矩阵和偏置向量。 完成 initialize_parameters_deep 时,您应该确保每个层之间的尺寸匹配。 回想一下 𝑛[𝑙]是层 𝑙中的单元数

例如:如果我们的输入 𝑋的大小是 (12288,209)(有 𝑚=209个例子),那么:
执行一下如下的代码:

<!-- 按照作业的代码稍微改了一下,不然显示不出来东西,
不太会html语言,轻喷= = -->

<html>
<body>

<table border="1">


    <tr>
        <td>  </td> 
        <td> **Shape of W** </td> 
        <td> **Shape of b**  </td> 
        <td> **Activation** </td>
        <td> **Shape of Activation** </td> 
    <tr>
    
    <tr>
        <td> **Layer 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> **Layer 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>
    
   <tr>
        <td> **Layer L-1** </td> 
        <td> $(n^{[L-1]}, n^{[L-2]})$ </td> 
        <td> $(n^{[L-1]}, 1)$  </td> 
        <td>$Z^{[L-1]} =  W^{[L-1]} A^{[L-2]} + b^{[L-1]}$ </td> 
        <td> $(n^{[L-1]}, 209)$ </td> 
    <tr>
    
    
   <tr>
        <td> **Layer L** </td> 
        <td> $(n^{[L]}, n^{[L-1]})$ </td> 
        <td> $(n^{[L]}, 1)$ </td>
        <td> $Z^{[L]} =  W^{[L]} A^{[L-1]} + b^{[L]}$</td>
        <td> $(n^{[L]}, 209)$  </td> 
    <tr>

</table>

</body>
</html>

在这里插入图片描述
请记住,当我们在python中计算𝑊𝑋+𝑏时,它进行广播。 例如,如果:
W = [ j k l m n o p q r ]        X = [ a b c d e f g h i ]        b = [ s t u ] (2) W = \begin{bmatrix} j & k & l\\ m & n & o \\ p & q & r \end{bmatrix}\;\;\; X = \begin{bmatrix} a & b & c\\ d & e & f \\ g & h & i \end{bmatrix} \;\;\; b =\begin{bmatrix} s \\ t \\ u \end{bmatrix}\tag{2} W=jmpknqlorX=adgbehcfib=stu(2)

𝑊𝑋+𝑏
W X + b = [ ( j a + k d + l g ) + s ( j b + k e + l h ) + s ( j c + k f + l i ) + s ( m a + n d + o g ) + t ( m b + n e + o h ) + t ( m c + n f + o i ) + t ( p a + q d + r g ) + u ( p b + q e + r h ) + u ( p c + q f + r i ) + u ] (3) WX + b = \begin{bmatrix} (ja + kd + lg) + s & (jb + ke + lh) + s & (jc + kf + li)+ s\\ (ma + nd + og) + t & (mb + ne + oh) + t & (mc + nf + oi) + t\\ (pa + qd + rg) + u & (pb + qe + rh) + u & (pc + qf + ri)+ u \end{bmatrix}\tag{3} WX+b=(ja+kd+lg)+s(ma+nd+og)+t(pa+qd+rg)+u(jb+ke+lh)+s(mb+ne+oh)+t(pb+qe+rh)+u(jc+kf+li)+s(mc+nf+oi)+t(pc+qf+ri)+u(3)

练习】:实现 L 层神经网络初始化

指示】:

  • 模型的结构是*[LINEAR -> RELU] ×× (L-1) -> LINEAR -> SIGMOID*。 即,它具有使用
    ReLU 激活函数的 𝐿−1 层,后跟具有 sigmoid 激活函数的输出层

  • 权重矩阵使用随机初始化。 使用 np.random.rand(shape) * 0.01

  • 偏差使用零初始化。 使用 np.zeros(shape)

  • 我们将在变量 layer_dims 中存储 𝑛[𝑙],不同层中的单元数。 例如,上周的“平面数据分类模型”的
    layer_dims 应该是 [2,4,1]:有2个输入,一个带有 4 个隐藏单元的隐藏层,一个带有 1
    个输出单元
    的输出层。 因此意味着 W1 的形状是 (4,2),b1 是 (4,1),W2 是 (1,4),b2 是 (1,1)。
    现在你将把它推广到 𝐿层!

  • 这是𝐿=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):
    """
    初始化深层神经网络参数
    
    参数:
    layer_dims -- python数组(列表)包含我们网络中每一层的维度
    
    Returns:
    parameters -- 包含参数 "W1", "b1", ..., "WL", "bL"的python字典:
                   Wl -- 形状为 (layer_dims[l], layer_dims[l-1])的权重矩阵
                   bl -- 形状为 (layer_dims[l], 1)的偏差矩阵
    """
    
    np.random.seed(3)
    parameters = {}
    L = len(layer_dims)            # 网络的层数

    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

测试代码

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 - 前向传播模块

4.1 - 线性前向

现在您已经初始化了您的参数,您将执行前向传播模块。 您将从实现一些基本功能开始,稍后您将在实现模型时使用这些功能。 您将按此顺序完成三个功能:

  • 线性
  • LINEAR -> ACTIVATION 其中 ACTIVATION 将是 ReLU 或 Sigmoid。
  • [LINEAR -> RELU] ×× (L-1) -> LINEAR -> SIGMOID(全模型)

线性前向模块(对所有样本进行矢量化)计算以下等式:
Z [ l ] = W [ l ] A [ l − 1 ] + b [ l ] (4) Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}\tag{4} Z[l]=W[l]A[l1]+b[l](4)

其中 A [ 0 ] = X A^{[0]} = X A[0]=X.

练习】:构建前向传播线性部分
提醒】:这个单位的数学表示是 Z [ l ] = W [ l ] A [ l − 1 ] + b [ l ] Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]} Z[l]=W[l]A[l1]+b[l]。 您可能还会发现 np.dot() 很有用。 如果您的尺寸不匹配,打印 W.shape 可能会有所帮助。

# GRADED FUNCTION: linear_forward

def linear_forward(A, W, b):
    """
    实现一层前向传播的线性部分.

    参数:
    A -- 来自前一层(或输入数据)的激活:(前一层的大小,样本数)
    W -- 权重矩阵:形状为(当前层的大小,前一层的大小)的 numpy 数组
    b -- 偏置向量,形状为(当前层的大小,1)的 numpy 数组

    返回:
    Z -- 激活函数的输入,也称为预激活参数 
    cache -- 包含“A”、“W”和“b”的python字典; 存储以有效计算反向传播
    """
    
    ### 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

测试代码

A, W, b = linear_forward_test_case()

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

输出结果为
在这里插入图片描述

4.2 - 线性激活前向

在本笔记本中,您将使用两个激活函数:

Sigmoid σ ( Z ) = σ ( W A + b ) = 1 1 + e − ( W A + b ) \sigma(Z) = \sigma(W A + b) = \frac{1}{ 1 + e^{-(W A + b)}} σ(Z)=σ(WA+b)=1+e(WA+b)1
我们已经为您提供了 sigmoid 函数。 该函数返回两项:激活值a”和包含“Z”的“缓存”(这是我们将提供给相应的反向函数的内容)。 要使用它,您只需调用:

A、activation_cache = sigmoid(Z)

ReLU:ReLu 的数学公式是 A = R E L U ( Z ) = m a x ( 0 , Z ) A = RELU(Z) = max(0, Z) A=RELU(Z)=max(0,Z)。 我们已经为您提供了 relu 功能。
该函数返回两项:激活值A”和包含“Z”的“缓存”(这是我们将提供给相应的反向函数的内容)。 要使用它,您只需调用:

A、activation_cache = relu(Z)

为方便起见,您将把两个函数(线性和激活)归为一个函数(线性->激活)。 因此,您将实现一个函数,该函数执行 LINEAR 前向步骤,然后是 ACTIVATION 前向步骤。

练习】:实现 LINEAR->ACTIVATION 层的前向传播
数学关系为: A [ l ] = g ( Z [ l ] ) = g ( W [ l ] A [ l − 1 ] + b [ l ] ) A^{[l]} = g(Z^{[l]}) = g(W^{[l]}A^{[l-1]} +b^{[l]}) A[l]=g(Z[l])=g(W[l]A[l1]+b[l])其中激活“g”可以是 sigmoid()relu()。 使用 linear_forward() 和正确的激活函数。

# GRADED FUNCTION: linear_activation_forward

def linear_activation_forward(A_prev, W, b, activation):
    """
    实现 LINEAR->ACTIVATION 层的前向传播

    参数:
    A_prev -- 来自前一层(或输入数据)的激活:(前一层的大小,样本数)
    W -- 权重矩阵:形状为(当前层的大小,前一层的大小)的numpy 数组
    b -- 偏置向量,形状为(当前层的大小,1)的 numpy 数组
    activation -- 在该层中使用的激活,存储为文本字符串:“sigmoid”或“relu”

    返回:
    A -- 激活函数的输出,也称为激活后值 
    cache -- 包含“linear_cache”和“activation_cache”的python字典;
             存储以有效计算反向传播
    """
    
    if activation == "sigmoid":
        # 输入: "A_prev, W, b". 输出: "A, activation_cache".
        ### START CODE HERE ### (≈ 2 lines of code)
        Z, linear_cache = linear_forward(A_prev, W, b)
        A, activation_cache = sigmoid(Z)
        ### END CODE HERE ###
    
    elif activation == "relu":
        # 输入: "A_prev, W, b". 输出: "A, activation_cache".
        ### START CODE HERE ### (≈ 2 lines of code)
        Z, linear_cache = linear_forward(A_prev, W, b)
        A, activation_cache = relu(Z)
        ### END CODE HERE ###
    
    assert (A.shape == (W.shape[0], A_prev.shape[1]))
    cache = (linear_cache, activation_cache)

    return A, cache

测试代码

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]”计算在神经网络中算作单层,而不是两层。

4.3 - L 层模型

为了在实现 𝐿 层神经网络时更加方便,您将需要一个函数来复制前一个函数(linear_activation_forward 和 RELU)𝐿−1次,然后是一个带有 SIGMOID 的 linear_activation_forward
在这里插入图片描述
练习】:实现上述模型的前向传播。
说明:在下面的代码中,变量AL表示 A [ L ] = σ ( Z [ L ] ) = σ ( W [ L ] A [ L − 1 ] + b [ L ] ) A^{[L]} = \sigma(Z^{[L]}) = \sigma(W^{[L]} A^{[L-1]} + b^{[L]}) A[L]=σ(Z[L])=σ(W[L]A[L1]+b[L]) (这有时也称为 Yhat,即这是 𝑌̂。)

提示】:

  • 使用您之前编写的函数
  • 使用 for 循环复制 [LINEAR->RELU] (L-1) 次
  • 不要忘记跟踪“缓存”列表中的缓存。 要将新值 c 添加到列表中,您可以使用 list.append(c)
# GRADED FUNCTION: L_model_forward

def L_model_forward(X, parameters):
    """
    为 [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID 计算实现前向传播
    
    参数:
    X -- data, numpy数组形状为 (输入大小, 样本数)
    parameters -- initialize_parameters_deep()的输出
    
    返回:
    AL -- 上次激活后的值
    caches -- 缓存列表包含:
                linear_relu_forward() 的每个缓存
                (其中有 L-1 个,索引从 0 到 L-2)
                linear_sigmoid_forward()的缓存
                (有一个,索引为 L-1)
    """

    caches = []
    A = X
    L = len(parameters) // 2              # 神经网络的层数
    
    # 实现 [LINEAR -> RELU]*(L-1)。 将“缓存”添加到“缓存”列表中
    for l in range(1, L):
        A_prev = A 
        ### START CODE HERE ### (≈ 2 lines of code)
        A, cache = linear_activation_forward(A, parameters['W' + str(l)], parameters['b' + str(l)], activation = 'relu')
        caches.append(cache)
        ### END CODE HERE ###
    
    # 实现 LINEAR -> SIGMOID。 将“缓存”添加到“缓存”列表中。.
    ### START CODE HERE ### (≈ 2 lines of code)
    AL, cache = linear_activation_forward(A, parameters['W' + str(L)], parameters['b' + str(L)], activation = 'sigmoid')

    ### END CODE HERE ###
    
    assert(AL.shape == (1,X.shape[1]))
            
    return AL, caches

测试代码

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输出一个包含你的预测的行向量 𝐴[𝐿]。 它还在“缓存”中记录所有中间值。 使用 𝐴[𝐿] ,您可以计算预测的成本

5 - 成本函数

现在您将实现前向和后向传播。 您需要计算成本,因为您想检查您的模型是否真的在学习。

练习】:使用以下公式计算交叉熵成本 𝐽
− 1 m ∑ i = 1 m ( y ( i ) log ⁡ ( a [ L ] ( i ) ) + ( 1 − y ( i ) ) log ⁡ ( 1 − a [ L ] ( i ) ) ) (7) -\frac{1}{m} \sum\limits_{i = 1}^{m} (y^{(i)}\log\left(a^{[L] (i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right)) \tag{7} m1i=1m(y(i)log(a[L](i))+(1y(i))log(1a[L](i)))(7)

# GRADED FUNCTION: compute_cost

def compute_cost(AL, Y):
    """
    实现等式(7)定义的成本函数

    参数:
    AL -- 对应于您的标签预测的概率向量, 大小为 (1, number of examples)
    Y -- 真正的“标签”向量 (举例: 包含 0 表示非猫,1 表示猫), 形状为 (1, 样本数量)

    返回:
    cost -- 交叉熵成本
    """
    
    m = Y.shape[1]

    # 从 AL 和 Y 计算损失.
    ### START CODE HERE ### (≈ 1 lines of code)
    cost = -1 / m * np.sum(Y * np.log(AL) + (1-Y) * np.log(1-AL),axis=1,keepdims=True)
    ### END CODE HERE ###
    
    cost = np.squeeze(cost)      # 确保您的成本形状符合我们的预期 (e.g. 这将 [[17]] 变成 17).
    assert(cost.shape == ())
    
    return cost

测试代码

Y, AL = compute_cost_test_case()

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

输出结果
在这里插入图片描述

6 - 反向传播模块

就像前向传播一样,您将实现反向传播的辅助函数。 请记住,反向传播用于计算损失函数相对于参数的梯度

提醒:
在这里插入图片描述
图 3LINEAR->RELU->LINEAR->SIGMOID 的正向和反向传播*
紫色方块代表前向传播,红色方块代表反向传播。

现在,类似于前向传播,您将分三步构建后向传播

  • LINEAR 向后
  • LINEAR -> ACTIVATION 向后,其中 ACTIVATION 计算 ReLU 或 sigmoid 激活的导数
  • [LINEAR -> RELU] ×× (L-1) -> LINEAR -> SIGMOID 向后(整个模型)

6.1 - 线性反向

对于层 𝑙线性部分为: Z [ l ] = W [ l ] A [ l − 1 ] + b [ l ] Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]} Z[l]=W[l]A[l1]+b[l]( 然后激活)。

假设你已经计算了导数 d Z [ l ] = ∂ L ∂ Z [ l ] dZ^{[l]} = \frac{\partial \mathcal{L} }{\partial Z^{[l]}} dZ[l]=Z[l]L。 你想得到 ( d W [ l ] , d b [ l ] d A [ l − 1 ] ) (dW^{[l]}, db^{[l]} dA^{[l-1]}) (dW[l],db[l]dA[l1])
在这里插入图片描述

这三个输出 ( d W [ l ] , d b [ l ] , d A [ l ] ) (dW^{[l]}, db^{[l]}, dA^{[l]}) (dW[l],db[l],dA[l]) 使用 d Z [ l ] dZ^{[l]} dZ[l]计算.这些是你需要的公式:
d W [ l ] = ∂ L ∂ W [ l ] = 1 m d Z [ l ] A [ l − 1 ] T (8) dW^{[l]} = \frac{\partial \mathcal{L} }{\partial W^{[l]}} = \frac{1}{m} dZ^{[l]} A^{[l-1] T} \tag{8} dW[l]=W[l]L=m1dZ[l]A[l1]T(8)
d b [ l ] = ∂ L ∂ b [ l ] = 1 m ∑ i = 1 m d Z [ l ] ( i ) (9) db^{[l]} = \frac{\partial \mathcal{L} }{\partial b^{[l]}} = \frac{1}{m} \sum_{i = 1}^{m} dZ^{[l](i)}\tag{9} db[l]=b[l]L=m1i=1mdZ[l](i)(9)
d A [ l − 1 ] = ∂ L ∂ A [ l − 1 ] = W [ l ] T d Z [ l ] (10) dA^{[l-1]} = \frac{\partial \mathcal{L} }{\partial A^{[l-1]}} = W^{[l] T} dZ^{[l]} \tag{10} dA[l1]=A[l1]L=W[l]TdZ[l](10)

练习】:使用上面的 3 个公式来实现 linear_backward()

# GRADED FUNCTION: linear_backward

def linear_backward(dZ, cache):
    """
    Implement the linear portion of backward propagation for a single layer (layer l)

    Arguments:
    dZ -- Gradient of the cost with respect to the linear output (of current layer l)
    cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer

    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
    """
    A_prev, W, b = cache
    m = A_prev.shape[1]
    
    ### START CODE HERE ### (≈ 3 lines of code)
    dW = 1/m * np.dot(dZ, A_prev.T)
    db = 1/m * np.sum(dZ, axis=1, keepdims=True)
    dA_prev = np.dot(W.T,dZ)
    ### END CODE HERE ###
    
    assert (dA_prev.shape == A_prev.shape)
    assert (dW.shape == W.shape)
    assert (db.shape == b.shape)
    
    return dA_prev, dW, db

测试代码

# 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_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)

如果 𝑔(.)是激活函数,sigmoid_backwardrelu_backward 计算
d Z [ l ] = d A [ l ] ∗ g ′ ( Z [ l ] ) (11) dZ^{[l]} = dA^{[l]} * g'(Z^{[l]}) \tag{11} dZ[l]=dA[l]g(Z[l])(11)

练习】:为 LINEAR->ACTIVATION 层实现反向传播

# GRADED FUNCTION: linear_activation_backward

def linear_activation_backward(dA, cache, activation):
    """
    实现 LINEAR->ACTIVATION 层的反向传播.
    
    参数:
    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

测试代码

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 模型反向

现在您将为整个网络实现反向功能。 回想一下,当您实现 L_model_forward 函数时,在每次迭代时,您都存储了一个包含 (X,W,b, 和 z)缓存。 在反向传播模块中,您将使用这些变量来计算梯度。 因此,在 L_model_backward 函数中,您将从层 𝐿 开始向后遍历所有隐藏层。 在每个步骤中,您将使用层 𝑙的缓存值通过层 𝑙进行反向传播。 下面的图 5 显示了反向传递。
在这里插入图片描述
初始化反向传播:为了通过这个网络反向传播,我们知道输出是 A [ L ] = σ ( Z [ L ] ) A^{[L]} = \sigma(Z^{[L]}) A[L]=σ(Z[L])。 因此,您的代码需要计算dAL = ∂ L ∂ A [ L ] = \frac{\partial \mathcal{L}}{\partial A^{[L]}} =A[L]L。 为此,请使用以下公式(使用您不需要深入了解的微积分得出):

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

numpy中的divide函数用法
然后,您可以使用此激活后梯度 dAL 继续向后移动。 如图 5 所示,您现在可以将 dAL 输入到您实现的 LINEAR->SIGMOID 反向函数中(它将使用 L_model_forward 函数存储的缓存值)。 之后,您将必须使用 for 循环使用 LINEAR->RELU 反向函数遍历所有其他层。 您应该将每个 dA、dW 和 db 存储在 grads 字典中。 为此,请使用以下公式:
g r a d s [ " d W " + s t r ( l ) ] = d W [ l ] (15) grads["dW" + str(l)] = dW^{[l]}\tag{15} grads["dW"+str(l)]=dW[l](15)

举例, 对于 l = 3 l=3 l=3 需要存储 d W [ l ] dW^{[l]} dW[l]grads["dW3"].

练习】: 实现反向传播[LINEAR->RELU] × \times × (L-1) -> LINEAR -> SIGMOID模型.

# GRADED FUNCTION: L_model_backward

def L_model_backward(AL, Y, caches):
    """
    Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group
    
    Arguments:
    AL -- probability vector, output of the forward propagation (L_model_forward())
    Y -- true "label" vector (containing 0 if non-cat, 1 if cat)
    caches -- list of caches containing:
                every cache of linear_activation_forward() with "relu" (it's caches[l], for l in range(L-1) i.e l = 0...L-2)
                the cache of linear_activation_forward() with "sigmoid" (it's caches[L-1])
    
    Returns:
    grads -- A dictionary with the gradients
             grads["dA" + str(l)] = ...
             grads["dW" + str(l)] = ...
             grads["db" + str(l)] = ...
    """
    grads = {}
    L = len(caches) # the number of layers
    m = AL.shape[1]
    Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL

    # Initializing the backpropagation
    ### START CODE HERE ### (1 line of code)
    dAL = -np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)
    ### END CODE HERE ###
    
    # Lth layer (SIGMOID -> LINEAR) gradients. Inputs: "AL, Y, caches". Outputs: "grads["dAL"], grads["dWL"], grads["dbL"]
    ### START CODE HERE ### (approx. 2 lines)
    current_cache = caches[L - 1]
    grads["dA" + str(L)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, activation = 'sigmoid')
    ### END CODE HERE ###
    
    for l in reversed(range(L - 1)):
        # lth layer: (RELU -> LINEAR) gradients.
        # Inputs: "grads["dA" + str(l + 2)], caches". Outputs: "grads["dA" + str(l + 1)] , grads["dW" + str(l + 1)] , grads["db" + str(l + 1)] 
        ### START CODE HERE ### (approx. 5 lines)
        current_cache = caches[l]
        dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 2)], current_cache, activation = 'relu')
        grads["dA" + str(l + 1)] = dA_prev_temp
        grads["dW" + str(l + 1)] = dW_temp
        grads["db" + str(l + 1)] = db_temp
        ### END CODE HERE ###

    return grads

测试代码

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 - 更新参数

在本节中,您将使用梯度下降更新模型的参数:

W [ l ] = W [ l ] − α   d W [ l ] (16) W^{[l]} = W^{[l]} - \alpha \text{ } dW^{[l]} \tag{16} W[l]=W[l]α dW[l](16)
b [ l ] = b [ l ] − α   d b [ l ] (17) b^{[l]} = b^{[l]} - \alpha \text{ } db^{[l]} \tag{17} b[l]=b[l]α db[l](17)

其中 α \alpha α学习率。 计算更新后的参数后,将它们存储在参数字典中。

练习】:实现 update_parameters() 以使用梯度下降更新参数。

说明】:在每个 𝑊[𝑙]和 𝑏[𝑙]上使用梯度下降更新参数,用于 𝑙=1,2,…,𝐿。

# GRADED FUNCTION: update_parameters

def update_parameters(parameters, grads, learning_rate):
    """
    Update parameters using gradient descent
    
    Arguments:
    parameters -- python dictionary containing your parameters 
    grads -- python dictionary containing your gradients, output of L_model_backward
    
    Returns:
    parameters -- python dictionary containing your updated parameters 
                  parameters["W" + str(l)] = ... 
                  parameters["b" + str(l)] = ...
    """
    
    L = len(parameters) // 2 # number of layers in the neural network

    # Update rule for each parameter. Use a for loop.
    ### START CODE HERE ### (≈ 3 lines of code)
    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)]
    ### END CODE HERE ###
        
    return 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 - 结论

恭喜您实现了构建深度神经网络所需的所有功能!
我们知道这是一项漫长的任务,但未来只会变得更好。 作业的下一部分更容易。
在下一个作业中,您将把所有这些放在一起构建两个模型:

  • 一个两层神经网络
  • 一个 L 层神经网络

实际上,您将使用这些模型对猫与非猫图像进行分类!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值