吳恩達深度學習 第二課第一周編程作業_Gradient Checking(梯度檢查)


Gradient Checking 梯度檢查

聲明

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

參考:https://blog.csdn.net/u013733326/article/details/79847918

參考Kulbear 的 【Initialization】【Regularization】【Gradient Checking】,以及念師【10. 初始化、正則化、梯度檢查實戰】,以及何寬


歡迎來到本周的期末作業!在這項作業中,你將學習如何實現和使用漸變檢查。
你是一個團隊的一員,致力於全球范圍內的移動支付,並被要求建立一個深度學習模型來檢測欺詐行為——每當有人進行支付時,你都想看看支付是否有欺詐行為,比如用戶的賬戶是否被黑客占領。
但是反向傳播的實現相當具有挑戰性,有時還存在缺陷。因為這是一個任務關鍵型應用程序,所以您公司的首席執行官希望確定您的反向傳播實現是正確的。你的首席執行官說,“給我一個證據,證明你的反向傳播是有效的!”為了保證這一點,您將使用“梯度檢查”
開始吧!

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

1) How does gradient checking work?  梯度檢查是如何工作的?

反向傳播計算梯度,其中θ表示模型的參數。使用前向傳播和損失函數計算 J,因為前向傳播相對容易實現,所以您確信自己是正確的,因此您幾乎百分之百確定您正確地計算了成本J。因此,您可以使用計算J的代碼來驗證用於計算的代碼。

讓我們回顧一下導數(或梯度)的定義:

 

 

 

如果你不熟悉“limε→0”表示法,那只是表示“當ε真的很小時”

我們知道以下幾點:

是你想要確保你計算正確的東西。

•您可以計算J(θ+ε)和J(θ-ε)(在θ是實數的情況下),因為您確信J的實現是正確的。

讓我們用等式(1)和一個小的ε值來說服您的CEO,您用於計算的代碼是正確的!

2) 1-dimensional gradient checking 一維梯度檢查

考慮一維線性函數J(θ)=θx,該模型僅包含一個實值參數θ,以x為輸入。
您將實現計算J(.)及其導數的代碼。然后使用梯度檢查來確保J的導數計算是正確的。

 

 

**Figure 1** : **1D linear model** 圖一 一維線性模型

上圖顯示了關鍵的計算步驟:首先從x開始,然后計算函數J(x)(“前向傳播”)。然后計算導數(“反向傳播”)。


練習:為這個簡單函數實現“正向傳播”和“反向傳播”。一、 在兩個不同的函數中計算J(.)(“前向傳播”)及其相對於θ的導數(“反向傳播”)

 1 # GRADED FUNCTION: forward_propagation
 2 
 3 def forward_propagation(x, theta):
 4     """
 5     Implement the linear forward propagation (compute J) presented in Figure 1 (J(theta) = theta * x)
 6     
 7     Arguments:
 8     x -- a real-valued input
 9     theta -- our parameter, a real number as well
10     
11     Returns:
12     J -- the value of function J, computed using the formula J(theta) = theta * x
13     """
14     
15     ### START CODE HERE ### (approx. 1 line)
16     J = theta * x
17     ### END CODE HERE ###
18     
19     return J
# GRADED FUNCTION: forward_propagation
x, theta = 2, 4
J = forward_propagation(x, theta)
print ("J = " + str(J))

 

 

練習:現在,實現圖1中的反向傳播步驟(導數計算)。也就是說,計算J(θ)=θx相對於θ的導數。為了省去做微積分,你應該得到dtheta==x。

 1 # GRADED FUNCTION: backward_propagation
 2 
 3 def backward_propagation(x, theta):
 4     """
 5     Computes the derivative of J with respect to theta (see Figure 1).
 6     
 7     Arguments:
 8     x -- a real-valued input
 9     theta -- our parameter, a real number as well
10     
11     Returns:
12     dtheta -- the gradient of the cost with respect to theta 相對於θ的成本梯度
13     """
14     
15     ### START CODE HERE ### (approx. 1 line)
16     dtheta = x
17     ### END CODE HERE ###
18     
19     return dtheta
# GRADED FUNCTION: backward_propagation
x, theta = 2, 4
dtheta = backward_propagation(x, theta)
print ("dtheta = " + str(dtheta))

 

 

