深度学习第一课程笔记(2)

plt.figure(figsize=(16, 32))
hidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50] #隐藏层数量
for i, n_h in enumerate(hidden_layer_sizes):
    plt.subplot(5, 2, i + 1)
    plt.title('Hidden Layer of size %d' % n_h)
    parameters = nn_model(X, Y, n_h, num_iterations=5000)
    plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
    predictions = predict(parameters, X)
    accuracy = float((np.dot(Y, predictions.T) + np.dot(1 - Y, 1 - predictions.T)) / float(Y.size) * 100)
    print ("隐藏层的节点数量: {}  ,准确率: {} %".format(n_h, accuracy))

隐藏层的节点数量: 1  ,准确率: 67.5 %
隐藏层的节点数量: 2  ,准确率: 67.25 %
隐藏层的节点数量: 3  ,准确率: 90.75 %
隐藏层的节点数量: 4  ,准确率: 90.5 %
隐藏层的节点数量: 5  ,准确率: 91.25 %
隐藏层的节点数量: 20  ,准确率: 90.0 %
隐藏层的节点数量: 50  ,准确率: 90.75 %

在这里插入图片描述

  • 较大的模型(具有更多隐藏单元)能够更好地适应训练集,直到最终的最大模型过度拟合数据。
    后面学习有关正则化的知识,它允许使用非常大的模型(如n_h = 50),而不会出现太多过度拟合。
    testCases.py
#-*- coding: UTF-8 -*-
"""
# WANGZHE12
"""
import numpy as np

def layer_sizes_test_case():
    np.random.seed(1)
    X_assess = np.random.randn(5, 3)
    Y_assess = np.random.randn(2, 3)
    return X_assess, Y_assess

def initialize_parameters_test_case():
    n_x, n_h, n_y = 2, 4, 1
    return n_x, n_h, n_y

def forward_propagation_test_case():
    np.random.seed(1)
    X_assess = np.random.randn(2, 3)

    parameters = {'W1': np.array([[-0.00416758, -0.00056267],
        [-0.02136196,  0.01640271],
        [-0.01793436, -0.00841747],
        [ 0.00502881, -0.01245288]]),
     'W2': np.array([[-0.01057952, -0.00909008,  0.00551454,  0.02292208]]),
     'b1': np.array([[ 0.],
        [ 0.],
        [ 0.],
        [ 0.]]),
     'b2': np.array([[ 0.]])}

    return X_assess, parameters

def compute_cost_test_case():
    np.random.seed(1)
    Y_assess = np.random.randn(1, 3)
    parameters = {'W1': np.array([[-0.00416758, -0.00056267],
        [-0.02136196,  0.01640271],
        [-0.01793436, -0.00841747],
        [ 0.00502881, -0.01245288]]),
     'W2': np.array([[-0.01057952, -0.00909008,  0.00551454,  0.02292208]]),
     'b1': np.array([[ 0.],
        [ 0.],
        [ 0.],
        [ 0.]]),
     'b2': np.array([[ 0.]])}

    a2 = (np.array([[ 0.5002307 ,  0.49985831,  0.50023963]]))

    return a2, Y_assess, parameters

def backward_propagation_test_case():
    np.random.seed(1)
    X_assess = np.random.randn(2, 3)
    Y_assess = np.random.randn(1, 3)
    parameters = {'W1': np.array([[-0.00416758, -0.00056267],
        [-0.02136196,  0.01640271],
        [-0.01793436, -0.00841747],
        [ 0.00502881, -0.01245288]]),
     'W2': np.array([[-0.01057952, -0.00909008,  0.00551454,  0.02292208]]),
     'b1': np.array([[ 0.],
        [ 0.],
        [ 0.],
        [ 0.]]),
     'b2': np.array([[ 0.]])}

    cache = {'A1': np.array([[-0.00616578,  0.0020626 ,  0.00349619],
         [-0.05225116,  0.02725659, -0.02646251],
         [-0.02009721,  0.0036869 ,  0.02883756],
         [ 0.02152675, -0.01385234,  0.02599885]]),
  'A2': np.array([[ 0.5002307 ,  0.49985831,  0.50023963]]),
  'Z1': np.array([[-0.00616586,  0.0020626 ,  0.0034962 ],
         [-0.05229879,  0.02726335, -0.02646869],
         [-0.02009991,  0.00368692,  0.02884556],
         [ 0.02153007, -0.01385322,  0.02600471]]),
  'Z2': np.array([[ 0.00092281, -0.00056678,  0.00095853]])}
    return parameters, cache, X_assess, Y_assess

