吴恩达网易云课堂--深度学习--编程作业--- 第一课第3周

前言

**
资源转载来源:[https://www.kesci.com/home/project/5dd3946900b0b900365f3a48]

环境:tensorflow2.0+python3.7

原文没有放所需要的文件,大家可以通过以下链接进行下载。【注意:这里只是作业所需的文件,不是完整作业的文件
链接:https://pan.baidu.com/s/1VYPWoP_Y82Mao2v0O0NsJg
提取码:4iz5

吴恩达老师的课程在B站上有,而且是中英字幕,想学习的童鞋✈✈✈✈点这里飞过去

❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ ❀ \color{maroon}{❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀ }

1.安装包

导入作业中所需要的的包:

  • numpy是Python科学计算的基本包。
  • sklearn提供了用于数据挖掘和分析的简单有效的工具。
  • matplotlib 是在Python中常用的绘制图形的库。
  • testCases提供了一些测试示例用以评估函数的正确性。
  • planar_utils提供了此作业中使用的各种函数
import numpy as np
import matplotlib.pyplot as plt
from testCases import *
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets

np.random.seed(1)   # 设置一个随机种子,以便我们后面的结果是一致的

2.数据集

用以下代码将花二分类数据集加载到变量X和Y中。

X,Y = load_planar_dataset() # 将花的二分类数据集加载到变量X和Y中

进行可视化数据

plt.scatter(X[0, :], X[1, :], c=Y, s=40, marker='*', cmap=plt.cm.Spectral)

可视化结果
在这里插入图片描述
marker是设置标记形状,可有可无,不设置就是我们的散点图,marker一般用于折线图的标记点等,他的符号形状大全想了解的点这里。在这里我只是测试一下。

不设置如下:

plt.scatter(X[0, :], X[1, :], c=Y, s=40,  cmap=plt.cm.Spectral)

在这里插入图片描述
现在我们有包含特征(x1,x2)的numpy数组(矩阵)X和包含标签(红色:0,蓝色:1)的numpy数组(向量)Y。

练习: 数据集中有多少个训练示例?另外,变量X和Y的shape是什么?

shape_X = X.shape
shape_Y = Y.shape

m = shape_X[1]

print("X的维度是:"+ str(shape_X))
print("Y的维度是:"+ str(shape_Y))
print("训练样本数:" +str(m))

输出结果为:
在这里插入图片描述

3.简单的Logistics回归

在构建完整的神经网络之前,首先让我们看看逻辑回归在此问题上的表现。 我们可以使用sklearn的内置函数来执行此操作。 运行以下代码以在数据集上训练逻辑回归分类器。

#训练逻辑回归分类器
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X.T, Y.T);

在这里插入图片描述
我们可以运行下面的代码来绘制此模型的决策边界:

#绘制决策边界
plot_decision_boundary(lambda x: clf.predict(x), X, Y)
#图标题
plt.title("Logistic Regression") 

#输出准确率
LR_predictions  = clf.predict(X.T) 
print ("逻辑回归的准确性: %d " % float((np.dot(Y, LR_predictions) + np.dot(1 - Y,1 - LR_predictions)) / float(Y.size) * 100) +"% " + "(正确标记的数据点所占的百分比)")

输出结果:
在这里插入图片描述
由于我们的数据集不是线性可分类的,所以用逻辑回归的效果不佳,我们现在进行搭建神经网络来分类,看其效果是否会更好。

✄ ✄ ✄ − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − − \color{blue}{✄✄✄-------------------------------------------------}

4.搭建神经网络模型

此次训练带有1个隐藏层的神经网络。
在这里插入图片描述
其中的数学原理:
在这里插入图片描述
根据所有的预测数据,我们可以计算损失J:
在这里插入图片描述
提示: 建立神经网络的一般方法是:

1.定义神经网络结构(输入单元数,隐藏单元数等)
2.初始化模型的参数
3.循环:

  • 实现前向传播
  • 计算损失
  • 反向传播来获得梯度
  • 更新参数(梯度下降)

