吳恩達深度學習第一課--第四周多層神經網絡實現

聲明

本文參考何寬念師

前言

本次教程,將構建兩個神經網絡,一個是具有兩個隱藏層的神經網絡,一個是多隱藏層的神經網絡。
一個神經網絡的計算過程如下:

  1. 初始化網絡參數
  2. 前向傳播
  • 計算一層的中線性求和的 部分
  • 計算激活函數的部分(ReLU使用L-1次,sigmoid使用1次)
  • 結合線性求和與激活函數
  1. 計算誤差
  2. 反向傳播
  • 線性部分的反向傳播公式
  • 激活函數部分的反向傳播公式
  • 結合線性部分與激活函數的反向傳播公式
  1. 更新參數
  2. 整合

引入相關依賴包

import numpy as np
import h5py
import matplotlib.pyplot as plt
import testCases #參見資料包,或者在文章底部copy
from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward #參見資料包
import lr_utils #參見資料包,或者在文章底部copy
np.random.seed(1)

其中,sigmoid函數如下:

def sigmoid(Z):
    """
    Implements the sigmoid activation in numpy
    
    Arguments:
    Z -- numpy array of any shape
    
    Returns:
    A -- output of sigmoid(z), same shape as Z
    cache -- returns Z as well, useful during backpropagation
    """
    
    A = 1/(1+np.exp(-Z))
    cache = Z
    
    return A, cache

sigmoid_backward函數如下:

def sigmoid_backward(dA, cache):
    """
    Implement the backward propagation for a single SIGMOID unit.
 
    Arguments:
    dA -- post-activation gradient, of any shape
    cache -- 'Z' where we store for computing backward propagation efficiently
 
    Returns:
    dZ -- Gradient of the cost with respect to Z
    """
    
    Z = cache
    
    s = 1/(1+np.exp(-Z))
    dZ = dA * s * (1-s)
    
    assert (dZ.shape == Z.shape)
    
    return dZ

relu函數如下:

def relu(Z):
    """
    Implement the RELU function.
 
    Arguments:
    Z -- Output of the linear layer, of any shape
 
    Returns:
    A -- Post-activation parameter, of the same shape as Z
    cache -- a python dictionary containing "A" ; stored for computing the backward pass efficiently
    """
    
    A = np.maximum(0,Z)
    
    assert(A.shape == Z.shape)
    
    cache = Z 
    return A, cache

relu_backward函數如下:

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

初始化參數

對於一個兩層的神經網絡而言,模型結構是:線性–>Relu–>線性–>sigmoid函數。
初始化函數如下:

def initialize_parameters(n_x,n_h,n_y):
    """
    此函數是爲了初始化兩層網絡參數而使用的函數。
    參數:
        n_x - 輸入層節點數量
        n_h - 隱藏層節點數量
        n_y - 輸出層節點數量
    
    返回:
        parameters - 包含你的參數的python字典:
            W1 - 權重矩陣,維度爲(n_h,n_x)
            b1 - 偏向量,維度爲(n_h,1)
            W2 - 權重矩陣,維度爲(n_y,n_h)
            b2 - 偏向量,維度爲(n_y,1)

    """
    W1 = np.random.randn(n_h, n_x) * 0.01
    b1 = np.zeros((n_h, 1))
    W2 = np.random.randn(n_y, n_h) * 0.01
    b2 = np.zeros((n_y, 1))
    
    #使用斷言確保我的數據格式是正確的
    assert(W1.shape == (n_h, n_x))
    assert(b1.shape == (n_h, 1))
    assert(W2.shape == (n_y, n_h))
    assert(b2.shape == (n_y, 1))
    
    parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}
    
    return parameters  

測試:

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

結果:

W1 = [[ 0.01624345 -0.00611756 -0.00528172]
 [-0.01072969  0.00865408 -0.02301539]]
b1 = [[0.]
 [0.]]
W2 = [[ 0.01744812 -0.00761207]]
b2 = [[0.]]

兩層神經網絡測試完畢,那麼對於一個L層的神經網絡而言呢?初始化會是什麼樣的?
其中,W[l]W^{[l]}維度爲(layers_dims [l],layers_dims [l-1]),b[l]b^{[l]}維度爲(layers_dims [l],1)。

