NG深度学习第二门课作业1-3 深度学习的实践

梯度校验

欢迎来到本周的期末作业!在这个作业中,你将学习如何实现和使用梯度校验。

您是一个致力于在全球范围内提供移动支付的团队的成员,并被要求建立一个深度学习模型来检测欺诈行为——判断用户账户在进行付款的时候是否是被黑客入侵的。

但是反向传播很难实现,有时会有缺陷。因为这是一个任务关键型应用程序,所以您公司的首席执行官希望真正确定您的反向传播实现是正确的。你的首席执行官说,“给我一个证据,证明你的反向传播确实有效!”为了保证这一点,您将使用“梯度校验”。

开始吧!

# Packages
import numpy as np
from testCases import *
from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector

 

1)梯度校验是如何工作的?

 

2)1维的梯度校验

考虑一个1D线性函数 J(θ)=θx。该模型只包含一个实值参数θ,并以x作为输入。

您将实现代码来计算 J(.) 及其衍生物 ∂J/∂θ。然后,您将使用梯度校验来确保您对J的导数计算是正确的。

上图显示了关键的计算步骤:首先从x开始,然后计算函数 J(x)(“正向传播”)。然后计算导数 ∂J/∂θ(“反向传播”)。

练习:为这个简单的函数实现“正向传播”和“反向传播”。即计算两者J(.)(“前向传播”)及其相对于θ的导数(“后向传播”),分为两个独立的函数。

# GRADED FUNCTION: forward_propagation

def forward_propagation(x, theta):
    """
    实现图中呈现的线性前向传播(计算J)(J(theta)= theta * x)

    参数:
    x  - 一个实值输入
    theta  - 参数,也是一个实数

    返回:
    J  - 函数J的值,用公式J(theta)= theta * x计算
    """
    
    ### START CODE HERE ### (approx. 1 line)
    J = np.dot(theta,x)
    ### END CODE HERE ###
    
    return J

测试:

x, theta = 2, 4
J = forward_propagation(x, theta)
print ("J = " + str(J))

结果:

J = 8

 

练习:现在,实现图1的反向传播步骤(导数计算)。也就是说,计算 J(θ)=θx 相对于θ的导数。为了避免你做微积分,你应该找dtheta=∂J/∂θ=x。

# GRADED FUNCTION: backward_propagation

def backward_propagation(x, theta):
    """
    计算J相对于θ的导数。

    参数:
        x  - 一个实值输入
        theta  - 参数,也是一个实数

    返回:
        dtheta  - 相对于θ的成本梯度
    """
    
    ### START CODE HERE ### (approx. 1 line)
    dtheta = x
    ### END CODE HERE ###
    
    return dtheta

测试:

x, theta = 2, 4
dtheta = backward_propagation(x, theta)
print ("dtheta = " + str(dtheta))

结果:

dtheta = 2

 

练习:为了显示 backward_propagation() 函数正在正确计算梯度 ∂J/∂θ,让我们实现梯度检查。

说明:

  • 首先使用上面的公式(1)和一个小的ε值计算“梯度近似值”。以下是要遵循的步骤:

       

  • 然后使用反向传播计算梯度,并将结果存储在变量“grad”中
  • 最后,使用以下公式计算“梯度近似值”和“梯度”之间的相对误差:

    

计算该公式需要3个步骤:

  • 1’. 使用 np.linalg.norm 计算分子(...)
  • 2’. 计算分母。你需要call给np.linalg.norm(...)两次。
  • 3’. 分开他们。

如果这种差异很小(比如小于10的-7次方),您可以确信您已经正确计算了梯度。否则,梯度计算可能会出错。

# GRADED FUNCTION: gradient_check