我们通常会构建辅助函数来计算第1-3步,然后将它们合并为nn_model()函数。一旦构建了nn_model()并学习了正确的参数,就可以对新数据进行预测。

4.1定义神经网络结构

练习:
定义三个变量:

  • n_x:输入层的大小
  • n_h:隐藏层的大小(将其设置为4)
  • n_y:输出层的大小

提示: 使用shape来找到n_x和n_y,另外将隐藏层大小硬编码为4。

def layer_sizes(X, Y):
    '''
    参数:
    
    X -- input dataset of shape (input size, number of examples)
    Y -- labels of shape (output size, number of examples)
    
    返回:
    n_x -- 输入层的大小
    n_h -- 隐藏层的大小(将其设置为4)
    n_y -- 输出层的大小
    
    
    '''
    n_x = X.shape[0]
    n_h = 4
    n_y = Y.shape[0]
    
    return (n_x, n_h, n_y)
    
X_assess, Y_assess = layer_sizes_test_case()
(n_x, n_h, n_y) = layer_sizes(X_assess, Y_assess)

print("输入层的大小为:n_x =  " + str(n_x))
print("隐藏层的大小为:n_h =  " + str(n_h))
print("输出层的大小为:n_y =  " + str(n_y))

输出结果是在这里插入图片描述
这个仅用于评估刚刚编码的函数,并不代表实际的网络大小,这里的大小指的是里面的节点数。

4.2 初始化模型的参数

练习: 实现函数initialize_parameters()
说明:

  • 请确保参数大小正确。 如果需要,也可参考上面的神经网络图。
  • 使用随机值初始化权重矩阵。 - 使用:np.random.randn(a,b)* 0.01随机初始化维度为(a,b)的矩阵。
  • 将偏差向量初始化为零。 - 使用:np.zeros((a,b)) 初始化维度为(a,b)零的矩阵。
# 初始化模型的参数

def initialize_parameters(n_x, n_h, n_y):
    """
    Argument:
    n_x -- size of the input layer
    n_h -- size of the hidden layer
    n_y -- size of the output layer
    
    Returns:
    params -- python dictionary containing your parameters:
                    W1 -- 权重矩阵维度为 (n_h, n_x)
                    b1 -- 偏差向量维度为 (n_h, 1)
                    W2 -- 权重矩阵维度为 (n_y, n_h)
                    b2 -- 偏差向量维度为 (n_y, 1)
    """
    # 我们设置个种子,来保证尽管初始化随机,您的输出跟我们的输出匹配
    np.random.seed(2) 
    
    ### START CODE HERE ### (≈ 4 lines of code)
    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))
    ### END CODE HERE ###
    
    
    #assert断言是一句必须等价于布尔真的判定!
    #格式:  assert+空格+要判断语句+双引号“报错语句”
    
    # 这里用来检查w和b的矩阵维度
    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
n_x, n_h, n_y = initialize_parameters_test_case()

parameters = initialize_parameters(n_x, n_h, n_y)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

可以得到如下的矩阵结果:
在这里插入图片描述

4.3 循环

4.3.1 前向传播

问题: 实现forward_propagation()
说明:

  • 在上方查看分类器的数学表示形式

  • 可以使用内置在笔记本中的sigmoid()函数。

  • 也可以使用numpy库中的np.tanh()函数。

  • 必须执行以下步骤:
    1.使用parameters [“ …”]从字典“ parameters”(这是initialize_parameters()的输出)中检索出每个参数。
    2.实现正向传播,计算 Z [ 1 ] Z^{[1]} Z[1] A [ 1 ] A^{[1]} A[1] Z [ 2 ] Z^{[2]} Z[2]
    A [ 2 ] A^{[2]} A[2](所有训练数据的预测结果向量)。

  • 向后传播所需的值存储在cache中, cache将作为反向传播函数的输入。