def update_parameters_test_case():
    parameters = {'W1': np.array([[-0.00615039,  0.0169021 ],
        [-0.02311792,  0.03137121],
        [-0.0169217 , -0.01752545],
        [ 0.00935436, -0.05018221]]),
 'W2': np.array([[-0.0104319 , -0.04019007,  0.01607211,  0.04440255]]),
 'b1': np.array([[ -8.97523455e-07],
        [  8.15562092e-06],
        [  6.04810633e-07],
        [ -2.54560700e-06]]),
 'b2': np.array([[  9.14954378e-05]])}

    grads = {'dW1': np.array([[ 0.00023322, -0.00205423],
        [ 0.00082222, -0.00700776],
        [-0.00031831,  0.0028636 ],
        [-0.00092857,  0.00809933]]),
 'dW2': np.array([[ -1.75740039e-05,   3.70231337e-03,  -1.25683095e-03,
          -2.55715317e-03]]),
 'db1': np.array([[  1.05570087e-07],
        [ -3.81814487e-06],
        [ -1.90155145e-07],
        [  5.46467802e-07]]),
 'db2': np.array([[ -1.08923140e-05]])}
    return parameters, grads

def nn_model_test_case():
    np.random.seed(1)
    X_assess = np.random.randn(2, 3)
    Y_assess = np.random.randn(1, 3)
    return X_assess, Y_assess

def predict_test_case():
    np.random.seed(1)
    X_assess = np.random.randn(2, 3)
    parameters = {'W1': np.array([[-0.00615039,  0.0169021 ],
        [-0.02311792,  0.03137121],
        [-0.0169217 , -0.01752545],
        [ 0.00935436, -0.05018221]]),
     'W2': np.array([[-0.0104319 , -0.04019007,  0.01607211,  0.04440255]]),
     'b1': np.array([[ -8.97523455e-07],
        [  8.15562092e-06],
        [  6.04810633e-07],
        [ -2.54560700e-06]]),
     'b2': np.array([[  9.14954378e-05]])}
    return parameters, X_assess


planar_utils.py

import matplotlib.pyplot as plt
import numpy as np
import sklearn
import sklearn.datasets
import sklearn.linear_model