def gradient_check(x, theta, epsilon = 1e-7):
    """
    实现图中的反向传播。

    参数:
        x  - 一个实值输入
        theta  - 参数,也是一个实数
        epsilon  - 使用公式(3)计算输入的微小偏移以计算近似梯度

    返回:
        近似梯度和后向传播梯度之间的差异
    """
    
    # 使用公式(1)的左侧计算gradapprox. epsilon is small enough, you don't need to worry about the limit.
    ### START CODE HERE ### (approx. 5 lines)
    thetaplus = theta + epsilon                               # Step 1
    thetaminus = theta - epsilon                              # Step 2
    J_plus = forward_propagation(x, thetaplus)                # Step 3
    J_minus = forward_propagation(x, thetaminus)              # Step 4
    gradapprox = (J_plus - J_minus) / (2 * epsilon)           # Step 5
    ### END CODE HERE ###
    
    # Check if gradapprox is close enough to the output of backward_propagation()
    ### START CODE HERE ### (approx. 1 line)
    grad = backward_propagation(x, theta)
    ### END CODE HERE ###
    
    ### START CODE HERE ### (approx. 1 line)
    numerator = np.linalg.norm(grad - gradapprox)                      # Step 1'
    denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox)    # Step 2'
    difference = numerator/denominator                                 # Step 3'
    ### END CODE HERE ###
    
    if difference < 1e-7:
        print ("The gradient is correct!")
    else:
        print ("The gradient is wrong!")
    
    return difference

测试:

x, theta = 2, 4
difference = gradient_check(x, theta)
print("difference = " + str(difference))

结果:

The gradient is correct!
difference = 2.919335883291695e-10

恭喜,差值小于10的-7次方阈值。因此,您可以很有信心正确计算了 backward_propagation() 中的梯度。

现在,在更一般的情况下,你的成本函数J不止有一个1维输入。当你训练一个神经网络时,θ实际上是由多个矩阵组成的,W[l]和偏置 b[l]!了解如何使用高维输入进行梯度校验非常重要。开始吧!

 

3)多维梯度检查

下图描述了欺诈检测模型的正向和反向传播。

                          *LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID*

让我们看看您的正向传播和反向传播的实现。

def forward_propagation_n(X, Y, parameters):
    """
    实现图中的前向传播(并计算成本)。

    参数:
        X - 训练集为m个例子
        Y -  m个示例的标签
        parameters - 包含参数“W1”,“b1”,“W2”,“b2”,“W3”,“b3”的python字典:
            W1  - 权重矩阵,维度为(5,4)
            b1  - 偏向量,维度为(5,1)
            W2  - 权重矩阵,维度为(3,5)
            b2  - 偏向量,维度为(3,1)
            W3  - 权重矩阵,维度为(1,3)
            b3  - 偏向量,维度为(1,1)

    返回:
        cost - 成本函数(logistic)
    """
    
    # retrieve parameters
    m = X.shape[1]
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    W3 = parameters["W3"]
    b3 = parameters["b3"]

    # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID
    Z1 = np.dot(W1, X) + b1
    A1 = relu(Z1)
    Z2 = np.dot(W2, A1) + b2
    A2 = relu(Z2)
    Z3 = np.dot(W3, A2) + b3
    A3 = sigmoid(Z3)

    # Cost
    logprobs = np.multiply(-np.log(A3),Y) + np.multiply(-np.log(1 - A3), 1 - Y)
    cost = 1./m * np.sum(logprobs)
    
    cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3)
    
    return cost, cache

现在,运行反向传播。

def backward_propagation_n(X, Y, cache):
    """
    实现图中所示的反向传播。

    参数:
        X - 输入数据点(输入节点数量,1)
        Y - 标签
        cache - 来自forward_propagation_n()的cache输出

    返回:
        gradients - 一个字典,其中包含与每个参数、激活和激活前变量相关的成本梯度。
    """
    
    m = X.shape[1]
    (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache
    
    dZ3 = A3 - Y
    dW3 = 1./m * np.dot(dZ3, A2.T)
    db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)
    
    dA2 = np.dot(W3.T, dZ3)
    dZ2 = np.multiply(dA2, np.int64(A2 > 0))
#     dW2 = 1./m * np.dot(dZ2, A1.T) * 2    #  Should not multiply by 2
    dW2 = 1. / m * np.dot(dZ2, A1.T)
    db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)
    
    dA1 = np.dot(W2.T, dZ2)
    dZ1 = np.multiply(dA1, np.int64(A1 > 0))
    dW1 = 1./m * np.dot(dZ1, X.T)
#     db1 = 4./m * np.sum(dZ1, axis=1, keepdims = True)    #  Should not multiply by 4
    db1 = 1. / m * np.sum(dZ1, axis=1, keepdims=True)
    
    gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,
                 "dA2": dA2, "dZ2": dZ2, "dW2": dW2, "db2": db2,
                 "dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1}
    
    return gradients