def forward_propagation(X, parameters):
    """
    Argument:
    X -- input data of size (n_x, m)
    parameters -- python dictionary containing your parameters (output of initialization function)
    
    Returns:
    A2 -- The sigmoid output of the second activation
    cache -- a dictionary containing "Z1", "A1", "Z2" and "A2"
    """
    # Retrieve each parameter from the dictionary "parameters"
    # 从字典“parameters”检索每个参数
    ### START CODE HERE ### (≈ 4 lines of code)
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    ### END CODE HERE ###
    
    # Implement Forward Propagation to calculate A2 (probabilities)
    # 实现正向传播 来计算A2 
    
    ### START CODE HERE ### (≈ 4 lines of code)
    Z1 = np.dot(W1,X) + b1
    A1 = np.tanh(Z1)
    Z2 = np.dot(W2,A1) + b2
    A2 = sigmoid(Z2)
    ### END CODE HERE ###
    
    assert(A2.shape == (1, X.shape[1]))
    
    cache = {"Z1": Z1,
             "A1": A1,
             "Z2": Z2,
             "A2": A2}
    
    return A2, cache
X_assess, parameters = forward_propagation_test_case()

A2, cache = forward_propagation(X_assess, parameters)

# Note: we use the mean here just to make sure that your output matches ours. 
# 注意:我们在这里使用mean 只是为了确保您的输出与我们的匹配
print(np.mean(cache['Z1']) ,np.mean(cache['A1']),np.mean(cache['Z2']),np.mean(cache['A2']))

输出:
在这里插入图片描述
现在我们已经计算了包含每个示例的 a [ 2 ] ( i ) a^{[2](i)} a[2](i) A [ 2 ] A^{[2]} A[2]

4.3.2 计算损失J

**练习:**实现compute_cost()以计算损失 J J J的值
说明:

  • 有很多种方法可以实现交叉熵损失,我们为你提供了实现方法:
    − ∑ i = 0 m y ( i ) l o g ( a [ 2 ] ( i ) ) -\sum_{i=0}^my^{(i)}log(a^{[2](i)}) i=0my(i)log(a[2](i))
logprobs = np.multiply(np.log(A2),Y)
cost = - np.sum(logprobs)

你也可以使用np.multiply()然后使用np.sum()或直接使用np.dot()

损失函数公式在这里再放下:
在这里插入图片描述
现在进行实现compute_cost()

def compute_cost(A2, Y, parameters):
    """
    Computes the cross-entropy cost given in equation (6)
    
    Arguments:
    A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
    Y -- "true" labels vector of shape (1, number of examples)
    parameters -- python dictionary containing your parameters W1, b1, W2 and b2
    
    Returns:
    cost -- cross-entropy cost given equation (6)
    """
    
    m = Y.shape[1] # number of example

    # Compute the cross-entropy cost
    #计算交叉熵损失
    
     ### START CODE HERE ### (≈ 2 lines of code)
    logprobs = Y*np.log(A2) + (1-Y)* np.log(1-A2)  # 这里的相乘是对应位置元素相乘,后面进行验证
    cost = -1/m * np.sum(logprobs)
    ### END CODE HERE ###
    
    cost = np.squeeze(cost)     # makes sure cost is the dimension we expect. 确保计算的成本是我们所期望的
                                # E.g., turns [[17]] into 17 
    assert(isinstance(cost, float))
    
    return cost
A2, Y_assess, parameters = compute_cost_test_case()

print("cost = " + str(compute_cost(A2, Y_assess, parameters)))

求出来的损失函数为 0.6929198937761265

上面的求损失函数的计算验证:

logprobs =  Y_assess*np.log(A2)
#cost = - np.sum(logprobs)
print("Y_assess:      "+str(Y_assess))
print("np.log(A2):    "+str(np.log(A2)))
print("logprobs:      "+str(logprobs))
Y_assess:      [[ 1.62434536 -0.61175641 -0.52817175]]
np.log(A2):    [[-0.69268589 -0.6934306  -0.69266804]]
logprobs:      [[-1.12516111  0.42421062  0.36584769]]

算一下会发现,第三个数据就是同一列前两个数据(对应位置元素)的乘积。

4.3.3 反向传播

