【深度学习】笔记6:梯度校验

写在前面

吴恩达老师第二门课程第一周的内容主要包括以下三部分:

1.初始化参数:
使用0来初始化参数;
使用随机数来初始化参数;
使用抑梯度异常初始化参数(可以参见视频中的梯度消失和梯度爆炸)。
2.正则化模型:
使用二范数对二分类模型正则化,尝试避免过拟合;
使用dropout法精简模型,同样是为了尝试避免过拟合。
3.梯度校验:
对模型使用梯度校验,检测它是否会在梯度下降的过程中出现误差过大的情况。

内容较多,我将分三次来整理。下面是最后一部分——梯度校验的内容。(个人认为这一部分最抽象,不太好理解。)

问题描述

假设你是致力于在全球范围内提供移动支付的团队的一员,并被要求构建一个深度学习模型来检测欺诈行为的存在,即每当有人付款时,你要查看付款是否可能是欺诈性的,比如用户的帐户已被黑客接管。

但是反向传播实施起来非常具有挑战性,有时还会出现错误。由于这是一项很关键的任务应用程序,贵公司的首席执行官希望确定你执行的反向传播是正确的。你的老板会说,“给我一个证据证明你的反向传播真的有效!” 为了保证这一点,我们会使用“梯度校验”。

OK,开始了!

梯度校验如何工作

在反向传播过程中需要计算梯度\frac{\partial J}{\partial \theta}\theta表示模型中的参数,J要用到前向传播和损失函数来计算。由于前向传播实现起来相对容易一些,所以我们默认J是百分百正确的,因此这里会用J来计算梯度\frac{\partial J}{\partial \theta}
OK,再来回顾一下导数(或梯度)的定义:
\frac{\partial J}{\partial \theta} = \lim_{\varepsilon \to 0} \frac{J(\theta + \varepsilon) - J(\theta - \varepsilon)}{2 \varepsilon} \tag{1}
这里我们要知道:

  • 要追求的计算正确的值是\frac{\partial J}{\partial \theta}
  • 在确定代价函数J正确的前提下,我们可以通过计算J(\theta + \varepsilon)J(\theta - \varepsilon)\theta为常数时)来校验

一维梯度校验

针对一维线性模型(J(\theta) = \theta x)梯度校验计算过程:

Figure 1 : 1D linear model

即首先在前向传播中计算
J(\theta)
,然后在反向传播中计算
\frac{\partial J}{\partial \theta}

#前向传播 J = theta * x
def forward_propagation(x, theta):

    J = np.dot(theta,x)

    return J

#反向传播dtheta即为导数(梯度)
def backward_propagation(x, theta):
    
    dtheta = x

    return dtheta

来看一下详细的计算步骤:
首先是计算导数(梯度)值"gradapprox"
1. \theta^{+} = \theta + \varepsilon
2. \theta^{-} = \theta - \varepsilon
3. J^{+} = J(\theta^{+})
4. J^{-} = J(\theta^{-})
5. gradapprox = \frac{J^{+} - J^{-}}{2 \varepsilon}
然后,计算梯度的反向传播值"grad",最后计算误差"difference"
difference = \frac {\mid\mid grad - gradapprox \mid\mid_2}{\mid\mid grad \mid\mid_2 + \mid\mid gradapprox \mid\mid_2} \tag{2}
这里设置误差的阈值是10^{-7},即当difference的值小于10^{-7}时,认为我们的计算结果是正确的。

def gradient_check(x, theta, epsilon = 1e-7):
   
    # Compute gradapprox using left side of formula (1). epsilon is small enough, you don't need to worry about the limit.
    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
    
    # Compute grad in the backward propagation
    grad = backward_propagation(x, theta)

    # Check if gradapprox is close enough to the output of backward_propagation()
    numerator = np.linalg.norm(grad - gradapprox)                      # Step 1'
    denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox)    # Step 2'
    difference = numerator / denominator                               # Step 3'
    
    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

可以看到,结果显示梯度的计算是正确的,因为误差小于阈值。

那么,在一般的情况下,输入都是高于一维的。在训练神经网络的时候,实际上模型参数\theta都是多维矩阵形式的权重W^{[l]}和偏置b^{[l]},接下来是多维梯度校验的内容!

多维梯度校验

下图表示的是一个三层神经网络的梯度校验过程:


Figure 2 : deep neural network
# DNN的前向传播
def forward_propagation_n(X, Y, parameters):
    
    # 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

# DNN的反向传播
def backward_propagation_n(X, Y, cache):
    
    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    # Hint
    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)    # Hint
    
    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

