本文主要是介绍deep_learning_week3_BP神经网络,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
deep_learning_week3_BP神经网络
标签: 机器学习深度学习
代码已上传github:
https://github.com/PerfectDemoT/my_deeplearning_homework
- deep_learning_week3_BP神经网络
-
- 这是吴恩达深度学习里的第二次作业
- 实现BP神经网络
- 现在开始真正的弄bp神经网络的各层啦
-
这是吴恩达深度学习里的第二次作业
实现BP神经网络
- 首先先导入包
#先导入包
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
import matplotlib.pyplot as plt
import pylab
- 然后我们设置一个随机数种子备用,再导入数据,然后可视化一下(PS:这个不知道什么原因,显示不出来,虽然原来的代码有问题会报错,不过我看了库中函数的运行方式,将Y修改后不会报错了,但是还是显示不出,就很迷,不过对后面的结果没影响)
np.random.seed(1) # set a seed so that the results are consistent#现在开始导入数据,一个X一个Y
X, Y = load_planar_dataset()print (np.shape(X))
print (np.shape(Y))
#可知,这个X为一个包含400个具有两个参数样本的矩阵,Y为其标签#将数据可视化一下,看起来像一朵红花(很奇怪,我这里已开始运行不了,然后改正后不报错了,不过还是显示不出图片)
plt.scatter(X[0, :], X[1, :], c=Y.reshape(X[0,:].shape), s=40, cmap=plt.cm.Spectral);
3. 现在,我们可以来处理这些数据了,比如,先看看这些矩阵的大小
### START CODE HERE ### (≈ 3 lines of code)
shape_X = X.shape
shape_Y = Y.shape
m = X.shape[1] # training set size
### END CODE HERE ###print ('The shape of X is: ' + str(shape_X))
print ('The shape of Y is: ' + str(shape_Y))
print ('I have m = %d training examples!' % (m))
- 然后呢,老师贴心地给了训练好了的单个logistic分类器,我们可以试试
# Train the logistic regression classifier(这里先用写好的分类器训练一下)
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X.T, Y.T);
- 但是呢,你会发现,这个的分类效果并不好,准确率只有百分之四十九
# Plot the decision boundary for logistic regression
plot_decision_boundary(lambda x: clf.predict(x), X, Y)
plt.title("Logistic Regression")# Print accuracy,现在这里画出这些点的分类边界(好吧这里有点小问题,还是上面那个画图的问题,)
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)")
#可以看出,这个线性分类器效果并不好,就算是训练集,准确率也很低所以这里就要用bp网络了
#这是输出
Accuracy of logistic regression: 47 % (percentage of correctly labelled datapoints)
现在开始真正的弄bp神经网络的各层啦
- 首先,我们设计一个定义网络结构的函数
#首先定义各层网络的结构
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 layern_h -- the size of the hidden layern_y -- the size of the output layer"""### START CODE HERE ### (≈ 3 lines of code)n_x = X.shape[0] # size of input layern_h = 4n_y = Y.shape[0] # size of output layer### END CODE HERE ###return (n_x, n_h, n_y)
返回的是X输入的参数个数,隐藏层的神经元个数,输出层神经元个数,现在我们来输出网络看一看
#现在输出来看看我们的网络结构
X_assess, Y_assess = layer_sizes_test_case() #这里是将数据导入
(n_x, n_h, n_y) = layer_sizes(X_assess, Y_assess)
print("The size of the input layer is: n_x = " + str(n_x))
print("The size of the hidden layer is: n_h = " + str(n_h))
print("The size of the output layer is: n_y = " + str(n_y))
输出是这样(就不截图了。。。)
The size of the input layer is: n_x = 5
The size of the hidden layer is: n_h = 4
The size of the output layer is: n_y = 2
2 . 现在来初始化(函数里面本身就写了随机的种子,这里为2)
#接下来是初始化函数
# GRADED FUNCTION: initialize_parameters
def initialize_parameters(n_x, n_h, n_y):"""Argument:n_x -- size of the input layern_h -- size of the hidden layern_y -- size of the output layerReturns: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.01b1 = np.zeros((n_h , 1)) #记着这里是两个括号W2 = np.random.randn(n_y , n_h) * 0.01b2 = 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
然后现在来看看初始化的样子
代码长这样:
#现在可以看看初始化结构咋样
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"]))
输出是
W1 = [[-0.00416758 -0.00056267][-0.02136196 0.01640271][-0.01793436 -0.00841747][ 0.00502881 -0.01245288]]
b1 = [[ 0.][ 0.][ 0.][ 0.]]
W2 = [[-0.01057952 -0.00909008 0.00551454 0.02292208]]
b2 = [[ 0.]]
- 前期准备算是做的差不多啦,现在开始正向传播啦
先上公式:
大家注意看23到26行,那里是正向传播的精髓之处
#OK,现在开始正向传播啦
# 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 activationcache -- 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) + b1A1 = np.tanh(Z1)Z2 = np.dot(W2 , A1) + b2A2 = 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.
print(np.mean(cache['Z1']) ,np.mean(cache['A1']),np.mean(cache['Z2']),np.mean(cache['A2']))
然后,结果如下:
-0.000499755777742 -0.000496963353232 0.000438187450959 0.500109546852
- 到了这里,我们可以来看看cost函数了,
先看看公式:
J=−1m∑i=0m(y(i)log(a[2](i))+(1−y(i))log(1−a[2](i))) J = − 1 m ∑ i = 0 m ( y ( i ) l o g ( a [ 2 ] ( i ) ) + ( 1 − y ( i ) ) l o g ( 1 − a [ 2 ] ( i ) ) )
下面是他的代码(重点关注28,29行)
#现在来算算代价函数J
#GRADED
#FUNCTION: compute_costdef 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 b2Returns:cost -- cross-entropy cost given equation (13)"""m = Y.shape[1] # number of example# Retrieve W1 and W2 from parameters### START CODE HERE ### (≈ 2 lines of code)W1 = parameters['W1']W2 = parameters['W2']### END CODE HERE #### 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 = -np.sum(logprobs) / m### END CODE HERE ###cost = np.squeeze(cost) # makes sure cost is the dimension we expect.# E.g., turns [[17]] into 17assert (isinstance(cost, float))return cost
我在完成这个的时候通过这个发现了一个前面犯的一个错误,程序一直警告logprobs和cost这两个参数运算的时候不可用,于是我怀疑是不是有小于零的参数存在式子中,最后发现,A2在前面的计算中我已开始用的tanh函数,和A1混啦,其实A2要用sigmoid函数,A1是tanh函数
OK,我们已经完成了cost函数的代码,我么来看看效果
下面是输出代码
#现在来检测下代价函数的计算
A2, Y_assess, parameters = compute_cost_test_case()
print("cost = " + str(compute_cost(A2, Y_assess, parameters)))
输出是这样
cost = 0.692919893776
- 难点来了,反向传播。(重点是32-37行,这是精髓)
#难点来了,反向传播
# 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 parameterscache -- 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 - YdW2 = np.dot(dZ2 , A1.T) / mdb2 = np.sum(dZ2 , axis = 1 , keepdims = True) / mdZ1 = np.dot(W2.T , dZ2) * (1 - A1**2)dW1 = np.dot(dZ1 , X.T) / mdb1 = np.sum(dZ1 , axis = 1 , keepdims = True) / m### END CODE HERE ###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]]
- 好了,反向传播页做完了,现在开始更新参数矩阵吧!!!
#反向传播完毕后,开始更新参数
# GRADED FUNCTION: update_parameters
def update_parameters(parameters, grads, learning_rate=1.2):"""Updates parameters using the gradient descent update rule given aboveArguments:parameters -- python dictionary containing your parametersgrads -- python dictionary containing your gradientsReturns: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 * dW1b1 = b1 - learning_rate * db1W2 = W2 - learning_rate * dW2b2 = b2 - learning_rate * db2### END CODE HERE ###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]]
ODK,各种功能函数终于可以说是写的差不多啦,现在来整合一个model函数吧
#好了,所有的函数都写完了,现在来整合一下,组成一个分类器模型
# 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 layernum_iterations -- Number of iterations in gradient descent loopprint_cost -- if True, print the cost every 1000 iterationsReturns: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)import pdbfor 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 iterationsif 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']))
上面设置的隐藏层是4个,迭代次数是10000
输出以下结果:
W1 = [[-4.18493855 5.33220875][-7.52989335 1.24306212][-4.19297397 5.32630669][ 7.52983568 -1.24309519]]
b1 = [[ 2.32926551][ 3.79459096][ 2.33002105][-3.79469147]]
W2 = [[-6033.83673001 -6008.12981298 -6033.1009627 6008.06639333]]
b2 = [[-52.66607002]]
最后,跑一下预测函数
#现在来写一写预测函数
# GRADED FUNCTION: predict
def predict(parameters, X):"""Using the learned parameters, predicts a class for each example in XArguments:parameters -- python dictionary containing your parametersX -- input data of size (n_x, m)Returnspredictions -- 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.array([0 if i <= 0.5 else 1 for i in np.squeeze(A2)])### END CODE HERE ###return predictions
看看预测值吧
#来看看预测值
parameters, X_assess = predict_test_case()
predictions = predict(parameters, X_assess)
print("predictions mean = " + str(np.mean(predictions)))
结果长这样:
predictions mean = 0.666666666667
最后,没有对比就没有伤害,,,来看看用这个模型训练的效果之前用单个logistic回归训练的效果的比较吧
#现在用刚才那个用单个逻辑回归只有百分之47的例子来训练
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))
pylab.show()
predictions=predict(parameters,X)
print ('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) + '%')
#可以看到,预测准确率达到了百分之89,
果然美滋滋,准确度达到了百分之九十,秒啊。上图
Cost after iteration 0: 0.693048
Cost after iteration 1000: 0.288083
Cost after iteration 2000: 0.254385
Cost after iteration 3000: 0.233864
Cost after iteration 4000: 0.226792
Cost after iteration 5000: 0.222644
Cost after iteration 6000: 0.219731
Cost after iteration 7000: 0.217504
Cost after iteration 8000: 0.219501
Cost after iteration 9000: 0.218620
Accuracy: 90%
另外,好像当隐藏层有5个神经元的时候,效果最好噢,大家可以自己试试的。
这篇关于deep_learning_week3_BP神经网络的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!