2. 一步步搭建多层神经网络及应用

本文主要参考了 严宽 大神的学习笔记,并在其基础上补充了一点内容,点此查看原文
本文所使用的资料已上传到百度网盘【点击下载】,提取码:xx1w,请在开始之前下载好所需资料。


import numpy as np
import h5py
import matplotlib.pyplot as plt
from PIL import Image
import testCases #参见资料包
from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward #参见资料包
import lr_utils #参见资料包

np.random.seed(1)   # 指定随机种子

一、准备工作

1. 初始化参数

两层神经网络的初始化函数:

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  
# 测试 initialize_parameters()
print("==============测试initialize_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"]))

多层神经网络的初始化函数:

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)
    
    # 对于层数为 L-1 的神经网络(不包括输入层),有 L-1 个 W 和 b 
    for l in range(1, L):    # l 可取 1—— L-1
        # 除以 np.sqrt()是为了避免梯度消失和梯度爆炸问题
        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

补充梯度消失和梯度爆炸及解决方法

# 测试 initialize_parameters_deep
print("==============================测试 initialize_parameters_deep ========================")
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"]))
2. 前向传播

前向传播有以下三个步骤:
  ① Linear Z [ l ] = W [ l ] A [ l − 1 ] + b [ l ] (1) Z^{[l]} = W^{[l]}A^{[l-1]} + b^{[l]} \tag{1} Z[l]=W[l]A[l1]+b[l](1)
  ② Linear -> Activation,其中 ψ \psi ψ 会使用 ReLU 或 Sigmoid A [ l ] = ψ ( Z [ l ] ) (2) A^{[l]}=\psi(Z^{[l]}) \tag{2} A[l]=ψ(Z[l])(2)
  ③ 【Linear -> ReLU】× (L-1) -> Linear -> Sigmoid(多层网络) ψ = { R e L U , l < L S i g m o i d , l = L (3) \psi=\left\{ \begin{matrix} ReLU & , & l < L \\ Sigmoid & , & l = L \end{matrix} \right. \tag{3} ψ={ReLUSigmoid,,l<Ll=L(3)
2.1 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
#测试linear_forward
print("==============测试linear_forward==============")
A,W,b = testCase.linear_forward_test_case()
Z,linear_cache = linear_forward(A,W,b)
print("Z = " + str(Z))      # Z = [[ 3.26295337 -1.23429987]]

2.2 Linear -> Activation
为了更方便,我们将两个功能(线性和激活)分组为一个功能函数(Linear - > Activation)。其中激活函数这里采用 ReLU 和 Sigmoid 函数。 S i g m o i d : σ ( Z ) = 1 1 + e − Z (4) Sigmoid:\sigma(Z)=\frac{1}{1+e^{-Z}} \tag{4} Sigmoidσ(Z)=1+eZ1(4) R e L U : R e L U ( Z ) = m a x ( 0 , Z ) (5) ReLU:ReLU(Z)=max(0, Z ) \tag{5} ReLUReLU(Z)=max(0,Z)(5)

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”的字典,我们需要存储它以有效地计算后向传递
    """
    Z, linear_cache = linear_forward(A_prev, W, b)
    
    if activation == "sigmoid":
        A, activation_cache = sigmoid(Z)
    elif activation == "relu":
        A, activation_cache = relu(Z)
        
    assert(A.shape == (W.shape[0], A_prev.shape[1]))
    cache = (linear_cache, activation_cache)
        
    return A, cache
#测试linear_activation_forward
print("==============测试linear_activation_forward==============")
A_prev, W,b = testCase.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))

2.3 【Linear -> ReLU】× (L-1) -> Linear -> Sigmoid(多层网络)

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
    
    # 前 L-1 次 Linear -> Activation:激活函数用 ReLU
    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)
    
    # 第 L 次激活,激活函数用 Sigmoid
    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
#测试L_model_forward
print("==============测试L_model_forward==============")
X,parameters = testCase.L_model_forward_test_case()
AL,caches = L_model_forward(X,parameters)
print("AL = " + str(AL))      # AL = [[0.17007265 0.2524272 ]]               
print("caches 的长度为 = " + str(len(caches)))  # caches 的长度为 = 2
3. 计算成本

计算成本的公式如下: J = − 1 m ∑ i = 1 m ( y ( i ) log ⁡ ( a [ L ] ( i ) ) + ( 1 − y ( i ) ) log ⁡ ( 1 − a [ L ] ( i ) ) ) (6) J=-\frac{1}{m}\sum_{i=1}^m{\big(y^{(i)}\log(a^{[L](i)}) + (1 - y^{(i)})\log(1 - a^{[L](i)})\big)} \tag{6} J=m1i=1m(y(i)log(a[L](i))+(1y(i))log(1a[L](i)))(6)

def compute_cost(AL, Y):
    """
    实施上述等式定义的成本函数。

    参数:
        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
#测试compute_cost
print("==============测试compute_cost==============")
Y,AL = testCase.compute_cost_test_case()
print("cost = " + str(compute_cost(AL, Y)))    # cost = 0.414931599615397
4. 反向传播

反向传播用于计算相对于参数的损失函数的梯度,我们来看看前向传播和反向传播的流程图:
在这里插入图片描述
我们需要使用 d Z [ l ] dZ^{[l]} dZ[l] 来计算三个输出( d W [ l ] , d b [ l ] , d A [ l ] dW^{[l]},db^{[l]},dA^{[l]} dW[l],db[l],dA[l]),下面三个公式是我们要用到的: d W [ l ] = ∂ L ∂ W [ l ] = 1 m d Z [ l ] A [ l − 1 ] T (7) dW^{[l]}=\frac{\partial L}{\partial W^{[l]}}=\frac{1}{m}dZ^{[l]}A^{[l-1]T} \tag{7} dW[l]=W[l]L=m1dZ[l]A[l1]T(7) d b [ l ] = ∂ L ∂ b [ l ] = 1 m ∑ i = 1 m d Z [ l ] ( i ) (8) db^{[l]}=\frac{\partial L}{\partial b^{[l]}}=\frac{1}{m}\sum_{i=1}^mdZ^{[l](i)} \tag{8} db[l]=b[l]L=m1i=1mdZ[l](i)(8) d A [ l − 1 ] = ∂ L ∂ A [ l − 1 ] = W [ l ] T d Z [ l ] (9) dA^{[l-1]}=\frac{\partial L}{\partial A^{[l-1]}}=W^{[l]T}dZ^{[l]} \tag{9} dA[l1]=A[l1]L=W[l]TdZ[l](9)
和前向传播类似,反向传播有以下三个步骤:
  ① Linear 后向计算
  ② Linear -> Activation 后向计算,其中 ψ \psi ψ 会使用 ReLU 或 Sigmoid
  ③ 【Linear -> ReLU】× (L-1) -> Linear -> Sigmoid 后向计算(多层网络)
4.1 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
#测试linear_backward
print("==============测试linear_backward==============")
dZ, linear_cache = testCase.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))

4.2 Linear -> Activation backward
为了帮你实现 linear_activation_backward,我们提供了两个反向函数:
(1)sigmoid_backward:实现了 sigmoid() 函数的反向传播,调用方法为:

dZ = sigmoid_backward(dA, activation_cache)

(2)relu_backward:实现了 relu() 函数的反向传播,调用方法为:

dZ = relu_backward(dA, activation_cache)

如果 g ( ⋅ ) g(·) g() 是激活函数,那么 sigmoid_backwardrelu_backward 这样计算: d Z [ l ] = d A [ l ] ∗ g ′ ( Z [ l ] ) (10) dZ^{[l]}=dA^{[l]}*g'(Z^{[l]}) \tag{10} dZ[l]=dA[l]g(Z[l])(10)

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
#测试linear_activation_backward
print("==============测试linear_activation_backward==============")
AL, linear_activation_cache = testCase.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))

