神经网络的梯度下降公式推导及代码实现
1. 神经网络结构
以 2-Layers-Neural Network 为例,其结构如下。
该神经网络有两层,仅有一层为隐藏层。输入相应的数据,输出为对应标签
神经网络的梯度下降(Gradient descent)更新步骤基本为:
Step 1 | Step 2 | Step 3 | Step 4 |
Forward Propagation | 计算Cost Function | Back Propagation | 更新参数W,b |
表格描述的是一个epoch的步骤,需要不停的重复Step 1~4, 需经过多个epochs直到Cost Function 收敛
2. Step 1: Forward Propagation
其第一层(隐藏层)由 $ h $ 个神经元(隐藏单元)构成, 每个神经元的都要经过两部计算:
同理, 只需要改变一下对应的下角标, 也能被计算出来。
此时,第一层神经元的输出为
接下来进行下一层的计算:
此时, 为模型生成的一个0~1之间的数字,需要利用一定的阈值使得其能变为标签值
if {A2 < 0.5}:
Y = 0
else:
Y = 1
由于第二层只有一个神经元,因此本文中 $Z_1^{[2]} $ 和 $Z^{[2]} $ 代表相同含义
- 简单的描述一下数据集的结构:
数据集为
其中, 为 feature个数, 为训练集的sample数, $Y \in {0,1} $. 下图举了两个samples的例子.
3. Step 2: 计算 Cost Function
Cost Function是对于每一个样本的 Loss 函数的平均值,计算如下:
其中,,及第二层第
4. Step 3: Back Propagation
Back Propagation 是基于Chain Theory的梯度计算方法。其输出为W,b参数的梯度,以实现参数更新。
梯度下降的参数更新为:
学习率小更新慢,反之则快。
因此,如果要更新 W 和 b,则需要计算对应的梯度。
由Forward Propagation知道,我么们需要计算的梯度由:
则其计算如下:
4.1 梯度
其中后面一项可以直接求解:
因为
所以
因此只需要求 .利用 Chain Theory 可得:
则
推导1: 求证下面等式
- 如何理解 的维度问题?
其中 ,
, , .
拿出 和 具体分析:
则
因为:则表示:
则 维度为(m,h)
因此,可以推导出
4.1 梯度
这相当于是对求平均值。
import numpy as np
dZ2 = A2 - Y
db2 = 1.0 / m * np.sum(dZ2, axis=1, keepdims=True)
4.2 梯度
其他梯度也可以通过类似的方式求解
5. 参数更新
梯度下降的参数更新为:
6. 部分函数以及代码实现
详情可见 Coursera Deep Learning.
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"
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
# Implement Forward Propagation to calculate A2 (probabilities)
Z1 = np.dot(W1, X) + b1
A1 = np.tanh(Z1)
Z2 = np.dot(W2, A1) + b2
A2 = sigmoid(Z2)
assert (A2.shape == (1, X.shape[1]))
cache = {"Z1": Z1,
"A1": A1,
"Z2": Z2,
"A2": A2}
return A2, cache
def compute_cost(A2, Y):
"""
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
logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y))
cost = -(1.0 / m) * np.sum(logprobs)
cost = np.squeeze(cost) # makes sure cost is the dimension we expect. # E.g., turns [[17]] into 17
assert (isinstance(cost, float))
return cost
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] # sample size
# First, retrieve W1 and W2 from the dictionary "parameters".
W1 = parameters["W1"]
W2 = parameters["W2"]
# Retrieve also A1 and A2 from dictionary "cache".
A1 = cache["A1"]
A2 = cache["A2"]
# Backward propagation: calculate dW1, db1, dW2, db2.
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)
grads = {"dW1": dW1,
"db1": db1,
"dW2": dW2,
"db2": db2}
return grads
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"
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
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)
Cost_plot = []
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)
# 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)
# Stack all the cost for plot
Cost_plot = np.append(Cost_plot, cost)
# Print the cost every 1000 iterations
if print_cost and i % 10 == 0:
print("Cost after iteration %i: %f" % (i, cost))
return parameters, Cost_plot
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 = (A2 > 0.5)
return predictions
- Main Process
# Package imports
import numpy as np
import matplotlib.pyplot as plt
import sklearn.linear_model
from NN_Compute_Function import nn_model, predict
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets
np.random.seed(1) # set a seed so that the results are consistent
'''
Import the data from Datasets
'''
# Visualize the data:
X, Y = load_planar_dataset()
'''
Build a model with a n_h-dimensional hidden layer
'''
parameters, cost_for_plot = nn_model(X, Y, n_h=9, num_iterations=10000, print_cost=True)
plt.plot(cost_for_plot, label='Cost function')
plt.legend()
plt.show()
# Print accuracy of 2-Layers-NN
predictions = predict(parameters, X)
print('Accuracy of 2-Layers-NN: %d' % float(
(np.dot(Y, predictions.T) + np.dot(1 - Y, 1 - predictions.T)) / float(Y.size) * 100) + '%'
+ " with hidden layer size of " + str(4))
if __name__ == "__main__":
print('=====[This is implementation of two layers neural network on classification]=====')