吴恩达深度学习笔记(二)——第一课第三周

概述

在这里插入图片描述
在神经网络中,其基本单元还是那些不同之处在于层数更多,组合的方式更加复杂。

分析只有一个隐藏层的网络

在这里插入图片描述
隐藏层的数值在训练集中是看不到的。
输入值X也能用 a [ 0 ] a^{[0]} a[0]表示,作为第1层的激活值
隐藏层(第1层)产生的值是 a [ 1 ] a^{[1]} a[1],里面的每一个元素可以写成 a 1 [ 1 ] , a 2 [ 1 ] . . . a^{[1]}_1,a^{[1]}_2... a1[1],a2[1]...
输入层作为第0层

对于其中的计算,先以 a 1 [ 1 ] a^{[1]}_1 a1[1]为例
a 1 [ 1 ] = σ ( w 1 [ 1 ] T X + b 1 [ 1 ] ) a^{[1]}_1=\sigma(w^{[1]T}_1X+b^{[1]}_1) a1[1]=σ(w1[1]TX+b1[1])
之后的计算类似
a 2 [ 1 ] = σ ( w 2 [ 1 ] T X + b 2 [ 1 ] ) a^{[1]}_2=\sigma(w^{[1]T}_2X+b^{[1]}_2) a2[1]=σ(w2[1]TX+b2[1])
a 3 [ 1 ] = σ ( w 3 [ 1 ] T X + b 3 [ 1 ] ) a^{[1]}_3=\sigma(w^{[1]T}_3X+b^{[1]}_3) a3[1]=σ(w3[1]TX+b3[1])
a 4 [ 1 ] = σ ( w 4 [ 1 ] T X + b 4 [ 1 ] ) a^{[1]}_4=\sigma(w^{[1]T}_4X+b^{[1]}_4) a4[1]=σ(w4[1]TX+b4[1])
向量化过程如下,对于同一层里不同的节点,往往纵向堆叠
在这里插入图片描述
给定单个特征向量X之后,执行下面4个语句,就能算出输出:
在这里插入图片描述
下面是把所有样本横向堆到矩阵中的形式,实现向量化

在这里插入图片描述

激活函数(activation function)

之前讨论的双层神经网络中,隐藏层与输出层的激活函数都是可选的,有些函数的效果比Sigmoid函数更好。
比如,双曲正切函数的表现就比 s i g m o i d sigmoid sigmoid更好(激活函数的均值更接近于0,类似于数据中心化的效果,可以让下一层的学习更方便一些)。
双曲正切函数的图像
一般而言, t a n h tanh tanh函数比 s i g m o i d sigmoid sigmoid更加优越,但在二元分类的输出层, y ^ \hat{y} y^应该在0和1之间。所以这里可以用 σ \sigma σ函数

但是不论是 s i g m o i d sigmoid sigmoid函数,还是 t a n h tanh tanh函数,当输入值很大时,斜率会变得很小,这样会拖慢梯度下降法。于是又有了 R e L U ReLU ReLU函数(修正线性函数,比较常用)
f ( z ) = m a x ( 0 , z ) f(z)=max(0,z) f(z)=max(0,z)
在这里插入图片描述 l e a k y leaky leaky R e L U ReLU ReLU
避免了Z小于0时导数为0的情况。
在这里插入图片描述
对于输出为0和1,或者进行二元分类,输出层用 s i g m a sigma sigma比较合适,其它单元用 R e L U ReLU ReLU

如果没有这些非线性的激活函数,那么输出 y ^ \hat{y} y^只是输入的一个线性组合。线性(隐藏)层没有用处,只有在输出层中可以用。如果要在中间的隐藏层中使用,可能只是用于压缩等,非常少见。

几种激活函数的导数
在这里插入图片描述

神经网络的梯度下降算法

在这里插入图片描述
其中的keepdims参数确保输出的仍是矩阵。如果不用这个,就要调用reshape函数。

随机初始化

如果把权重矩阵W初始化为0,那么就寄了
所有隐藏单元将完全对称,迭代后,对称性依然存在,那就等于隐藏层只有1个隐藏单元。就不能起到“不同的隐藏单元去计算不同的函数”这一目的。
如果初始值太大,又很可能落在激活函数中斜率极小的部分(对于 s i g m o i d sigmoid sigmoid t a n h tanh tanh函数都是如此)。所以初始化的值一般都较小。

代码作业

本次作业中是给了一个二分类的数据集,其中数据是非线性的,整体形状像一朵花。目标是构建一个神经网络来适应这些数据,实现分类。

下面是这次练习需要的包

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

%matplotlib inline

np.random.seed(1) # set a seed so that the results are consistent
X, Y = load_planar_dataset() #用来加载数据集

在这里插入图片描述

尝试使用Logistic Regression

这里的逻辑回归用的是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 ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +
       '% ' + "(percentage of correctly labelled datapoints)")

不过这里的数据显然不是简单的线性分布,用线性的逻辑回归得到的效果并不是很好。
在这里插入图片描述

神经网络模型

在这里插入图片描述
模型的示意图与相关公式见上图。
一般情况下,对于构建一个神经网络,有以下几个步骤

  • 定义网络结构(包含输入单元、隐藏层单元等等)
  • 初始化模型参数
  • 进入一个循环:forward propagation ->计算Loss ->backward propagation ,得到梯度->更新参数

定义神经网络结构

练习中要求了把隐藏单元数设为4

# GRADED FUNCTION: layer_sizes