def plot_decision_boundary(model, X, y):
    # Set min and max values and give it some padding
    x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1
    y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1
    h = 0.01
    # Generate a grid of points with distance h between them
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    # Predict the function value for the whole grid
    Z = model(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    # Plot the contour and training examples
    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.ylabel('x2')
    plt.xlabel('x1')
    plt.scatter(X[0, :], X[1, :], c=np.squeeze(y), cmap=plt.cm.Spectral)


def sigmoid(x):
    s = 1/(1+np.exp(-x))
    return s

def load_planar_dataset():
    np.random.seed(1)
    m = 400 # number of examples
    N = int(m/2) # number of points per class
    D = 2 # dimensionality
    X = np.zeros((m,D)) # data matrix where each row is a single example
    Y = np.zeros((m,1), dtype='uint8') # labels vector (0 for red, 1 for blue)
    a = 4 # maximum ray of the flower

    for j in range(2):
        ix = range(N*j,N*(j+1))
        t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # theta
        r = a*np.sin(4*t) + np.random.randn(N)*0.2 # radius
        X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
        Y[ix] = j

    X = X.T
    Y = Y.T

    return X, Y

def load_extra_datasets():  
    N = 200
    noisy_circles = sklearn.datasets.make_circles(n_samples=N, factor=.5, noise=.3)
    noisy_moons = sklearn.datasets.make_moons(n_samples=N, noise=.2)
    blobs = sklearn.datasets.make_blobs(n_samples=N, random_state=5, n_features=2, centers=6)
    gaussian_quantiles = sklearn.datasets.make_gaussian_quantiles(mean=None, cov=0.5, n_samples=N, n_features=2, n_classes=2, shuffle=True, random_state=None)
    no_structure = np.random.rand(N, 2), np.random.rand(N, 2)

    return noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure

深层神经网络

深层神经网络和前面类似,无非就是所对应的隐藏层数增多,类型增多,计算复杂
多层神经网络

  • 同时注意在多层网络中,不可避免的for循环,在代码实现中,需要核对矩阵的维数。
  • 再核对时候,进行手写,会更加详细,下面是手写的层数核对w和b矩阵,注意以下输出单元为一个输出单元,在后面学习中,也会学习有多个输出单元的情况:
    在这里插入图片描述
    在这里插入图片描述
  • 注意到,这两张图片详细写了每个参数所对应的维度,在代码实现过程中,务必保证每个参数的维度保持正确,可以大大降低BUG的出现率,以及自己的调试过程。

对于深层神经的理解

以下面的图片为例进行理解:
在这里插入图片描述

  • 以人脸识别为例:
  1. 将第一层,当成一个特征探测器或者边缘探测器,在第二层第一个图,各个小的隐藏单元找不同方向的边缘。
  2. 第二层可以看成,在第一层找的边缘结合起来,形成人脸不同部分。
  3. 第三层可以看成,在不同的部位合成一个完整的人脸,就可以进行人脸的识别。
    级别依次变复杂,从小区域到大区域。
  • 以语音识别为例:
  1. 第一层可以看成,低层次音频的波形特征,分辨白噪音,底噪等等。
  2. 第二层可以看成,组合乘了单词中的某个字母。
  3. 第三层可以看成,这些字母在组合成单词。
  4. 第四层可以看成,单词变句子,这样子就完成了一个语音的识别。

整个多层的前向和反向传播的流程图

如下图:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

前向和反向很清楚的展现出来了。

  • 深度学习在解决问题时候,不是说隐藏层数,节点数量越多越好,而是要采取一个合理的匹配的层数与节点,在代码中隐藏层的大小n学习率α迭代次数神经网络中的层数L激活函数的选择,以及节点的数量都是我们要进行超参数调节的。

  • 可以从logistic模型开始,1层,2层进行试验。

  • 对于,学习率α迭代次数神经网络中的层数L,他们一般决定了w和b的大小。

  • 多层示意图:在这里插入图片描述

  • 不论是单层,双层还是多层,其大体步骤相似:

  1. 初始化网络参数
  2. 前向传播,包括正向z和激活函数部分
  3. 计算成本函数(误差函数)
  4. 反向传播,包括反向dw,db和激活函数的反向传播
  5. 更新参数

具体函数有:
initialize_parameters 双层结构数据初始化
initialize_parameters_deep 多层神经网络数据初始化
linear_forward 线性正向Z前向
linear_activation_forward 线性激活前向传播
L_model_forward 多层向前传播
compute_cost 计算成本函数
linear_backward 反向传播需要用到dZ
linear_activation_backward 带激活函数的线性反向传播
L_model_backward 多层向后传播
update_parameters 使用梯度下降更新参数
predict 该函数用于预测L层神经网络的结果
L_layer_model L层神经网络模型
print_mislabeled_images 绘制预测和实际不同的图像
具体代码如下,有注释解释:

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

np.random.seed(1)


def initialize_parameters(n_x, n_h, n_y):
    # 双层结构的初始化
    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

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代表层数  len方法返回对象(字符、列表、元组等)长度或项目个数。

    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])
        # sqrt 数字x的平方根。
        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

def linear_forward(A, W, b):
    #
    #    A[l] 就是激活后的Z[l],且注意,维数相同 (layers_dims[l] , 1 )
    #    W - 权重矩阵,numpy数组,维度为(当前图层的节点数量,前一图层的节点数量)(layers_dims [l],layers_dims [l-1])
    #    b - 偏向量,numpy向量,维度为(当前图层节点数量,1)(layers_dims[l] , 1 )

    #    Z - 激活功能的输入,也称为预激活参数
    #    cache - 一个包含“A”,“W”和“b”的字典,存储这些变量以有效地计算后向传递

    Z = np.dot(W, A) + b
    assert (Z.shape == (W.shape[0], A.shape[1]))
    # shape[0]W的矩阵行数,shape [1]A的矩阵列数
    cache = (A, W, b)

    return Z, cache
def linear_activation_forward(A_prev, W, b, activation):
    # 两层前向传播模型
    # activation - 选择在此层中使用的激活函数名,字符串类型,【"sigmoid" | "relu"】
    # A - 激活函数的输出,也称为激活后的值
    # cache - 一个包含“linear_cache”和“activation_cache”的字典,我们需要存储它以有效地计算后向传递

    if activation == "sigmoid":
        Z, linear_cache = linear_forward(A_prev, W, b)
        # linear_cache 是 A W B 的数据 这里的A是上一层的激活A[l-1]
        A, activation_cache = sigmoid(Z)
        # activation_cache其实就是Z,这里的A是激活后的A[l]
    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

def L_model_forward(X, parameters):
    # 多层向前传播
    #    X - 数据,numpy数组,维度为(输入节点数量,示例数)
    #    parameters - initialize_parameters_deep()的输出,即初始化多层W,B的参数
    #    AL - 最后的激活值
    #    caches  包括linear_relu_forward()的每个cache(有L-1个,索引为从0到L-2)
    #                   中间层数的数据
    #               linear_sigmoid_forward()的cache(只有一个,索引为L-1)
    #
    caches = []
    A = X
    L = len(parameters) // 2  # parameters 是包含w和b的字典,除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]))
    # X.shape[1],最开始输入x的列数,即样本数。
    return AL, caches

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


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
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)
        # 这里线性传播要先求出dZ,其实就是在代码实现中分开写了
        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
