目錄

@[toc]

前言

反向傳播計算梯度\(\frac{\partial J}{\partial \theta}\)\(\theta\)表示模型的參數。 \(J\)是使用正向傳播和損失函數來計算的。
計算公式如下:
$$ \frac{\partial J}{\partial \theta} = \lim_{\varepsilon \to 0} \frac{J(\theta + \varepsilon) - J(\theta - \varepsilon)}{2 \varepsilon} \tag{1}$$
因爲向前傳播相對容易實現,所以比較容易獲得正確的結果,確定要計算成本\(J\) 正確。因此,可以通過計算\(J\) 驗證計算\(\frac{\partial J}{\partial \theta}\)

一維梯度檢查

一維線性函數\(J(\theta) = \theta x\)。該模型只包含一個實值參數\(\theta\),並採取x作爲輸入。

一維線性模型
上圖顯示了關鍵的計算步驟:首先從開始$x$,然後評估該功能 $J(x)$(“前向傳播”)。然後計算導數 $\frac{\partial J}{\partial \theta}$(“反向傳播”)。下面就用代碼來實現。 ## 導入依賴包 首先我們要導入相應的依賴包,其中一些工具類可以在[這裏下載](https://resource.doiduoyi.com/#6g0m9sm)。
# coding=utf-8
from testCases import *
from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector
## 正向傳播 下面是線性前向傳播函數代碼:
def forward_propagation(x, theta):
    """
    實現線性向前傳播(計算J) (J(theta) = theta * x)

    Arguments:
    x -- 一個實值輸入
    theta -- 我們的參數,一個實數。

    Returns:
    J -- 函數J的值, 計算使用公式 J(theta) = theta * x
    """
    J = theta * x
    return J
## 反向傳播 線性反向傳播函數,計算公式是 $dtheta = \frac { \partial J }{ \partial \theta} = x$:
def backward_propagation(x, theta):
    """
    計算J對的導數

    Arguments:
    x -- 一個實值輸入
    theta -- 我們的參數,一個實數。

    Returns:
    dtheta -- 成本的梯度。
    """

    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”中。 - 最後,使用以下公式計算“gradapprox”和“grad”之間的相對差異: $$ difference = \frac {\mid\mid grad - gradapprox \mid\mid_2}{\mid\mid grad \mid\mid_2 + \mid\mid gradapprox \mid\mid_2} \tag{2}$$ 如果計算得到的結果足夠小,就證明是梯度沒問題了,以下是梯度檢查代碼:
def gradient_check(x, theta, epsilon=1e-7):
    """
    實現反向傳播

    Arguments:
    x -- 一個實值輸入
    theta -- 我們的參數,一個實數
    epsilon -- 用公式對輸入進行微小位移計算近似梯度

    Returns:
    difference -- 近似梯度與反向傳播梯度之間的差異。
    """

    # 用公式的左邊來計算gradapprox(1)
    thetaplus = theta + epsilon  # Step 1
    thetaminus = theta - epsilon  # Step 2
    J_plus = thetaplus * x  # Step 3
    J_minus = thetaminus * x  # Step 4
    gradapprox = (J_plus - J_minus) / (2 * epsilon)  # Step 5

    # :檢查gradapprox是否足夠接近backward_propagation()的輸出
    grad = backward_propagation(x, theta)

    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 ("梯度是正確的!")
    else:
        print ("梯度是錯誤的!")

    return difference
然後執行這一段代碼,看看梯度是否正確:
if __name__ == "__main__":
    x, theta = 2, 4
    difference = gradient_check(x, theta)
    print("difference = " + str(difference))