接下来,我们可以使用在正向传播期间计算得到的缓存,来实现反向传播。
问题: 实现函数backward_propagation()。
说明: 反向传播通常是深度学习中最难(最数学)的部分。为了帮助你更好地了解,我们提供了反向传播课程的幻灯片。你将要使用此幻灯片右侧的六个方程式以构建向量化实现。
在这里插入图片描述
在这里插入图片描述

  • 请注意, ∗ * 表示元素乘法,即对应位置的元素相乘返回其结果。

  • 将使用在深度学习中很常见的编码表示方法:
    dW1 = ∂ J ∂ W 1 \frac{\partial J}{\partial W_1} W1J

    db1 = ∂ J ∂ b 1 \frac{\partial J}{\partial b_1} b1J

    dW2 = ∂ J ∂ W 2 \frac{\partial J}{\partial W_2} W2J

    db2 = ∂ J ∂ b 2 \frac{\partial J}{\partial b_2} b2J

  • 要计算dZ1,首先要计算 g [ 1 ] ′ ( Z [ 1 ] ) g^{[1]^{'}}(Z^{[1]}) g[1](Z[1])。由于 g [ 1 ] ( . ) g^{[1]}(.) g[1](.)是tanh激活函数,因此如果 a = g [ 1 ] ( z ) a = g^{[1]}(z) a=g[1](z) g [ 1 ] ′ ( z ) = 1 − a 2 g^{[1]^{'}}(z) = 1-a^2 g[1](z)=1a2。所以我们可以使用(1 - np.power(A1, 2))计算 g [ 1 ] ′ ( Z [ 1 ] ) g^{[1]^{'}}(Z^{[1]}) g[1](Z[1])

# 反向传播

def backward_propagation(parameters, cache, X, Y):
    """
    Implement the backward propagation using the instructions above.
    
    Arguments:
    parameters -- python dictionary containing our parameters 
    cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
    X -- input data of shape (2, number of examples)
    Y -- "true" labels vector of shape (1, number of examples)
    
    Returns:
    grads -- python dictionary containing your gradients with respect to different parameters
    梯度
    """
    m = X.shape[1]
    
    # First, retrieve W1 and W2 from the dictionary "parameters".
     # 首先,从之前得到的字典“parameters”中获取W1和W2
   
    W1 = parameters["W1"]
    W2 = parameters["W2"]

        
    # Retrieve also A1 and A2 from dictionary "cache".
   # 然后 , 在之前的缓存“cache”中获取A1和A2
    A1 = cache["A1"]
    A2 = cache["A2"]
 
    # Backward propagation: calculate dW1, db1, dW2, db2. 
    # 反向传播 计算 dW1, db1, dW2, db2
    
    #根据前面幻灯片的右侧写
    
    dZ2= A2 - Y
    dW2 = 1 / m * np.dot(dZ2,A1.T)
    db2 = 1 / m * np.sum(dZ2,axis=1,keepdims=True)
    dZ1 = np.dot(W2.T,dZ2) * (1-np.power(A1,2))
    dW1 = 1 / m * np.dot(dZ1,X.T)
    db1 = 1 / m * np.sum(dZ1,axis=1,keepdims=True)
   
    
    grads = {"dW1": dW1,
             "db1": db1,
             "dW2": dW2,
             "db2": db2}
    
    return grads
parameters, cache, X_assess, Y_assess = backward_propagation_test_case()

grads = backward_propagation(parameters, cache, X_assess, Y_assess)
print ("dW1 = "+ str(grads["dW1"]))
print ("db1 = "+ str(grads["db1"]))
print ("dW2 = "+ str(grads["dW2"]))
print ("db2 = "+ str(grads["db2"]))

运行输出的结果为:

dW1 = [[ 0.01018708 -0.00708701]
       [ 0.00873447 -0.0060768 ]
       [-0.00530847  0.00369379]
       [-0.02206365  0.01535126]]
db1 = [[-0.00069728]
       [-0.00060606]
       [ 0.000364  ]
       [ 0.00151207]]
dW2 = [[ 0.00363613  0.03153604  0.01162914 -0.01318316]]
db2 = [[0.06589489]]

4.3.4 更新参数(梯度下降)

问题: 实现参数更新。 使用梯度下降,必须使用(dW1,db1,dW2,db2)才能更新(W1,b1,W2,b2)。
一般的梯度下降规则: θ = θ − α ∂ J ∂ θ \theta = \theta - \alpha \frac{\partial J }{ \partial \theta } θ=θαθJ 其中 α \alpha α是学习率,而 θ \theta θ代表一个参数。
下面两个图是: 具有良好的学习速率(收敛)和较差的学习速率(发散)的梯度下降算法。 图片由Adam Harley提供。

在这里插入图片描述
在这里插入图片描述
实现梯度下降函数:

def update_parameters(parameters, grads, learning_rate = 1.2):
    """
    Updates parameters using the gradient descent update rule given above
    使用上面给出的梯度下降更新规则更新参数
    
    Arguments:
    参数:
    
    parameters -- python dictionary containing your parameters 
    参数 ----  包含参数的python字典
    
    grads -- python dictionary containing your gradients 
    梯度 ---- 包含梯度的python字典
    
    
    Returns:
    返回
    parameters -- python dictionary containing your updated parameters 
    参数----包含更新参数了的python字典
    
    """
    # Retrieve each parameter from the dictionary "parameters"

    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
      
    # Retrieve each gradient from the dictionary "grads"
   
    dW1 = grads["dW1"]
    db1 = grads["db1"]
    dW2 = grads["dW2"]
    db2 = grads["db2"]
    
    # Update rule for each parameter
    # 根据梯度下降规则进行更新
  
    W1 = W1 - learning_rate * dW1
    b1 = b1 - learning_rate * db1
    W2 = W2 - learning_rate * dW2
    b2 = b2 - learning_rate * db2
  
    
    parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}
    
    return parameters
parameters, grads = update_parameters_test_case()
parameters = update_parameters(parameters, grads)

print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

更新参数的运行结果:

W1 = [[-0.00643025  0.01936718]
      [-0.02410458  0.03978052]
      [-0.01653973 -0.02096177]
      [ 0.01046864 -0.05990141]]
b1 = [[-1.02420756e-06]
      [ 1.27373948e-05]
      [ 8.32996807e-07]
      [-3.20136836e-06]]
W2 = [[-0.01041081 -0.04463285  0.01758031  0.04747113]]
b2 = [[0.00010457]]

4.4 构建nn_model()进行合并

问题: 在nn_model()中建立你的神经网络模型。

说明: 神经网络模型必须以正确的顺序组合先前构建的函数。

将前面4.1、4.2和4.3里面的函数合并进nn_model()里。

# 建立神经网络模型
# 将前面的函数进行合并
def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False):
    """
    Arguments:
    X -- dataset of shape (2, number of examples)
    Y -- labels of shape (1, number of examples)
    n_h -- size of the hidden layer
    num_iterations -- Number of iterations in gradient descent loop
    print_cost -- if True, print the cost every 1000 iterations
    
    Returns:
    parameters -- parameters learnt by the model. They can then be used to predict.
    """
    
    np.random.seed(3)
    n_x = layer_sizes(X, Y)[0]
    n_y = layer_sizes(X, Y)[2]
    
    # Initialize parameters, then retrieve W1, b1, W2, b2. Inputs: "n_x, n_h, n_y". Outputs = "W1, b1, W2, b2, parameters".
    # 初始化网络参数
 
    parameters = initialize_parameters(n_x, n_h, n_y)
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
   
    # Loop (gradient descent)

    for i in range(0, num_iterations):
         
        
        # Forward propagation. Inputs: "X, parameters". Outputs: "A2, cache".
        # 前向传播
        A2, cache = forward_propagation(X, parameters)
        
        # Cost function. Inputs: "A2, Y, parameters". Outputs: "cost".
        # 损失函数
        cost = compute_cost(A2, Y, parameters)
 
        # Backpropagation. Inputs: "parameters, cache, X, Y". Outputs: "grads".
        # 反向传播
        grads = backward_propagation(parameters, cache, X, Y)
 
        # Gradient descent parameter update. Inputs: "parameters, grads". Outputs: "parameters".
        # 梯度下降更新参数
        parameters = update_parameters(parameters, grads)
        
       
        
        # Print the cost every 1000 iterations
        # 每迭代1000次输出一次损失函数
       # if print_cost and i % 1000 == 0:
        #    print ("Cost after iteration %i: %f" %(i, cost))

    return parameters