def initialize_parameters_deep(layers_dims):
    """
    此函數是爲了初始化多層網絡參數而使用的函數。
    參數:
        layers_dims - 包含我們網絡中每個圖層的節點數量的列表
    
    返回:
        parameters - 包含參數“W1”,“b1”,...,“WL”,“bL”的字典:
                     W1 - 權重矩陣,維度爲(layers_dims [1],layers_dims [1-1])
                     bl - 偏向量,維度爲(layers_dims [1],1)
    """
    np.random.seed(3)
    parameters = {}
    L = len(layers_dims)
    
    for l in range(1,L):
        parameters['W'+str(l)] = np.random.randn(layers_dims[l],layers_dims[l-1]) / np.sqrt(layers_dims[l-1])
        parameters['b'+str(l)] = np.zeros((layers_dims[l],1))
        
        #確保我要的數據的格式是正確的
        assert(parameters["W" + str(l)].shape == (layers_dims[l], layers_dims[l-1]))
        assert(parameters["b" + str(l)].shape == (layers_dims[l], 1))
        
    return parameters

測試:

layers_dims = [5,4,3]
parameters = initialize_parameters_deep(layers_dims)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

結果:

W1 = [[ 0.79989897  0.19521314  0.04315498 -0.83337927 -0.12405178]
 [-0.15865304 -0.03700312 -0.28040323 -0.01959608 -0.21341839]
 [-0.58757818  0.39561516  0.39413741  0.76454432  0.02237573]
 [-0.18097724 -0.24389238 -0.69160568  0.43932807 -0.49241241]]
b1 = [[0.]
 [0.]
 [0.]
 [0.]]
W2 = [[-0.59252326 -0.10282495  0.74307418  0.11835813]
 [-0.51189257 -0.3564966   0.31262248 -0.08025668]
 [-0.38441818 -0.11501536  0.37252813  0.98805539]]
b2 = [[0.]
 [0.]
 [0.]]

自此,我們已經分別構建了兩層和多層神經網絡的初始化參數的函數,現在開始構建前向傳播函數。

前向傳播函數

前向傳播有以下三個步驟:

  • linear
  • linear–>avtivation,其中激活函數使用Relu或sigmoid。
  • [linear–>Relu]x(L-1)–>linear–>sigmoid(整個模型)。

其中,
Z[L]=W[L]A[L1]+b[L]Z^{[L]}=W^{[L]}A^{[L-1]}+b^{[L]}
A[L]=g[L](Z[L])=g[L](W[L]A[L1]+b[L])A^{[L]}=g^{[L]}(Z^{[L]})=g^{[L]}(W^{[L]}A^{[L-1]}+b^{[L]})

線性部分linear

def linear_forward(A,W,b):
    """
    實現前向傳播的線性部分。

    參數:
        A - 來自上一層(或輸入數據)的激活,維度爲(上一層的節點數量,示例的數量)
        W - 權重矩陣,numpy數組,維度爲(當前圖層的節點數量,前一圖層的節點數量)
        b - 偏向量,numpy向量,維度爲(當前圖層節點數量,1)

    返回:
         Z - 激活功能的輸入,也稱爲預激活參數
         cache - 一個包含“A”,“W”和“b”的字典,存儲這些變量以有效地計算後向傳遞
    """
    Z = np.dot(W,A) + b
    assert(Z.shape == (W.shape[0],A.shape[1]))
    cache = (A,W,b)
     
    return Z,cache

測試

print("==============測試linear_forward==============")
A,W,b = testCases.linear_forward_test_case()
Z,linear_cache = linear_forward(A,W,b)
print("Z = " + str(Z))

結果:

Z = [[ 3.26295337 -1.23429987]]

線性激活部分linear–>avtivation