def L_model_backward(AL, Y, caches):
     # 多层向后传播
     # AL - 概率向量,正向传播的输出(L_model_forward())
     # Y - 标签向量(例如:如果不是猫,则为0,如果是猫则为1),维度为(1,数量)
     # caches:  linear_activation_forward("relu")的cache,不包含输出层
     #          linear_activation_forward("sigmoid")的cache


    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
def update_parameters(parameters, grads, learning_rate):
    # 使用梯度下降更新参数
    #  parameters - c
    #  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
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
def L_layer_model(X, Y, layers_dims, learning_rate=0.0075, num_iterations=3000, print_cost=False, isPlot=True):
     #    L层神经网络模型
	 #    X - 输入的数据,维度为(n_x,例子数)
     #    Y - 标签,向量,0为非猫,1为猫,维度为(1,数量)
     #    layers_dims - 包含我们网络中每个图层的节点数量的列表
     #    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
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)  # set default size of plots
    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"))

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, 8, 6, 1] #  5-layer model
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) #训练集
pred_test = predict(test_x, test_y, parameters) #测试集

#  12288 20 8 6 1效果很好

训练开始:

  1. 选取 12288,20,7,5,1
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)

结果如下

0 次迭代,成本值为: 0.715731513414100 次迭代,成本值为: 0.674737759347200 次迭代,成本值为: 0.660336543362300 次迭代,成本值为: 0.646288780215400 次迭代,成本值为: 0.629813121693500 次迭代,成本值为: 0.606005622927600 次迭代,成本值为: 0.569004126398700 次迭代,成本值为: 0.519796535044800 次迭代,成本值为: 0.464157167863900 次迭代,成本值为: 0.4084203004831000 次迭代,成本值为: 0.3731549921611100 次迭代,成本值为: 0.305723745731200 次迭代,成本值为: 0.2681015284771300 次迭代,成本值为: 0.2387247482771400 次迭代,成本值为: 0.2063226325791500 次迭代,成本值为: 0.1794388692751600 次迭代,成本值为: 0.1579873581881700 次迭代,成本值为: 0.1424041301231800 次迭代,成本值为: 0.1286516599791900 次迭代,成本值为: 0.1124431499822000 次迭代,成本值为: 0.08505631034972100 次迭代,成本值为: 0.05758391198612200 次迭代,成本值为: 0.0445675345472300 次迭代,成本值为: 0.0380827516662400 次迭代,成本值为: 0.0344107490184

在这里插入图片描述

pred_train = predict(train_x, train_y, parameters) #训练集
pred_test = predict(test_x, test_y, parameters) #测试集

得到

准确度为: 0.9952153110047847
准确度为: 0.78
  1. 当选取
layers_dims = [12288, 20, 8, 6, 1] #  5-layer model
parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 2500, print_cost = True,isPlot=True)
0 次迭代,成本值为: 0.7090066035463921100 次迭代,成本值为: 0.5547976710796781200 次迭代,成本值为: 0.452866809390846300 次迭代,成本值为: 0.3699436293448533400 次迭代,成本值为: 0.25595110840785856500 次迭代,成本值为: 0.19486317927574656600 次迭代,成本值为: 0.10483426581959851700 次迭代,成本值为: 0.06079827792749748800 次迭代,成本值为: 0.040036296543017866900 次迭代,成本值为: 0.0253572567535491761000 次迭代,成本值为: 0.0182890159706556031100 次迭代,成本值为: 0.0139880038114062311200 次迭代,成本值为: 0.0110600212182293441300 次迭代,成本值为: 0.0090121688774010821400 次迭代,成本值为: 0.0075147245120866211500 次迭代,成本值为: 0.0063925839277496111600 次迭代,成本值为: 0.0055180383020631681700 次迭代,成本值为: 0.00483167721000152351800 次迭代,成本值为: 0.0042741888933359531900 次迭代,成本值为: 0.0038144486566334062000 次迭代,成本值为: 0.0034392341516958062100 次迭代,成本值为: 0.0031184902964373882200 次迭代,成本值为: 0.0028469946344227452300 次迭代,成本值为: 0.0026132166085896082400 次迭代,成本值为: 0.0024110043646669395

在这里插入图片描述
在迭代到1000次左右,就可以把误差函数值保持在比较小的地方,不同的层数,每层不同的数量,都会影响效率的高低,这也是优化的目标。

参考何宽文章,点击这里可以到达

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值