def layer_sizes(X, Y):
    """
    Arguments:
    X -- input dataset of shape (input size, number of examples)
    Y -- labels of shape (output size, number of examples)
    
    Returns:
    n_x -- 输入层的大小
    n_h -- 隐藏层的大小
    n_y -- 输出层的大小
    """
    ### START CODE HERE ### (≈ 3 lines of code)
    n_x = X.shape[0] # size of input layer
    n_h = 4
    n_y = Y.shape[0] # size of output layer
    ### END CODE HERE ###
    return (n_x, n_h, n_y)

在这里插入图片描述

初始化模型参数

注意

  • 每个参数的维数(size)要正确,可以用shape来检查
  • 用随机值初始化权重矩阵。np.random.randn(a,b) * 0.01可以初始化一个shape=(a,b)的矩阵
  • 把误差向量(公式中的b)用np.zeros((a,b))初始化成0向量。(注意括号的层数!)
# GRADED FUNCTION: initialize_parameters

def initialize_parameters(n_x, n_h, n_y):
    """
    参数说明:
    n_x -- 输入层的大小
    n_h -- 隐藏层的大小
    n_y -- 输出层的大小
    
    Returns:
    params -- python dictionary containing your parameters:
                    W1 -- weight matrix of shape (n_h, n_x)
                    b1 -- bias vector of shape (n_h, 1)
                    W2 -- weight matrix of shape (n_y, n_h)
                    b2 -- bias vector of shape (n_y, 1)
    这里把参数放到了字典里,便于之后的使用
    """
    #下面这个语句是为了控制我们的随机数与教材中的一致,不是必须的
    np.random.seed(2) # we set up a seed so that your output matches ours although the initialization is random.
    
    ### 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 (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

在这里插入图片描述

循环

向前传播:
# GRADED FUNCTION: forward_propagation

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"
    ### 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)
    ### START CODE HERE ### (≈ 4 lines of code)
    Z1 = np.dot(W1,X)
    A1 = np.tanh(Z1)
    Z2 = np.dot(W2,A1)
    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

在这里插入图片描述

计算cost函数

主要就是敲公式,注意利用numpy进行向量化

# GRADED FUNCTION: compute_cost

def compute_cost(A2, Y, parameters):
    """
    Computes the cross-entropy cost given in equation (13)
    
    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 (13)
    """
    
    m = Y.shape[1] # number of example

    # Compute the cross-entropy cost
    ### START CODE HERE ### (≈ 2 lines of code)
    logprobs = np.multiply(np.log(A2),Y)+np.multiply((1-Y),np.log(1-A2))
    cost = (-np.sum(logprobs))/m
    ### 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

在这里插入图片描述

反向传播过程

把先前计算好的公式输入即可
在这里插入图片描述

# GRADED FUNCTION: backward_propagation

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".
    ### START CODE HERE ### (≈ 2 lines of code)
    W1 = parameters["W1"]
    W2 = parameters["W2"]
    ### END CODE HERE ###
        
    # Retrieve also A1 and A2 from dictionary "cache".
    ### START CODE HERE ### (≈ 2 lines of code)
    A1 = cache["A1"]
    A2 = cache["A2"]
    ### END CODE HERE ###
    
    # Backward propagation: calculate dW1, db1, dW2, db2. 
    ### START CODE HERE ### (≈ 6 lines of code, corresponding to 6 equations on slide above)
    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)
    ### END CODE HERE ###
    
    grads = {"dW1": dW1,
             "db1": db1,
             "dW2": dW2,
             "db2": db2}
    
    return grads
参数更新
# GRADED FUNCTION: update_parameters

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 
    grads -- python dictionary containing your gradients 
    
    Returns:
    parameters -- python dictionary containing your updated parameters 
    """
    # Retrieve each parameter from the dictionary "parameters"
    ### START CODE HERE ### (≈ 4 lines of code)
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    ### END CODE HERE ###
    
    # Retrieve each gradient from the dictionary "grads"
    ### START CODE HERE ### (≈ 4 lines of code)
    dW1 = grads["dW1"]
    db1 = grads["db1"]
    dW2 = grads["dW2"]
    db2 = grads["db2"]
    ## END CODE HERE ###
    
    # Update rule for each parameter
    ### START CODE HERE ### (≈ 4 lines of code)
    W1 -= learning_rate*dW1
    b1 -= learning_rate*db1
    W2 -= learning_rate*dW2
    b2 -= learning_rate*db2
    ### END CODE HERE ###
    
    parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}
    
    return parameters

在这里插入图片描述

把前面的内容整合成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".
    ### START CODE HERE ### (≈ 5 lines of code)
    parameters = initialize_parameters(n_x, n_h, n_y)
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    ### END CODE HERE ###
    
    # Loop (gradient descent)

    for i in range(0, num_iterations):
         
        ### START CODE HERE ### (≈ 4 lines of code)
        # 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 )
        
        ### END CODE HERE ###
        
        # Print the cost every 1000 iterations
        if print_cost and i % 1000 == 0:
            print ("Cost after iteration %i: %f" %(i, cost))

    return parameters

在这里插入图片描述

预测

# GRADED FUNCTION: predict

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.
    ### START CODE HERE ### (≈ 2 lines of code)
    A2, cache = forward_propagation(X, parameters)
    predictions = np.round(A2)
    ### END CODE HERE ###
    
    return predictions

在这里插入图片描述

在这里插入图片描述
最后的效果还是不错的(准确率比预计还高了1% emm)

#这一段代码可以看到当隐藏层单元数不同的时候在同一个数据集上产生的不同效果
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))

在这里插入图片描述
可以看到,在隐藏单元数到20的时候,产生的误差就又比较明显了。
图中n_h = 4,5,10的时候比较好。当隐藏层数过大,就会产生过拟合

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值