def linear_activation_forward(A_prev,W,b,activation):
    """
    實現LINEAR-> ACTIVATION 這一層的前向傳播

    參數:
        A_prev - 來自上一層(或輸入層)的激活,維度爲(上一層的節點數量,示例數)
        W - 權重矩陣,numpy數組,維度爲(當前層的節點數量,前一層的大小)
        b - 偏向量,numpy陣列,維度爲(當前層的節點數量,1)
        activation - 選擇在此層中使用的激活函數名,字符串類型,【"sigmoid" | "relu"】

    返回:
        A - 激活函數的輸出,也稱爲激活後的值
        cache - 一個包含“linear_cache”和“activation_cache”的字典,我們需要存儲它以有效地計算後向傳遞
    """
    
    if activation == "sigmoid":
        Z, linear_cache = linear_forward(A_prev, W, b)
        A, activation_cache = sigmoid(Z)
    elif activation == "relu":
        Z, linear_cache = linear_forward(A_prev, W, b)
        A, activation_cache = relu(Z)
    
    assert(A.shape == (W.shape[0],A_prev.shape[1]))
    cache = (linear_cache,activation_cache)
    
    return A,cache

測試:

A_prev, W,b = testCases.linear_activation_forward_test_case()

A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "sigmoid")
print("sigmoid,A = " + str(A))

A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = "relu")
print("ReLU,A = " + str(A))

結果:

sigmoid,A = [[0.96890023 0.11013289]]
ReLU,A = [[3.43896131 0.        ]]

多層模型的前向傳播計算模型代碼如下:

def L_model_forward(X,parameters):
    """
    實現[LINEAR-> RELU] *(L-1) - > LINEAR-> SIGMOID計算前向傳播,也就是多層網絡的前向傳播,爲後面每一層都執行LINEAR和ACTIVATION
    
    參數:
        X - 數據,numpy數組,維度爲(輸入節點數量,示例數)
        parameters - initialize_parameters_deep()的輸出
    
    返回:
        AL - 最後的激活值
        caches - 包含以下內容的緩存列表:
                 linear_relu_forward()的每個cache(有L-1個,索引爲從0到L-2)
                 linear_sigmoid_forward()的cache(只有一個,索引爲L-1)
    """
    caches = []
    A = X
    L = len(parameters) // 2
    for l in range(1,L):
        A_prev = A 
        A, cache = linear_activation_forward(A_prev, parameters['W' + str(l)], parameters['b' + str(l)], "relu")
        caches.append(cache)
    
    AL, cache = linear_activation_forward(A, parameters['W' + str(L)], parameters['b' + str(L)], "sigmoid")
    caches.append(cache)
    
    assert(AL.shape == (1,X.shape[1]))
    
    return AL,caches

測試:

X,parameters = testCases.L_model_forward_test_case()
AL,caches = L_model_forward(X,parameters)
print("AL = " + str(AL))
print("caches 的長度爲 = " + str(len(caches)))

結果:

AL = [[0.17007265 0.2524272 ]]
caches 的長度爲 = 2

計算成本

def compute_cost(AL,Y):
    """
    實施等式(4)定義的成本函數。

    參數:
        AL - 與標籤預測相對應的概率向量,維度爲(1,示例數量)
        Y - 標籤向量(例如:如果不是貓,則爲0,如果是貓則爲1),維度爲(1,數量)

    返回:
        cost - 交叉熵成本
    """
    m = Y.shape[1]
    cost = -np.sum(np.multiply(np.log(AL),Y) + np.multiply(np.log(1 - AL), 1 - Y)) / m
        
    cost = np.squeeze(cost)
    assert(cost.shape == ())

    return cost

測試:

Y,AL = testCases.compute_cost_test_case()
print("cost = " + str(compute_cost(AL, Y)))

結果:

cost = 0.414931599615397

反向傳播

反向傳播用於計算相對於參數的損失函數的梯度,來看看向前、向後傳播的流程圖:
在這裏插入圖片描述
對於線性部分,反向傳播的公式如下:
在這裏插入圖片描述
與前向傳播類似,使用三個步驟來構建反向傳播:

  • linear後向計算
  • linear–>activation後向計算,其中activation計算Relu或者sigmoid的結果。
  • [linear–>Relu]x(L-1)–>linear–>sigmoid後向計算(整個模型)

線性部分linear backward

def linear_backward(dZ,cache):
    """
    爲單層實現反向傳播的線性部分(第L層)

    參數:
         dZ - 相對於(當前第l層的)線性輸出的成本梯度
         cache - 來自當前層前向傳播的值的元組(A_prev,W,b)

    返回:
         dA_prev - 相對於激活(前一層l-1)的成本梯度,與A_prev維度相同
         dW - 相對於W(當前層l)的成本梯度,與W的維度相同
         db - 相對於b(當前層l)的成本梯度,與b維度相同
    """
    A_prev, W, b = cache
    m = A_prev.shape[1]
    dW = np.dot(dZ, A_prev.T) / m
    db = np.sum(dZ, axis=1, keepdims=True) / m
    dA_prev = np.dot(W.T, dZ)
    
    assert (dA_prev.shape == A_prev.shape)
    assert (dW.shape == W.shape)
    assert (db.shape == b.shape)
    
    return dA_prev, dW, db