如果想比较"gradapprox"与反向传播的梯度,公式仍然是\frac{\partial J}{\partial \theta} = \lim_{\varepsilon \to 0} \frac{J(\theta + \varepsilon) - J(\theta - \varepsilon)}{2 \varepsilon} \tag{1}
这里不同的是,\theta不再是标量,而是一个名为"parameters"的字典(字典在python的基本数据类型中有简单提到,大概两三周的样子会详细介绍)。下面是一个函数"dictionary_to_vector()",它通过将参数(W1, b1, W2, b2, W3, b3)整形并连接来完成从字典"parameters"到向量"values"的转换。

Figure 3 : dictionary_to_vector() and vector_to_dictionary()

同样的,在反向传播中会产生字典"gradients",我会用函数"gradients_to_vector()"将它转换为向量"grad",实现代码如下:

# 友情赠送向量转换为字典
def vector_to_dictionary(theta):

    parameters = {}
    parameters["W1"] = theta[:20].reshape((5,4))
    parameters["b1"] = theta[20:25].reshape((5,1))
    parameters["W2"] = theta[25:40].reshape((3,5))
    parameters["b2"] = theta[40:43].reshape((3,1))
    parameters["W3"] = theta[43:46].reshape((1,3))
    parameters["b3"] = theta[46:47].reshape((1,1))

    return parameters


def gradients_to_vector(gradients):
  
    count = 0
    for key in ["dW1", "db1", "dW2", "db2", "dW3", "db3"]:
        # flatten parameter
        new_vector = np.reshape(gradients[key], (-1,1))
        
        if count == 0:
            theta = new_vector
        else:
            theta = np.concatenate((theta, new_vector), axis=0)
        count = count + 1

    return theta

下面是高维梯度校验的详细步骤:
For each i in num_parameters:
计算J_plus[i]:
1. 从np.copy(parameters_values)提取值赋给\theta^{+}
2. 把\theta^{+}_i赋值为\theta^{+}_i + \varepsilon
3. 用forward_propagation_n(x, y, vector_to_dictionary(\theta^{+} ))来计算J^{+}_i
计算J_minus[i]:对\theta^{-}做相同的操作
计算gradapprox:gradapprox[i] = \frac{J^{+}_i - J^{-}_i}{2 \varepsilon}
这里会得到梯度的近似计算值向量"gradapprox",通过反向传播会得到梯度值向量"grad",比较两个向量并计算误差即可。

def gradient_check_n(parameters, gradients, X, Y, epsilon = 1e-7):
    
    # 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))
    
    # Compute gradapprox
    for i in range(num_parameters):
        
        # Compute 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
        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
        
        # Compute J_minus[i]. Inputs: "parameters_values, epsilon". Output = "J_minus[i]".
        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
        
        # Compute gradapprox[i]
        gradapprox[i] = (J_plus[i] - J_minus[i]) / (2 * epsilon)
    
    # Compare gradapprox to backward propagation gradients by computing difference.
    numerator = np.linalg.norm(grad - gradapprox)                     # Step 1'
    denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox)   # Step 2'
    difference = numerator / denominator                              # Step 3'

    if difference > 1e-7:
        print ("There is a mistake in the backward propagation! difference = " + str(difference))
    else:
        print ("Your backward propagation works perfectly fine! difference = " + str(difference) )
    
    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)

结果如下

There is a mistake in the backward propagation! difference = 0.2850931567761624

可以看到,这里梯度校验显示出错,因为吴恩达老师在反向传播"backward_propagation_n()"里面故意写了两个错误,感兴趣的朋友可以找一下,改了之后的输出就是下面这样的:

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

注意

  • 梯度校验是用来检验反向传播的梯度与梯度的数值近似解(用前向传播来计算)之间的接近程度;
  • 要在没有应用dropout功能的情况下运行梯度校验算法,否则会出现参数向量长度错误;
  • 梯度校验很慢,因此不会在每次训练迭代时运行。通常梯度校验只是用来确保代码的正确性,然后再将梯度校验关闭进行实际的神经网络训练。

写在后面

好了,吴恩达老师的第二门课程第一周作业已经整理完毕,期待下一周的内容——算法优化!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 文章主要分为:一、深度学习概念;二、国内外研究现状;三、深度学习模型结构;四、深度学习训练算法;五、深度学习的优点...
    艾剪疏阅读 21,975评论 0 58
  • 显示某个workCopy的svn相关信息
    iOneWay阅读 5,168评论 1 0
  • 以诗代酒,回敬岁月。 《未完》 这一生 多少故事搁浅 半截的诗 未完的爱 我一生匆忙 所有的事/草草结尾 《秘密》...
    f3494c632b49阅读 904评论 58 53
  • 对于吃货的我,看到《决战美食》这部电影时便迫不及待的打开观看。看完之后,作为一部电影或许并不出众,但有些情节...
    落云的鱼阅读 442评论 0 0
  • 这一周频繁的做梦。 梦到有一只可爱粘人到不行的小奶猫。 温暖的触感,被治愈熨帖的心情。 昨夜梦到你 明明最近好像都...
    梦到不想醒的梦阅读 226评论 0 0