X_assess, Y_assess = nn_model_test_case()

parameters = nn_model(X_assess, Y_assess, 4, num_iterations=10000, print_cost=False)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

最后模型得到的最新参数为;

W1 = [[-4.18494482  5.33220319]
      [-7.52989354  1.24306197]
      [-4.19295428  5.32631786]
      [ 7.52983748 -1.24309404]]
b1 = [[ 2.32926815]
      [ 3.7945905 ]
      [ 2.33002544]
      [-3.79468791]]
W2 = [[-6033.83672179 -6008.12981272 -6033.10095329  6008.06636901]]
b2 = [[-52.66607704]]

4.5 预测

问题: 使用你的模型通过构建predict()函数进行预测。 使用正向传播来预测结果。
提示: 在这里插入图片描述
例如,如果你想基于阈值将矩阵X设为0和1,则可以执行以下操作: X_new = (X > threshold)

# 预测
def predict(parameters, X):
    """
    Using the learned parameters, predicts a class for each example in X
    
    Arguments:
    parameters -- python dictionary containing your parameters 
    X -- input data of size (n_x, m)
    
    Returns
    predictions -- vector of predictions of our model (red: 0 / blue: 1)
    """
    
    # Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold.

    A2, cache = forward_propagation(X, parameters)
    predictions = np.round(A2)

    return predictions