練習:為了證明反向傳播函數正確地計算了梯度,讓我們實現梯度檢查。
說明:

•首先使用上述公式(1)和較小的ε值計算“gradeapprox”。以下是要遵循的步驟:

 

 

•然后使用反向傳播計算梯度,並將結果存儲在變量“grad”

•最后,使用以下公式計算“gradeapprow”和“grad”之間的相對差

 

 

 

計算此公式需要3個步驟:

1、使用np.linalg.norm(...)計算分子

2、計算分母。你需要使用np.linalg.norm(…)兩次。

3、把他們相除

•如果這個差異很小(比如小於10-7),您可以非常確信您已經正確地計算了梯度。否則,梯度計算可能會出錯。

 1 # GRADED FUNCTION: gradient_check
 2 
 3 def gradient_check(x, theta, epsilon = 1e-7):
 4     """
 5     Implement the backward propagation presented in Figure 1.
 6     
 7     Arguments:
 8     x -- a real-valued input
 9     theta -- our parameter, a real number as well
10     epsilon -- tiny shift to the input to compute approximated gradient with formula(1)
11     
12     Returns:
13     difference -- difference (2) between the approximated gradient and the backward propagation gradient近似梯度和后向傳播梯度之間的差異
14     """
15     
16     # Compute gradapprox using left side of formula (1). epsilon is small enough, you don't need to worry about the limit.
17     ### START CODE HERE ### (approx. 5 lines)
18     thetaplus = theta + epsilon                             # Step 1
19     thetaminus = theta - epsilon                              # Step 2
20     J_plus = forward_propagation(x, thetaplus)                                 # Step 3
21     J_minus = forward_propagation(x, thetaminus)                               # Step 4
22     gradapprox =  (J_plus - J_minus) / (2 * epsilon)                            # Step 5
23     ### END CODE HERE ###
24     
25     # Check if gradapprox is close enough to the output of backward_propagation() 檢查gradapprox是否足夠接近backward_propagation()的輸出
26     ### START CODE HERE ### (approx. 1 line)
27     grad = backward_propagation(x, theta)
28     ### END CODE HERE ###
29     
30     ### START CODE HERE ### (approx. 1 line)
31     numerator =  np.linalg.norm(grad - gradapprox)                            # Step 1'
32     denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox)                            # Step 2'
33     difference = numerator / denominator                             # Step 3'
34     ### END CODE HERE ###
35     
36     if difference < 1e-7:
37         print ("The gradient is correct!")
38     else:
39         print ("The gradient is wrong!")
40     
41     return difference
# GRADED FUNCTION: gradient_check
x, theta = 2, 4
difference = gradient_check(x, theta)
print("difference = " + str(difference))

結果:

 

 

恭喜你,誤差小於10-7閾值。因此,您可以有很高的信心,您已經正確地計算了反向傳播()中的梯度
現在,在更一般的情況下,成本函數J有不止一個一維輸入。當你訓練一個神經網絡時,θ實際上由多個矩陣W[l]和偏差b[l]組成!重要的是要知道如何使用高維輸入進行梯度檢查。開始吧!

3) N-dimensional gradient checking N維梯度檢查

下圖描述了欺詐檢測模型的正向和反向傳播。高維參數是怎樣計算的呢?我們看一下下圖:

**Figure 2** : **deep neural network** 圖2 深度神經網絡
*LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID*

 