您在欺诈检测测试集上获得了一些结果,但是您对您的模型没有100%的把握。没有人是完美的!让我们实现梯度检查来验证您的梯度是否正确。

梯度校验是如何工作的? 如1)和2)中一样

我们还使用 gradients_to_vector() 将 "gradients" 字典转换成向量 "grad" 。你不用担心这个。

练习:实现 gradient_check_n(). 

说明:这里是伪代码,将帮助您实现梯度检查。

# GRADED FUNCTION: gradient_check_n

def gradient_check_n(parameters, gradients, X, Y, epsilon = 1e-7):
    """
    检查backward_propagation_n是否正确计算forward_propagation_n输出的成本梯度

    参数:
        parameters - 包含参数“W1”,“b1”,“W2”,“b2”,“W3”,“b3”的python字典:
        grad_output_propagation_n的输出包含与参数相关的成本梯度。
        x  - 输入数据点,维度为(输入节点数量,1)
        y  - 标签
        epsilon  - 计算输入的微小偏移以计算近似梯度

    返回:
        difference - 近似梯度和后向传播梯度之间的差异
    """
    
    # Set-up variables
    parameters_values, _ = dictionary_to_vector(parameters)
    grad = gradients_to_vector(gradients)
    num_parameters = parameters_values.shape[0]
    J_plus = np.zeros((num_parameters, 1))
    J_minus = np.zeros((num_parameters, 1))
    gradapprox = np.zeros((num_parameters, 1))
    
    # 计算 gradapprox
    for i in range(num_parameters):
        
        # 计算 J_plus[i]. Inputs: "parameters_values, epsilon". Output = "J_plus[i]".
        # "_" is used because the function you have to outputs two parameters but we only care about the first one
        ### START CODE HERE ### (approx. 3 lines)
        thetaplus = np.copy(parameters_values)                                     # Step 1
        thetaplus[i][0] = thetaplus[i][0] + epsilon                                 # Step 2
        J_plus[i], _ = forward_propagation_n(X,Y,vector_to_dictionary(thetaplus))                                   # Step 3
        ### END CODE HERE ###
        
        # 计算 J_minus[i]. Inputs: "parameters_values, epsilon". Output = "J_minus[i]".
        ### START CODE HERE ### (approx. 3 lines)
        thetaminus = np.copy(parameters_values)                                    # Step 1
        thetaminus[i][0] =thetaminus[i][0] - epsilon                            # Step 2        
        J_minus[i], _ = forward_propagation_n(X,Y,vector_to_dictionary(thetaminus))                                 # Step 3
        ### END CODE HERE ###
        
        # 计算 gradapprox[i]
        ### START CODE HERE ### (approx. 1 line)
        gradapprox[i] = (J_plus[i] - J_minus[i]) / (2 * epsilon)
        ### END CODE HERE ###
    
    # 通过计算差异比较gradapprox和后向传播梯度
    ### START CODE HERE ### (approx. 1 line)
    numerator = np.linalg.norm(grad - gradapprox)                                          # Step 1'
    denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox)                                          # Step 2'
    difference = numerator / denominator                                           # Step 3'
    ### END CODE HERE ###

    if difference > 2e-7:
        print ("\033[93m" + "There is a mistake in the backward propagation! difference = " + str(difference) + "\033[0m")
    else:
        print ("\033[92m" + "Your backward propagation works perfectly fine! difference = " + str(difference) + "\033[0m")
    
    return difference

测试:

X, Y, parameters = gradient_check_n_test_case()

cost, cache = forward_propagation_n(X, Y, parameters)
gradients = backward_propagation_n(X, Y, cache)
difference = gradient_check_n(parameters, gradients, X, Y)

结果:

Your backward propagation works perfectly fine! difference = 1.1890913023330276e-07

 

我们给你的反向传播代码似乎有错误!很高兴你已经实现了梯度检查。返回反向传播并尝试查找/纠正错误(提示:检查dW2和db1)。当您认为已经修复渐变检查时,请重新运行它。请记住,如果修改代码,您需要重新执行定义反向传播的单元格。 你能通过梯度检查来证明你的导数计算是正确的吗?即使作业的这一部分没有评分,我们强烈建议您尝试找到错误并重新运行梯度检查,直到您确信backprop现在已经正确实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值