【神经网络学习笔记】构建多层神经网络

构建多层神经网络

一、步骤

  1. 初始化网络的参数
  2. 正向传播
    • 计算一层中线性求和的部分
    • 计算激活函数的部分(隐藏层用Relu函数,最后的输出曾用Sigmoid函数)
  3. 计算代价(误差)
  4. 反向传播
    • 线性部分的反向传播
    • 激活函数部分的反向传播
  5. 更新参数

二、前期准备

2.1准备包

其中testCases,dnn_utils,lr_utils是额外的包,可以去此文下载:
https://blog.csdn.net/u013733326/article/details/79767169
同时本人也是参考这篇文章进行学习,如有错漏望指正,谢谢~!

import numpy as np
import h5py
import matplotlib.pyplot as plt
import testCases
from dnn_utils import sigmoid,sigmoid_backward,relu,relu_backward
import lr_utils
from prediction import predict
# 指定一个随机种子
np.random.seed(1)

2.2初始化参数

首先我们用两层的神经网络来开头,他的结构是线性->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

测试一下

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"]))
==============测试initialize_parameters==============
W1 = [[ 0.01624345 -0.00611756 -0.00528172]
 [-0.01072969  0.00865408 -0.02301539]]
b1 = [[0.]
 [0.]]
W2 = [[ 0.01744812 -0.00761207]]
b2 = [[0.]]

两层的测试完成,那么当神经网络不止两层,那么就要稍微复杂一点

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

# 测试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"]))
==============测试initialize_parameters_deep==============
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.]]

2.3正向传播

参数初始化完成,下一步就该正向传播了,其中用到的公式为:
公式

2.3.1线性计算部分

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))
==============测试linear_forward==============
Z = [[ 3.26295337 -1.23429987]]

2.3.2线性激活部分

这里用到两个激活函数分别为Relu和Sigmoid。

def linear_activation_forward(A_prev,W,b,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

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

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

当然以上是两层网络下的正向传播,当我们要进行多层传播的时候如下:

def L_model_forward(X,parameters):
    """
    参数:
        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')
        # cache是元组,包含linear_cache和activation_cache,而其中linear_cache又是一个元组,包含当前层的A,W,b
        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

测试一下:

print("==============测试L_model_forward==============")
X,parameters = testCases.L_model_forward_test_case()
AL,caches = L_model_forward(X,parameters)
print("AL = " + str(AL))
print("caches 的长度为 = " + str(len(caches)))
==============测试L_model_forward==============
AL = [[0.17007265 0.2524272 ]]
caches 的长度为 = 2

2.4计算成本(误差)

当正向传播结果,就可以计算成本了,就是输出值和预测值相差多少,后面根据这个相差值来调整前面的参数,公式如下:
在这里插入图片描述

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 = testCases.compute_cost_test_case()
print("cost = " + str(compute_cost(AL, Y)))
==============测试compute_cost==============
cost = 0.414931599615397

2.5反向传播

在这里插入图片描述
反向传播用于计算相对于参数的损失函数的梯度,通过链式求导法则我们可以获得一些公式:
在这里插入图片描述
此时我们之前在中间部分缓存的输出就派上用场了

2.5.1线性部分反向传播

def linear_backward(dZ,cache):
    """
    参数:
         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

测试一下

print("==============测试linear_backward==============")
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))

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

2.5.2线性激活部分

def linear_activation_backward(dA,cache,activation='relu'):
    """
    参数:
         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

测试一下

print("==============测试linear_activation_backward==============")
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))
==============测试linear_activation_backward==============
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层开始反向传播的,因此我们需要计算出第L层A的梯度dAL,公式为:

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

我们知道这个公式后,就可以开始构建多层模型的反向传播了。

def L_model_backward(AL,Y,caches):
    """
    参数:
     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

测试一下

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

2.6更新参数