讓我們來看看您的前向傳播和后向傳播的實現

 1 def forward_propagation_n(X, Y, parameters):
 2     """
 3     Implements the forward propagation (and computes the cost) presented in Figure 3.
 4     
 5     Arguments:
 6     X -- training set for m examples
 7     Y -- labels for m examples 
 8     parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":包含參數“W1”,“b1”,“W2”,“b2”,“W3”,“b3”的python字典:
 9                     W1 -- weight matrix of shape (5, 4)權重矩陣,維度為(5,4)
10                     b1 -- bias vector of shape (5, 1)偏向量,維度為(5,1)
11                     W2 -- weight matrix of shape (3, 5)
12                     b2 -- bias vector of shape (3, 1)
13                     W3 -- weight matrix of shape (1, 3)
14                     b3 -- bias vector of shape (1, 1)
15     
16     Returns:
17     cost -- the cost function (logistic cost for one example) - 成本函數(logistic)
18     """
19     
20     # retrieve parameters
21     m = X.shape[1]
22     W1 = parameters["W1"]
23     b1 = parameters["b1"]
24     W2 = parameters["W2"]
25     b2 = parameters["b2"]
26     W3 = parameters["W3"]
27     b3 = parameters["b3"]
28 
29     # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID
30     Z1 = np.dot(W1, X) + b1
31     A1 = relu(Z1)
32     Z2 = np.dot(W2, A1) + b2
33     A2 = relu(Z2)
34     Z3 = np.dot(W3, A2) + b3
35     A3 = sigmoid(Z3)
36 
37     # Cost
38     logprobs = np.multiply(-np.log(A3),Y) + np.multiply(-np.log(1 - A3), 1 - Y)
39     cost = 1./m * np.sum(logprobs)
40     
41     cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3)
42     
43     return cost, cache

現在,運行反向傳播。

 1 def backward_propagation_n(X, Y, cache):
 2     """
 3     Implement the backward propagation presented in figure 2.
 4     
 5     Arguments:
 6     X -- input datapoint, of shape (input size, 1) 輸入數據點(輸入節點數量,1)
 7     Y -- true "label"標簽
 8     cache -- cache output from forward_propagation_n() 來自forward_propagation_n()的cache輸出
 9     
10     Returns:
11     gradients -- A dictionary with the gradients of the cost with respect to each parameter, activation and pre-activation variables. 一個字典,其中包含與每個參數、激活和激活前變量相關的成本梯度。
12     """
13     
14     m = X.shape[1]
15     (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache
16     
17     dZ3 = A3 - Y
18     dW3 = 1./m * np.dot(dZ3, A2.T)
19     db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)
20     
21     dA2 = np.dot(W3.T, dZ3)
22     dZ2 = np.multiply(dA2, np.int64(A2 > 0))
23     dW2 = 1./m * np.dot(dZ2, A1.T)
24     db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)
25     
26     dA1 = np.dot(W2.T, dZ2)
27     dZ1 = np.multiply(dA1, np.int64(A1 > 0))
28     dW1 = 1./m * np.dot(dZ1, X.T)
29     db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True)
30     
31     gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,
32                  "dA2": dA2, "dZ2": dZ2, "dW2": dW2, "db2": db2,
33                  "dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1}
34     
35     return gradients

 

您在欺詐檢測測試集上獲得了一些結果,但您對您的模型沒有100%的把握。沒有人是完美的!讓我們實現梯度檢查來驗證梯度是否正確。

 

梯度檢查是如何工作的?

如1)和2)中所述,您需要將“gradeapproach”與反向傳播計算的梯度進行比較。公式仍然是:

 

 

然而,θ不再是標量。這是一本叫做“參數”的字典。我們為您實現了一個函數“dictionary_to_vector()”。它將“parameters”字典轉換為一個名為“values”的向量,該向量通過將所有參數(W1、b1、W2、b2、W3、b3)重塑為向量並將它們連接起來而獲得。反函數是“向量字典”,它輸出“參數”字典

**Figure 2** : **dictionary_to_vector() and vector_to_dictionary()**
You will need these functions in gradient_check_n()

