【深度学习基础2】神经网络基础--浅层神经网络

        转载请注明出处。谢谢。

        本博文根据 coursera 吴恩达 深度学习整理。作为理解神经网络的基础。

        本章主要内容分为两个部分,第一理解浅层网络中的前向和后向传播规则,尤其要注意其中的标注规范;第二了解到实现的细节,包括激活函数的选择以及权重初始化等更为工程化的内容。

 

一、知识点

1. 单个隐藏层的神经网络

                                           

 a) 命名

第一层:输入层; 最后一层:输出层;中间层:隐藏层

对于标记,a^{[i]}_{j},w^{[i]}_{j} 上标 i 表示层数,下标 j 表示神经元的个数 

对于输入样本X,x \in \mathbb{R}^{n_x\times m}, 记做 x^{(i)}_j, 上标 i 表示第 i 个样本,下标 j 表示第 j 个特征。

 

b) 向量化前向计算

Z^{[1]}=W^{[1]}X+b^{[1]}

A^{[1]} = g(Z^{[1]}])

Z^{[2]}=W^{[2]}A^{[1]}+b^{[2]}

A^{[2]} =\sigma(Z^{[2]}])

       和逻辑回归类似,可以写出以上公式。利用下图( 单个神经元)可以增进理解单个神经元的作用和一层神经元的作用,任意一个神经元都是由一个线性变换和一个激活函数组合而成,该层的输出为下一层的输入:

                             

       有两个地方值得注意:

       首先矩阵W,在逻辑回归中是w_T,在这里W其实是每一个神经元的w_t的组合,统一记做了W,即

                                                                       W^{[1]}=\begin{bmatrix} \cdots & w^{[1]} _1 ^T&\cdots \\ ... & w^{[1]} _2 ^T &... \\ \cdots & \vdots &\cdots \\ \cdots & w^{[1]} _4 ^T & \cdots \end{bmatrix}

      其次,中间的函数 g 表示了任意激活函数,可以是sigmoid,tanh,  ReLU,  Leaky ReLU 中任意一个。但是由于这是二分类问题,所以最后的激活函数仍旧是sigmoid。

c) 向量化的反向传播

      最简便的方法就是依据链式法则和前向公式直接计算。第二层的反向传播和逻辑回归类似。但第一层有细微差别:

 dZ^{[2]} = A^{[2]} -Y

 dW^{[2]} = dZ^{[2]}A^{[1]}^T

 db^{[2]} = dZ^{[2]}

 dZ^{[1]}=W^{[2]}^TdZ^{[2]}*g^{[1]}'(Z^{[1]})

 dW^{[1]}=dZ^{[1]}X^T

 db^{[1]} = dZ^{[1]}

dz2 = A2 - Y
dw2 = 1.0/m * np.dot(dz2, A1.T)
db2 = 1.0/m * np.sum(dz2, axis=1, keepdims=True)
dz1 = np.dot(w2.T, dz2) * g_(Z1)
dw1 = 1.0/m * np.dot(dz1,X.T)
db1 = 1.0/m * np.sum(dz1,axis=1,keepdims=True)

2. 激活函数

(1) sigmoid:     \sigma(x) = \frac{e^z}{1+e^z} 

def sigmoid(x):
    return 1.0 / (1.0 + np.exp(-x))

 优点:输出是在(0,1)开区间内,容易联想到概率。

 缺点:当输入极大或极小,函数的梯度就变得很小了,几乎为零。在反向传播的过程中,容易造成梯度饱和(梯度弥散);函数输出不是以0为中心的,这样会使权重更新效率降低;sigmod函数要进行指数运算,相对比较慢

 

(2) tanh :   tanh(x) = \frac{e^x-e^{-x}}{e^x+e^{-x}}

def tanh(x):
    return 2 * sigmoid(2 * x) - 1

       tanh是双曲正切函数,tanh函数和sigmod函数的曲线是比较相近的。同样不利于梯度下降。但其在整个函数是以0为中心的,因而特性相对好一些。一般二分类问题中,隐藏层用tanh函数,输出层用sigmod函数。

(3) ReLU : ReLU(x)=max(0,x)