當結果滿足`difference < 1e-7`,梯度是正確的。
梯度是正確的!
difference = 2.91933588329e-10
# 多維梯度檢查 多維梯度模型的向前和向後傳播如下圖: ![](/static/files/2018-04-16/20d23c781cbf4db2bd6cbc2674863cb2.png)
多維梯度
LINEAR - > RELU - > LINEAR - > RELU - > LINEAR - > SIGMOID
## 向前傳播 多維梯度的向前傳播:
def forward_propagation_n(X, Y, parameters):
    """
    實現前面的傳播(並計算成本),如圖3所示。

    Arguments:
    X -- m例的訓練集。
    Y -- m的樣本的標籤
    parameters -- 包含參數的python字典 "W1", "b1", "W2", "b2", "W3", "b3":
                    W1 -- 權重矩陣的形狀(5, 4)
                    b1 -- 偏差的矢量形狀(5, 1)
                    W2 -- 權重矩陣的形狀(3, 5)
                    b2 -- 偏差的矢量形狀(3, 1)
                    W3 -- 權重矩陣的形狀(1, 3)
                    b3 -- 偏差的矢量形狀(1, 1)

    Returns:
    cost -- 成本函數(一個樣本的邏輯成本)
    """

    # 檢索參數
    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):
    """
    實現反向傳播。

    Arguments:
    X -- 輸入數據點,形狀(輸入大小,1)
    Y -- true "label"
    cache -- 緩存輸出forward_propagation_n()

    Returns:
    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 # 這有個錯誤
    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) # 這有個錯誤

    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
## 開始檢查 同樣這個還是用回來之前的公式: $$ \frac{\partial J}{\partial \theta} = \lim_{\varepsilon \to 0} \frac{J(\theta + \varepsilon) - J(\theta - \varepsilon)}{2 \varepsilon} \tag{3}$$ 但有一些不同的是,$\theta$ 不再是一個標量。這是一個叫做“參數”的字典。 其中函數是“ vector_to_dictionary”,它輸出“參數”字典,操如下圖: ![](/static/files/2018-04-16/4e6040b33c084546bb6fb37514a2a979.png) For each i in num_parameters: - 計算 `J_plus[i]`: 1. Set $\theta^{+}$ to `np.copy(parameters_values)` 2. Set $\theta^{+}_i$ to $\theta^{+}_i + \varepsilon$ 3. 使用 `forward_propagation_n(x, y, vector_to_dictionary(`$\theta^{+}$ `))`計算$J^{+}_i$ - 計算 `J_minus[i]`:同樣計算$\theta^{-}$ - 計算$gradapprox[i] = \frac{J^{+}_i - J^{-}_i}{2 \varepsilon}$ 最後使用以下的公式計算結果差異: $$ difference = \frac {\| grad - gradapprox \|_2}{\| grad \|_2 + \| gradapprox \|_2 } \tag{4}$$
def gradient_check_n(parameters, gradients, X, Y, epsilon=1e-7):
    """
    檢查backward_propagation_n是否正確地計算了正向傳播的成本輸出的梯度。

    Arguments:
    parameters --包含參數的python字典 "W1", "b1", "W2", "b2", "W3", "b3":
    grad -- backward_propagation_n的輸出包含參數的成本梯度。
    x -- 輸入數據點,形狀(輸入大小,1)
    y -- true "label"
    epsilon -- 用公式對輸入進行微小位移計算近似梯度

    Returns:
    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))

    # Compute gradapprox
    for i in range(num_parameters):
        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

        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)

    # 通過計算與反向傳播梯度比較差異。
    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 > 2e-7:
        print (
            "\033[93m" + "反向傳播有一個錯誤! difference = " + str(difference) + "\033[0m")
    else:
        print (
            "\033[92m" + "你的反向傳播效果非常好! difference = " + str(difference) + "\033[0m")

    return difference
最後運行一下這個多維梯度檢測:
if __name__ == "__main__":
    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)
以下是輸出結果,可以看到已經超過最低的誤差了:
反向傳播有一個錯誤! difference = 0.285093156781
所以我們知道`backward_propagation_n`的代碼有錯誤!這時我們可以去檢查`backward_propagation`並嘗試查找/更正錯誤,最後我們找到以下的代碼出了錯誤:
dW2 = 1. / m * np.dot(dZ2, A1.T) * 2
db1 = 4. / m * np.sum(dZ1, axis=1, keepdims=True)
然後我們修改正確的代碼:
dW2 = 1. / m * np.dot(dZ2, A1.T)
db1 = 1. / m * np.sum(dZ1, axis=1, keepdims=True)
我們再檢查一遍的結果是:
你的反向傳播效果非常好! difference = 1.18904178766e-07
# 參考資料 1. http://deeplearning.ai/


>該筆記是學習吳恩達老師的課程寫的。初學者入門,如有理解有誤的,歡迎批評指正!
小夜