我們還使用gradients_to_vector()將“gradients”字典轉換為向量“grad”。你不用擔心這個。
練習:實現梯度檢查。
說明:下面是一些偽代碼,可以幫助您實現梯度檢查。
對於每個i in num_參數:

 1 # GRADED FUNCTION: gradient_check_n
 2 
 3 def gradient_check_n(parameters, gradients, X, Y, epsilon = 1e-7):
 4     """
 5     Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n
 6     檢查backward_propagation_n是否正確計算forward_propagation_n輸出的成本梯度
 7     
 8     Arguments:
 9     parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3": parameters - 包含參數“W1”,“b1”,“W2”,“b2”,“W3”,“b3”的python字典:
10     grad -- output of backward_propagation_n, contains gradients of the cost with respect to the parameters.grad_output_propagation_n的輸出包含與參數相關的成本梯度。 
11     x -- input datapoint, of shape (input size, 1)
12     y -- true "label"
13     epsilon -- tiny shift to the input to compute approximated gradient with formula(1) 計算輸入的微小偏移以計算近似梯度
14     
15     Returns:
16     difference -- difference (2) between the approximated gradient and the backward propagation gradient
17     """
18     
19     # Set-up variables 設置變量
20     parameters_values, _ = dictionary_to_vector(parameters) #這邊keys用不到,可以用“_”代替
21     grad = gradients_to_vector(gradients)
22     num_parameters = parameters_values.shape[0]
23     J_plus = np.zeros((num_parameters, 1))
24     J_minus = np.zeros((num_parameters, 1))
25     gradapprox = np.zeros((num_parameters, 1))
26     
27     # Compute gradapprox
28     for i in range(num_parameters):
29         
30         # Compute J_plus[i]. Inputs: "parameters_values, epsilon". Output = "J_plus[i]".計算J_plus [i]。輸入:“parameters_values,epsilon”。輸出=“J_plus [i]”
31         # "_" is used because the function you have to outputs two parameters but we only care about the first one
32         ### START CODE HERE ### (approx. 3 lines)
33         thetaplus =  np.copy(parameters_values)                          # Step 1
34         thetaplus[i][0] = thetaplus[i][0] + epsilon                             # Step 2
35         J_plus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaplus))                                # Step 3
36         ### END CODE HERE ###
37         
38         # Compute J_minus[i]. Inputs: "parameters_values, epsilon". Output = "J_minus[i]".
39         ### START CODE HERE ### (approx. 3 lines)
40         thetaminus = np.copy(parameters_values)                                  # Step 1
41         thetaminus[i][0] =  thetaminus[i][0] - epsilon                            # Step 2        
42         J_minus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaminus))                # Step 3
43         ### END CODE HERE ###
44         
45         # Compute gradapprox[i]
46         ### START CODE HERE ### (approx. 1 line)
47         gradapprox[i] = (J_plus[i] - J_minus[i]) / (2. * epsilon)
48         ### END CODE HERE ###
49     
50     # Compare gradapprox to backward propagation gradients by computing difference.
51     ### START CODE HERE ### (approx. 1 line)
52     numerator = np.linalg.norm(grad - gradapprox)                                       # Step 1'
53     denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox)            # Step 2'
54     difference = numerator / denominator                                     # Step 3'
55     ### END CODE HERE ###
56 
57     if difference > 1e-7:
58         print ("\033[93m" + "There is a mistake in the backward propagation! difference = " + str(difference) + "\033[0m")
59     else:
60         print ("\033[92m" + "Your backward propagation works perfectly fine! difference = " + str(difference) + "\033[0m")
61     
62     return difference
# GRADED FUNCTION: gradient_check_n
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)

 

 

我們給你的反向傳播代碼似乎有錯誤!很好,你已經實現了梯度檢查。返回反向傳播並嘗試查找/更正錯誤(提示:檢查dW2和db1)。當你認為你已經修復了梯度檢查。請記住,如果修改代碼,則需要重新執行定義反向傳播的單元格
你能用梯度檢查來證明你的導數計算正確嗎?即使作業的這一部分沒有評分,我們強烈建議您嘗試找到錯誤重新運行漸變檢查,直到您確信backprop現在已經正確實現。

 

 

 

 修改后:

 

 

 

Note

梯度檢查很慢!用近似梯度計算成本很高。由於這個原因,我們不在訓練期間的每次迭代中運行梯度檢查。只需幾次檢查梯度是否正確。

梯度檢查,至少我們已經介紹過了,對dropout不起作用。你通常會運行梯度檢查算法沒有輟學,以確保你的backprop是正確的,然后添加輟學。
恭喜你,你可以相信你的深度學習模型是正確的!你甚至可以用這個來說服你的CEO。:)
**你應該記住這本筆記本**:-梯度檢查 驗證了 反向傳播的梯度 和 梯度的數值近似(使用正向傳播計算)之間  的  接近度。

梯度檢查很慢,所以我們不是在每次訓練迭代中都運行它。您通常只運行它以確保您的代碼是正確的,然后關閉它並使用backprop進行實際的學習過程。

 

 

 

 

 

 

 


免責聲明!

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



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