def ReLU(x):
    return np.maximum(0, x)

 

       该函数能较好解决梯度下降的问题。计算速度要快很多,不需要进行指数运算。但当输入是负数的时候,ReLU是完全不被激活的,在反向传播过程中,输入负数,梯度就会完全恒为零,无法更新。同样它也不是对称的图像。

 

(4)Leaky ReLu : LeakyReLU(x)= max(0.01*x,x)

def LeakyReLu(x):
    return np.maximum(0.01*x, x)

在负数区域内是线性运算,斜率很小,但是不会趋于0.

3. 随机初始化

    在多层网络中,不能使用0为初始化权重,因为这会导致同一层的梯度更新为同一个值。最好采用随机初始化:

w = np.random.rand((2,2))*0.01
b = np.zeros((2,1))

### 概念辨析 ###:

Logistic回归的权重w应该随机初始化,而不是全零,因为如果初始化为全零,那么逻辑回归将无法学习到有用的决策边界,因为它将无法“破坏对称性”,是正确的吗?

       Logistic回归没有隐藏层。 如果将权重初始化为零,则Logistic回归中的第一个示例x将输出零,但Logistic回归的导数取决于不是零的输入x(因为没有隐藏层)。 因此,在第二次迭代中,如果x不是常量向量,则权值遵循x的分布并且彼此不同。

二、实践

The general methodology to build a Neural Network is to:

1. Define the neural network structure ( # of input units,  # of hidden units, etc). 
2. Initialize the model's parameters
3. Loop:
    - Implement forward propagation
    - Compute loss
    - Implement backward propagation to get the gradients
    - Update parameters (gradient descent)

You often build helper functions to compute steps 1-3 and then merge them into one function we call nn_model(). Once you've built nn_model() and learnt the right parameters, you can make predictions on new data.

1. 定义网络的结构:输入层的大小(特征)、输出层大小(特征)包括隐藏层神经元个数

- n_x: the size of the input layer
- n_h: the size of the hidden layer (set this to 4) 
- n_y: the size of the output layer

 

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 -- the size of the input layer
    n_h -- the size of the hidden layer
    n_y -- the size of the output layer
    """
    ### 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)

2. 初始化网络参数

 np.random.randn(a,b) * 0.01 对尺寸为 (a,b) 的权重矩阵进行初始化。

   np.zeros((a,b)) 对尺寸为(a,b)的bias矩阵进行初始化。

# GRADED FUNCTION: initialize_parameters

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 -- 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

3. 开始循环(根据公式)

3.1 前向传播

# 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)+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

3.2 计算损失

logprobs = np.multiply(np.log(A2),Y)
cost = - np.sum(logprobs) 

# 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(np.log(1-A2),1-Y)
    cost = -1.0/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

3.3 根据公式计算反向传播

# 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.0/m * np.dot(dZ2,A1.T)
    db2 = 1.0/m * np.sum(dZ2,axis=1,keepdims=True)
    dZ1 = np.dot(W2.T,dZ2)*(1 - np.power(A1, 2))
    dW1 = 1.0/m * np.dot(dZ1,X.T)
    db1 = 1.0/m * np.sum(dZ1,axis=1,keepdims=True)
    ### END CODE HERE ###
    
    grads = {"dW1": dW1,
             "db1": db1,
             "dW2": dW2,
             "db2": db2}
    
    return grads

3.4 参数更新

# 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 = W1 - learning_rate * dW1 
    b1 = b1 - learning_rate * db1 
    W2 = W2 - learning_rate * dW2 
    b2 = b2 - learning_rate * db2 
    ### END CODE HERE ###
    
    parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}
    
    return parameters

3.5 综合nn模型

# GRADED FUNCTION: 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, learning_rate = 1.2)
        
        ### 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

3.6 预测

# 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 = (A2 > 0.5)
    ### END CODE HERE ###
    
    return predictions

结果:

# 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))

小结:

1. 熟悉单层训练过程

2. 拓展:使用不同神经元个数的影响:

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 20 hidden units: 90.0 %
Accuracy for 50 hidden units: 90.25 %

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值