4.3 【Linear -> ReLU】× (L-1) -> Linear -> Sigmoid 后向计算(多层网络)
在这里插入图片描述
在之前的前向计算中,我们存储了一些包含 ( X , W , b , z X, W, b, z X,W,b,z) 的 cache,在反向传播中,我们将会使用它们来计算梯度值,所以,在 L 层模型中,我们需要从 L 层遍历所有的隐藏层,在每一步中,我们需要使用那一层的 cache 值来进行反向传播。
上面我们提到了 A [ L ] A^{[L]} A[L],它属于输出层, A [ L ] = σ ( Z [ L ] ) A^{[L]}=\sigma(Z^{[L]}) A[L]=σ(Z[L]),所以我们需要计算 d A L dAL dAL,我们可以使用下面的代码来计算它:

dAL = -(np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))

计算完了之后,我们可以使用此激活后的梯度 d A L dAL dAL 继续向后计算。一下就是我们构建多层网络的反向传播函数:

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
#测试L_model_backward
print("==============测试L_model_backward==============")
AL, Y_assess, caches = testCase.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"]))
5. 更新参数

我们采用梯度下降法来更新参数,其公式如下( α \alpha α 为学习率): W [ l ] = W [ l ] − α d W [ l ] (11) W^{[l]}=W^{[l]}-\alpha dW^{[l]} \tag{11} W[l]=W[l]αdW[l](11) b [ l ] = b [ l ] − α d b [ l ] (12) b^{[l]}=b^{[l]}-\alpha db^{[l]} \tag{12} b[l]=b[l]αdb[l](12)

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(L):
        parameters["W" + str(l + 1)] = parameters["W" + str(l + 1)] - learning_rate * grads["dW" + str(l + 1)]
        parameters["b" + str(l + 1)] = parameters["b" + str(l + 1)] - learning_rate * grads["db" + str(l + 1)]
        
    return parameters