測試:

dZ, linear_cache = testCases.linear_backward_test_case()

dA_prev, dW, db = linear_backward(dZ, linear_cache)
print ("dA_prev = "+ str(dA_prev))
print ("dW = " + str(dW))
print ("db = " + str(db))

結果:

dA_prev = [[ 0.51822968 -0.19517421]
 [-0.40506361  0.15255393]
 [ 2.37496825 -0.89445391]]
dW = [[-0.10076895  1.40685096  1.64992505]]
db = [[0.50629448]]

線性激活部分linear–>activation backward

def linear_activation_backward(dA,cache,activation="relu"):
    """
    實現LINEAR-> ACTIVATION層的後向傳播。
    
    參數:
         dA - 當前層l的激活後的梯度值
         cache - 我們存儲的用於有效計算反向傳播的值的元組(值爲linear_cache,activation_cache)
         activation - 要在此層中使用的激活函數名,字符串類型,【"sigmoid" | "relu"】
    返回:
         dA_prev - 相對於激活(前一層l-1)的成本梯度值,與A_prev維度相同
         dW - 相對於W(當前層l)的成本梯度值,與W的維度相同
         db - 相對於b(當前層l)的成本梯度值,與b的維度相同
    """
    linear_cache, activation_cache = cache
    if activation == "relu":
        dZ = relu_backward(dA, activation_cache)
        dA_prev, dW, db = linear_backward(dZ, linear_cache)
    elif activation == "sigmoid":
        dZ = sigmoid_backward(dA, activation_cache)
        dA_prev, dW, db = linear_backward(dZ, linear_cache)
    
    return dA_prev,dW,db

測試:

AL, linear_activation_cache = testCases.linear_activation_backward_test_case()
 
dA_prev, dW, db = linear_activation_backward(AL, linear_activation_cache, activation = "sigmoid")
print ("sigmoid:")
print ("dA_prev = "+ str(dA_prev))
print ("dW = " + str(dW))
print ("db = " + str(db) + "\n")
 
dA_prev, dW, db = linear_activation_backward(AL, linear_activation_cache, activation = "relu")
print ("relu:")
print ("dA_prev = "+ str(dA_prev))
print ("dW = " + str(dW))
print ("db = " + str(db))

結果:

sigmoid:
dA_prev = [[ 0.11017994  0.01105339]
 [ 0.09466817  0.00949723]
 [-0.05743092 -0.00576154]]
dW = [[ 0.10266786  0.09778551 -0.01968084]]
db = [[-0.05729622]]

relu:
dA_prev = [[ 0.44090989 -0.        ]
 [ 0.37883606 -0.        ]
 [-0.2298228   0.        ]]
dW = [[ 0.44513824  0.37371418 -0.10478989]]
db = [[-0.20837892]]

對於L層神經網絡,其反向傳播函數如下:
在這裏插入圖片描述

def L_model_backward(AL,Y,caches):
    """
    對[LINEAR-> RELU] *(L-1) - > LINEAR - > SIGMOID組執行反向傳播,就是多層網絡的向後傳播
    
    參數:
     AL - 概率向量,正向傳播的輸出(L_model_forward())
     Y - 標籤向量(例如:如果不是貓,則爲0,如果是貓則爲1),維度爲(1,數量)
     caches - 包含以下內容的cache列表:
                 linear_activation_forward("relu")的cache,不包含輸出層
                 linear_activation_forward("sigmoid")的cache
    
    返回:
     grads - 具有梯度值的字典
              grads [“dA”+ str(l)] = ...
              grads [“dW”+ str(l)] = ...
              grads [“db”+ str(l)] = ...
    """
    grads = {}
    L = len(caches)
    m = AL.shape[1]
    Y = Y.reshape(AL.shape)
    dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))
    
    current_cache = caches[L-1]
    grads["dA" + str(L)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, "sigmoid")
    
    for l in reversed(range(L-1)):
        current_cache = caches[l]
        dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 2)], current_cache, "relu")
        grads["dA" + str(l + 1)] = dA_prev_temp
        grads["dW" + str(l + 1)] = dW_temp
        grads["db" + str(l + 1)] = db_temp
    
    return grads

