1. 程式人生 > >深度學習DeepLearning.ai系列課程學習總結:8. 多層神經網路程式碼實戰

深度學習DeepLearning.ai系列課程學習總結:8. 多層神經網路程式碼實戰

轉載過程中,圖片丟失,程式碼顯示錯亂。

為了更好的學習內容,請訪問原創版本:

http://www.missshi.cn/api/view/blog/59ac0136e519f50d040001a7

Ps:初次訪問由於js檔案較大,請耐心等候(8s左右)

本節課中,我們將學習如何利用Python的來實現具有多個隱藏層的圖片分類問題。

這是本課程的第三個Python程式碼實踐,通過本節課的實踐,你將會一步步的建立一個多層神經網路模型。

此外,通過這次建立的多層神經網路模型,可以將之前的貓分類問題的準確率提升到80%。

本文學習完成後,希望你可以做到:

1. 使用非線性對映單元(例如ReLU)去改善你的模型。

2. 建立一個多個隱藏層的神經網路

3. 建立一個易於呼叫的模型類

第一步:引入相關的依賴包

  1. import numpy as np
  2. import time
  3. import h5py
  4. import matplotlib.pyplot as plt
  5. import scipy
  6. from PIL importImage
  7. from testCases_v2 import*#提供了一些測試函式所有的資料和方法
  8. from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward  #封裝好的方法
  9. from dnn_app_utils_v2 
    import*
  10. %matplotlib inline
  11. plt.rcParams['figure.figsize']=(5.0,4.0)# set default size of plots
  12. plt.rcParams['image.interpolation']='nearest'
  13. plt.rcParams['image.cmap']='gray'
  14. %load_ext autoreload
  15. %autoreload 2
  16. np.random.seed(1)

其中,sigmoid函式如下:

  1. def sigmoid(Z):
  2. """
  3.     Implements the sigmoid activation in numpy
  4.     Arguments:
  5.     Z -- numpy array of any shape
  6.     Returns:
  7.     A -- output of sigmoid(z), same shape as Z
  8.     cache -- returns Z as well, useful during backpropagation
  9.     """
  10.     A =1/(1+np.exp(-Z))
  11.     cache = Z
  12. return A, cache

sigmoid_backward函式如下:

  1. def sigmoid_backward(dA, cache):
  2. """
  3.     Implement the backward propagation for a single SIGMOID unit.
  4.     Arguments:
  5.     dA -- post-activation gradient, of any shape
  6.     cache -- 'Z' where we store for computing backward propagation efficiently
  7.     Returns:
  8.     dZ -- Gradient of the cost with respect to Z
  9.     """
  10.     Z = cache
  11.     s =1/(1+np.exp(-Z))
  12.     dZ = dA * s *(1-s)
  13. assert(dZ.shape == Z.shape)
  14. return dZ

relu函式如下:

  1. def relu(Z):
  2. """
  3.     Implement the RELU function.
  4.     Arguments:
  5.     Z -- Output of the linear layer, of any shape
  6.     Returns:
  7.     A -- Post-activation parameter, of the same shape as Z
  8.     cache -- a python dictionary containing "A" ; stored for computing the backward pass efficiently
  9.     """
  10.     A = np.maximum(0,Z)
  11. assert(A.shape == Z.shape)
  12.     cache = Z 
  13. return A, cache

relu_backward函式如下:

  1. def relu_backward(dA, cache):
  2. """
  3.     Implement the backward propagation for a single RELU unit.
  4.     Arguments:
  5.     dA -- post-activation gradient, of any shape
  6.     cache -- 'Z' where we store for computing backward propagation efficiently
  7.     Returns:
  8.     dZ -- Gradient of the cost with respect to Z
  9.     """
  10.     Z = cache
  11.     dZ = np.array(dA, copy=True)# just converting dz to a correct object.
  12. # When z <= 0, you should set dz to 0 as well. 
  13.     dZ[<=0]=0
  14. assert(dZ.shape == Z.shape)
  15. return dZ

第二步:任務描述

接下來,我們首先簡單的描述一下我們需要實現的功能。

為了最終建立我們的神經網路模型,我們首先需要實現其中相關的一些方法。

接下來,我們將會去依次實現這些需要的方法。

一個神經網路的計算過程如下:

1. 初始化網路引數

2. 前向傳播

    2.1 計算一層的中線性求和的部分

    2.2 計算啟用函式的部分(ReLU使用L-1次,Sigmod使用1次)

    2.3 結合線性求和與啟用函式

3. 計算誤差

4. 反向傳播

    4.1 線性部分的反向傳播公式

    4.2 啟用函式部分的反向傳播公式

    4.3 結合線性部分與啟用函式的反向傳播公式

5. 更新引數

整個流程圖如下圖所示:

第三步:初始化

接下來,我們需要實現初始化函式

對於一個兩層的神經網路結構而言,模型結構是線性->ReLU->線性->sigmod函式。

初始化函式如下:

  1. def initialize_parameters(n_x, n_h, n_y):
  2. """
  3.     Argument:
  4.     n_x -- size of the input layer
  5.     n_h -- size of the hidden layer
  6.     n_y -- size of the output layer
  7.     Returns:
  8.     parameters -- python dictionary containing your parameters:
  9.                     W1 -- weight matrix of shape (n_h, n_x)
  10.                     b1 -- bias vector of shape (n_h, 1)
  11.                     W2 -- weight matrix of shape (n_y, n_h)
  12.                     b2 -- bias vector of shape (n_y, 1)
  13.     """
  14.     np.random.seed(1)
  15. ### START CODE HERE ### (≈ 4 lines of code)
  16.     W1 = np.random.randn(n_h, n_x)*0.01
  17.     b1 = np.zeros((n_h,1))
  18.     W2 = np.random.randn(n_y, n_h)*0.01
  19.     b2 = np.zeros((n_y,1))
  20. ### END CODE HERE ###
  21. assert(W1.shape ==(n_h, n_x))
  22. assert(b1.shape ==(n_h,1))
  23. assert(W2.shape ==(n_y, n_h))
  24. assert(b2.shape ==(n_y,1))
  25.     parameters ={"W1": W1,
  26. "b1": b1,
  27. "W2": W2,
  28. "b2": b2}
  29. return parameters  

驗證一下:

  1. parameters = initialize_parameters(3,2,1)
  2. print("W1 = "+ str(parameters["W1"]))
  3. print("b1 = "+ str(parameters["b1"]))
  4. print("W2 = "+ str(parameters["W2"]))
  5. print("b2 = "+ str(parameters["b2"]))

那麼,對於一個L層的神經網路而言呢?初始化是什麼樣的?

假設X的維度為(12288,209)

第l層的W的維度為(layer_dims[l], layer_dims[l-1])。

而第l層的b的維度為(layer_dims[l], 1)。

因此,初始化函式如下:

  1. def initialize_parameters_deep(layer