#测试update_parameters
print("==============测试update_parameters==============")
parameters, grads = testCase.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"]))

二、搭建网络

1. 搭建两层网络模型

接下来我们要搭建的两层神经网络模型图如下:
在这里插入图片描述

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

我们现在开始加载数据集,图像数据集的处理可以参照:【中文】【吴恩达课后编程作业】Course 1 - 神经网络和深度学习 - 第二周作业,就连数据集也是一样的。

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 = 2500, print_cost=True,isPlot=True)

在这里插入图片描述
编写预测函数

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)   # 准确度为:1.0
predictions_test = predict(test_x, test_y, parameters)   # 准确度为:0.72
2. 搭建多层神经网络

多层神经网络的结构图如下:
在这里插入图片描述

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 - 一个包含W1,b1,W2,b2的字典变量
    """
    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()
        
    # 返回 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

训练一个 5 层神经网络模型

layers_dims = [12288, 20, 7, 5, 1] 
parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations=2500, print_cost=True, isPlot=True)

在这里插入图片描述
对其进行预测,分析其准确度:

pred_train = predict(train_x, train_y, parameters)   # 准确度为:0.9952153110047847
pred_test = predict(test_x, test_y, parameters)      # 准确度为:0.78
3. 分析上述模型

我们可以看一看有哪些东西在 L 层模型中被错误地标记了,导致准确率没有提高。

def print_mislabeled_images(classes, X, y, p):
    """
    绘制预测和实际不同的图像。
        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)

在这里插入图片描述
经过分析可以得知,模型表现欠佳的几种类型的图像包括:①猫身体在一个不同的位置,②猫出现在相似颜色的背景下,③不同的猫的颜色和品种,④相机角度,⑥图片的亮度,⑦比例变化(猫的图像很大或很小)

4. 测试

我们使用上述模型来分析自己的图片,然后识别它:
在这里插入图片描述

my_image = "cat.jpg"   # 这里最好将文件保存为 jpg 格式
my_label_y = [1]
num_px = 64

fname = "../data/" + my_image  # 文件路径
image = np.array(imread(fname))    # 以数组形式读入图片
im = Image.fromarray(np.uint8(image))   # 将数组转换为图片
new_image =  np.array(im.resize((num_px, num_px)))

my_image = new_image.reshape((num_px * num_px * 3, 1))
my_predicted_image = predict(my_image, my_label_y, parameters)

plt.imshow(image)
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.")

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值