測試:

AL, Y_assess, caches = testCases.L_model_backward_test_case()
grads = L_model_backward(AL, Y_assess, caches)
print ("dW1 = "+ str(grads["dW1"]))
print ("db1 = "+ str(grads["db1"]))
print ("dA1 = "+ str(grads["dA1"]))

結果:

dW1 = [[0.41010002 0.07807203 0.13798444 0.10502167]
 [0.         0.         0.         0.        ]
 [0.05283652 0.01005865 0.01777766 0.0135308 ]]
db1 = [[-0.22007063]
 [ 0.        ]
 [-0.02835349]]
dA1 = [[ 0.          0.52257901]
 [ 0.         -0.3269206 ]
 [ 0.         -0.32070404]
 [ 0.         -0.74079187]]

更新參數

更新參數公式如下:
W[L]=W[L]αdW[L]W^{[L]}=W^{[L]}-\alpha dW^{[L]}
b[L]=b[L]αdb[L]b^{[L]}=b^{[L]}-\alpha db^{[L]}

def update_parameters(parameters, grads, learning_rate):
    """
    使用梯度下降更新參數
    
    參數:
     parameters - 包含你的參數的字典
     grads - 包含梯度值的字典,是L_model_backward的輸出
    
    返回:
     parameters - 包含更新參數的字典
                   參數[“W”+ str(l)] = ...
                   參數[“b”+ str(l)] = ...
    """
    L = len(parameters) // 2 #整除
    for l in range(1,L):
        parameters["W" + str(l)] = parameters["W" + str(l)] - learning_rate * grads["dW" + str(l)]
        parameters["b" + str(l)] = parameters["b" + str(l)] - learning_rate * grads["db" + str(l)]
        
    return parameters

測試:

parameters, grads = testCases.update_parameters_test_case()
parameters = update_parameters(parameters, grads, 0.1)
 
print ("W1 = "+ str(parameters["W1"]))
print ("b1 = "+ str(parameters["b1"]))
print ("W2 = "+ str(parameters["W2"]))
print ("b2 = "+ str(parameters["b2"]))

結果:

W1 = [[-0.59562069 -0.09991781 -2.14584584  1.82662008]
 [-1.76569676 -0.80627147  0.51115557 -1.18258802]
 [-1.0535704  -0.86128581  0.68284052  2.20374577]]
b1 = [[-0.04659241]
 [-1.28888275]
 [ 0.53405496]]
W2 = [[-0.55569196  0.0354055   1.32964895]]
b2 = [[-0.84610769]]

整合

至此,已經實現該神經網絡中所有需要的函數,接下來,將這些方法組合在一起,構成一個神經網絡類。

兩層神經網絡模型