parameters, X_assess = predict_test_case()

predictions = predict(parameters, X_assess)
print("predictions mean = " + str(np.mean(predictions)))

预测平均值为:0.6666666666666666

我们现在可以运行模型以查看其如何在二维数据集上运行。

# Build a model with a n_h-dimensional hidden layer
parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)

# Plot the decision boundary
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
plt.title("Decision Boundary for hidden layer size " + str(4))

# Print accuracy
predictions = predict(parameters, X)
print ('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) + '%')

在这里插入图片描述
Accuracy达到 90% 。

与Logistic回归相比,准确性确实更高。 该模型学习了flower的叶子图案! 与逻辑回归不同,神经网络甚至能够学习非线性的决策边界。

4.6 调整隐藏层大小(练习)

# 调整隐藏层大小,看其效果
plt.figure(figsize=(16, 32))
hidden_layer_sizes = [1, 2, 3, 4, 5, 10, 20]
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 ("Accuracy for {} hidden units: {} %".format(n_h, accuracy))

Accuracy for 1 hidden units: 67.5 %
Accuracy for 2 hidden units: 67.25 %
Accuracy for 3 hidden units: 90.75 %
Accuracy for 4 hidden units: 90.5 %
Accuracy for 5 hidden units: 91.25 %
Accuracy for 10 hidden units: 90.25 %
Accuracy for 20 hidden units: 90.5 %

我们可以看下对应的图示:
❧ ஐ ஐ ஐ ஐ ❧ \color{blue}{❧ஐஐஐஐ❧ }
这 里 图 片 并 排 放 置 一 直 失 败 ! ! ( 。 • ˊ ︿ • ˋ 。 ) \color{purple}{这里图片并排放置一直失败!!(。•́︿•̀。)} (ˊ︿ˋ)
在这里插入图片描述在这里插入图片描述

在这里插入图片描述在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
说明:

1.较大的模型(具有更多隐藏的单元)能够更好地拟合训练集,直到最终最大的模型过拟合数据为止。
2.隐藏层的最佳大小似乎在n_h = 5左右。此值似乎很好地拟合了数据,而又不会引起明显的过度拟合。
3.稍后我们还将学习正则化,来帮助构建更大的模型(例如n_h = 50)而不会过度拟合。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值