反向传播结束后,有了对于参数的梯度,我们就可以开始更新参数了。

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 = 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"]))
==============测试update_parameters==============
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):
    """
     参数:
        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

    # 1.初始化参数
    parameters = initialize_parameters(n_x,n_h,n_y)

    W1 = parameters['W1']
    b1 = parameters['b1']
    W2 = parameters['W2']
    b2 = parameters['b2']

    # 2.开始进行迭代
    for i in range(0,num_iterations):
        # 2.1 正向传播
        A1,cache1 = linear_activation_forward(X,W1,b1,'relu')
        A2,cache2 = linear_activation_forward(A1,W2,b2,'sigmoid')

        # 2.2 计算成本
        cost = compute_cost(A2,Y)

       # 2.3 反向传播
        # 2.3.1 初始化反向传播
        dA2 = -(np.divide(Y,A2)-np.divide(1-Y,1-A2))

       # 2.3.2 开始向后传播
        dA1,dW2,db2 = linear_activation_backward(dA2,cache2,'sigmoid')
        dA0,dW1,db1 = linear_activation_backward(dA1,cache1,'relu')

        # 2.3.3 将梯度存入grads
        grads['dW1'] = dW1
        grads['db1'] = db1
        grads['dW2'] = dW2
        grads['db2'] = db2

        # 2.3.4 更新参数
        parameters = update_parameters(parameters,grads,learning_rate)
        W1 = parameters['W1']
        b1 = parameters['b1']
        W2 = parameters['W2']
        b2 = parameters['b2']

        # 2.4 打印成本值
        if i % 100 == 0:
            costs.append(cost)
            if print_cost:
                print("第", i ,"次迭代,成本值为:" ,np.squeeze(cost))

        # 2.5 绘图
    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

# 加载数据
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)
predictions_train = predict(train_x, train_y, parameters) #训练集
predictions_test = predict(test_x, test_y, parameters) #测试集

第 0 次迭代,成本值为: 0.6930497356599891
第 100 次迭代,成本值为: 0.6464320953428849
第 200 次迭代,成本值为: 0.6325140647912677
第 300 次迭代,成本值为: 0.6015024920354665
第 400 次迭代,成本值为: 0.5601966311605748
第 500 次迭代,成本值为: 0.515830477276473
第 600 次迭代,成本值为: 0.4754901313943326
第 700 次迭代,成本值为: 0.4339163151225749
第 800 次迭代,成本值为: 0.40079775362038883
第 900 次迭代,成本值为: 0.3580705011323798
第 1000 次迭代,成本值为: 0.3394281538366412
第 1100 次迭代,成本值为: 0.3052753636196264
第 1200 次迭代,成本值为: 0.2749137728213015
第 1300 次迭代,成本值为: 0.2468176821061485
第 1400 次迭代,成本值为: 0.19850735037466102
第 1500 次迭代,成本值为: 0.17448318112556643
第 1600 次迭代,成本值为: 0.17080762978097014
第 1700 次迭代,成本值为: 0.11306524562164712
第 1800 次迭代,成本值为: 0.09629426845937145
第 1900 次迭代,成本值为: 0.08342617959726863
第 2000 次迭代,成本值为: 0.07439078704319078
第 2100 次迭代,成本值为: 0.06630748132267932
第 2200 次迭代,成本值为: 0.05919329501038171
第 2300 次迭代,成本值为: 0.05336140348560556
第 2400 次迭代,成本值为: 0.04855478562877018

在这里插入图片描述

准确度为: 1.0
准确度为: 0.72

可以看到,相比于我们第一次的作业,这里测试集的准确度提高了,现在是72%。
现在试试多层神经网络。

def L_layer_model(X,Y,layers_dims,learning_rate=0.0075,num_iterations=3000,print_cost=False,isPlot=True):
    """
    参数:
	    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)

        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

# 加载数据
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

layers_dims = [12288, 20, 7, 5, 1] #  5-layer model
parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 2500, print_cost = True,isPlot=True)
predictions_train = predict(train_x, train_y, parameters) #训练集
predictions_test = predict(test_x, test_y, parameters) #测试集

第 0 次迭代,成本值为: 0.715731513413713
第 100 次迭代,成本值为: 0.6747377593469114
第 200 次迭代,成本值为: 0.6603365433622128
第 300 次迭代,成本值为: 0.6462887802148751
第 400 次迭代,成本值为: 0.6298131216927773
第 500 次迭代,成本值为: 0.606005622926534
第 600 次迭代,成本值为: 0.5690041263975134
第 700 次迭代,成本值为: 0.5197965350438059
第 800 次迭代,成本值为: 0.46415716786282285
第 900 次迭代,成本值为: 0.40842030048298916
第 1000 次迭代,成本值为: 0.37315499216069026
第 1100 次迭代,成本值为: 0.30572374573047106
第 1200 次迭代,成本值为: 0.26810152847740826
第 1300 次迭代,成本值为: 0.23872474827672663
第 1400 次迭代,成本值为: 0.20632263257914712
第 1500 次迭代,成本值为: 0.17943886927493605
第 1600 次迭代,成本值为: 0.15798735818801682
第 1700 次迭代,成本值为: 0.1424041301227456
第 1800 次迭代,成本值为: 0.12865165997889055
第 1900 次迭代,成本值为: 0.11244314998165543
第 2000 次迭代,成本值为: 0.0850563103498449
第 2100 次迭代,成本值为: 0.05758391198618134
第 2200 次迭代,成本值为: 0.044567534546998216
第 2300 次迭代,成本值为: 0.03808275166600601
第 2400 次迭代,成本值为: 0.034410749018422206

在这里插入图片描述

准确度为: 0.9952153110047847
准确度为: 0.78

此时,测试集的准确率又提高了,提高到78%了。至此,多层神经网络构建完成,后续会继续完善这篇文章。

四、总结

所谓的模型,个人理解其实就是用训练集训练后的parameters,然后用这个parameters用在测试集上,最后通过prediction来进行验证,因此我们可以看到每次的出来的训练集准确度几乎为100%,就是因为这是用训练集测试出来的,但我们用这个parameters去作用于测试集时,就可能会由于各种原因导致准确率不高。

猜你喜欢

转载自blog.csdn.net/weixin_40764047/article/details/109538993