def two_layer_model(X,Y,layers_dims,learning_rate=0.0075,num_iterations=3000,print_cost=False,isPlot=True):
    """
    實現一個兩層的神經網絡,【LINEAR->RELU】 -> 【LINEAR->SIGMOID】
    參數:
        X - 輸入的數據,維度爲(n_x,例子數)
        Y - 標籤,向量,0爲非貓,1爲貓,維度爲(1,數量)
        layers_dims - 層數的向量,維度爲(n_y,n_h,n_y)
        learning_rate - 學習率
        num_iterations - 迭代的次數
        print_cost - 是否打印成本值,每100次打印一次
        isPlot - 是否繪製出誤差值的圖譜
    返回:
        parameters - 一個包含W1,b1,W2,b2的字典變量
    """
    np.random.seed(1)
    grads = {}
    costs = []
    (n_x,n_h,n_y) = layers_dims
    
    """
    初始化參數
    """
    parameters = initialize_parameters(n_x, n_h, n_y)
    
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    
    """
    開始進行迭代
    """
    for i in range(0,num_iterations):
        #前向傳播
        A1, cache1 = linear_activation_forward(X, W1, b1, "relu")
        A2, cache2 = linear_activation_forward(A1, W2, b2, "sigmoid")
        
        #計算成本
        cost = compute_cost(A2,Y)
        
        #後向傳播
        ##初始化後向傳播
        dA2 = - (np.divide(Y, A2) - np.divide(1 - Y, 1 - A2))
        
        ##向後傳播,輸入:“dA2,cache2,cache1”。 輸出:“dA1,dW2,db2;還有dA0(未使用),dW1,db1”。
        dA1, dW2, db2 = linear_activation_backward(dA2, cache2, "sigmoid")
        dA0, dW1, db1 = linear_activation_backward(dA1, cache1, "relu")
        
        ##向後傳播完成後的數據保存到grads
        grads["dW1"] = dW1
        grads["db1"] = db1
        grads["dW2"] = dW2
        grads["db2"] = db2
        
        #更新參數
        parameters = update_parameters(parameters,grads,learning_rate)
        W1 = parameters["W1"]
        b1 = parameters["b1"]
        W2 = parameters["W2"]
        b2 = parameters["b2"]
        
        #打印成本值,如果print_cost=False則忽略
        if i % 100 == 0:
            #記錄成本
            costs.append(cost)
            #是否打印成本值
            if print_cost:
                print("第", i ,"次迭代,成本值爲:" ,np.squeeze(cost))
    #迭代完成,根據條件繪製圖
    if isPlot:
        plt.plot(np.squeeze(costs))
        plt.ylabel('cost')
        plt.xlabel('iterations (per tens)')
        plt.title("Learning rate =" + str(learning_rate))
        plt.show()
    
    #返回parameters
    return parameters

測試:

train_set_x_orig , train_set_y , test_set_x_orig , test_set_y , classes = lr_utils.load_dataset()

train_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T 
test_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T

train_x = train_x_flatten / 255
train_y = train_set_y
test_x = test_x_flatten / 255
test_y = test_set_y

n_x = 12288
n_h = 7
n_y = 1
layers_dims = (n_x,n_h,n_y)

parameters = two_layer_model(train_x, train_set_y, layers_dims = (n_x, n_h, n_y), num_iterations = 1000, print_cost=True,isPlot=True)

結果:

0 次迭代,成本值爲: 0.6930497356599891100 次迭代,成本值爲: 0.6464320953428849200 次迭代,成本值爲: 0.6325140647912678300 次迭代,成本值爲: 0.6015024920354665400 次迭代,成本值爲: 0.5601966311605748500 次迭代,成本值爲: 0.515830477276473600 次迭代,成本值爲: 0.47549013139433266700 次迭代,成本值爲: 0.4339163151225749800 次迭代,成本值爲: 0.4007977536203886900 次迭代,成本值爲: 0.35807050113237976

在這裏插入圖片描述
預測部分:

def predict(X, y, parameters):
    """
    該函數用於預測L層神經網絡的結果,當然也包含兩層
    
    參數:
     X - 測試集
     y - 標籤
     parameters - 訓練模型的參數
    
    返回:
     p - 給定數據集X的預測
    """
    
    m = X.shape[1]
    n = len(parameters) // 2 # 神經網絡的層數
    p = np.zeros((1,m))
    
    #根據參數前向傳播
    probas, caches = L_model_forward(X, parameters)
    
    for i in range(0, probas.shape[1]):
        if probas[0,i] > 0.5:
            p[0,i] = 1
        else:
            p[0,i] = 0
    
    print("準確度爲: "  + str(float(np.sum((p == y))/m)))
        
    return p

測試:

predictions_train = predict(train_x, train_y, parameters) #訓練集
predictions_test = predict(test_x, test_y, parameters) #測試集

結果:

準確度爲: 1.0
準確度爲: 0.72

L層神經網絡

def L_layer_model(X, Y, layers_dims, learning_rate=0.0075, num_iterations=3000, print_cost=False,isPlot=True):
    """
    實現一個L層神經網絡:[LINEAR-> RELU] *(L-1) - > LINEAR-> SIGMOID。
    
    參數:
	    X - 輸入的數據,維度爲(n_x,例子數)
        Y - 標籤,向量,0爲非貓,1爲貓,維度爲(1,數量)
        layers_dims - 層數的向量,維度爲(n_y,n_h,···,n_h,n_y)
        learning_rate - 學習率
        num_iterations - 迭代的次數
        print_cost - 是否打印成本值,每100次打印一次
        isPlot - 是否繪製出誤差值的圖譜
    
    返回:
     parameters - 模型學習的參數。 然後他們可以用來預測。
    """
    np.random.seed(1)
    costs = []
    
    parameters = initialize_parameters_deep(layers_dims)
    
    for i in range(0,num_iterations):
        AL , caches = L_model_forward(X,parameters)
        
        cost = compute_cost(AL,Y)
        
        grads = L_model_backward(AL,Y,caches)
        
        parameters = update_parameters(parameters,grads,learning_rate)
        
        #打印成本值,如果print_cost=False則忽略
        if i % 100 == 0:
            #記錄成本
            costs.append(cost)
            #是否打印成本值
            if print_cost:
                print("第", i ,"次迭代,成本值爲:" ,np.squeeze(cost))
    #迭代完成,根據條件繪製圖
    if isPlot:
        plt.plot(np.squeeze(costs))
        plt.ylabel('cost')
        plt.xlabel('iterations (per tens)')
        plt.title("Learning rate =" + str(learning_rate))
        plt.show()
    return parameters

測試:

layers_dims = [12288, 20, 7, 5, 1] #  5-layer model
parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 1000, print_cost = True,isPlot=True)

結果:

0 次迭代,成本值爲: 0.715731513413713100 次迭代,成本值爲: 0.6747377593469114200 次迭代,成本值爲: 0.6603365433622127300 次迭代,成本值爲: 0.6462887802148751400 次迭代,成本值爲: 0.6298131216927773500 次迭代,成本值爲: 0.606005622926534600 次迭代,成本值爲: 0.5690041263975134700 次迭代,成本值爲: 0.519796535043806800 次迭代,成本值爲: 0.46415716786282285900 次迭代,成本值爲: 0.40842030048298916

在這裏插入圖片描述
預測部分測試:

train_set_x_orig , train_set_y , test_set_x_orig , test_set_y , classes = lr_utils.load_dataset()

train_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T 
test_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T

train_x = train_x_flatten / 255
train_y = train_set_y
test_x = test_x_flatten / 255
test_y = test_set_y

pred_train = predict(train_x, train_y, parameters) #訓練集
pred_test = predict(test_x, test_y, parameters) #測試集

結果:

準確度爲: 0.9952153110047847
準確度爲: 0.78

分析

可以看一看有哪些東西在L層模型找哪個被錯誤地標記了,導致準確率沒有提高。

def print_mislabeled_images(classes,X,y,p):
    a = p+y
    mislabeled_indices = np.asarray(np.where(a==1))
    plt.rcParams['figure.figsize'] = (40.0,40.0)
    num_images = len(mislabeled_indices[0])
    for i in range(num_images):
        index = mislabeled_indices[1][i]
        
        plt.subplot(2,num_images,i+1)
        plt.imshow(X[:,index].reshape(64,64,3),interpolation='nearest')
        plt.axis('off')
        plt.title("Prediction:"+classes[int(p[0,index])].decode("utf-8")+"\n Class:"+classes[y[0,index]].decode("utf-8"))
    
print_mislabeled_images(classes,test_x,test_y,pred_test)

結果:
在這裏插入圖片描述
分析一下就得知原因:模型往往表現欠佳的幾種類型圖形包括:

  • 貓身體在一個不同的位置
  • 貓出現在相似顏色的背景下
  • 不同的貓的顏色和品種
  • 相機角度
  • 圖片的亮度
  • 比例變化(貓的圖像非常大或很小)

測試本地電腦圖片:

from skimage import transform
my_image = "tim.jpg"
my_label_y = [1]

fname = "D:/20200112zhaohuan/"+my_image
image = plt.imread(fname,'rb')
plt.imshow(image)
my_image = transform.resize(image,(64,64,3)).reshape(64*64*3,1)
my_predicted_image = predict(my_image,my_label_y,parameters)
print("y = "+str(np.squeeze(my_predicted_image))+",your L-layer model predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8")+"\"picture.")

結果:

(455, 640, 3)
(12288, 1)
準確度爲: 0.0
y = 0.0,your L-layer model predicts a "non-cat"picture.

在這裏插入圖片描述
看來並不是所有的圖片都能識別呢!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章