[关闭]
@Perfect-Demo 2018-05-01T08:41:51.000000Z 字数 12768 阅读 926

deep_learning_week3_BP神经网络

机器学习深度学习


代码已上传github:
https://github.com/PerfectDemoT/my_deeplearning_homework


这是吴恩达深度学习里的第二次作业

实现BP神经网络

  1. 首先先导入包
  1. #先导入包
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from testCases import *
  5. import sklearn
  6. import sklearn.datasets
  7. import sklearn.linear_model
  8. from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets
  9. import matplotlib.pyplot as plt
  10. import pylab
  1. 然后我们设置一个随机数种子备用,再导入数据,然后可视化一下(PS:这个不知道什么原因,显示不出来,虽然原来的代码有问题会报错,不过我看了库中函数的运行方式,将Y修改后不会报错了,但是还是显示不出,就很迷,不过对后面的结果没影响)
  1. np.random.seed(1) # set a seed so that the results are consistent
  2. #现在开始导入数据,一个X一个Y
  3. X, Y = load_planar_dataset()
  4. print (np.shape(X))
  5. print (np.shape(Y))
  6. #可知,这个X为一个包含400个具有两个参数样本的矩阵,Y为其标签
  7. #将数据可视化一下,看起来像一朵红花(很奇怪,我这里已开始运行不了,然后改正后不报错了,不过还是显示不出图片)
  8. plt.scatter(X[0, :], X[1, :], c=Y.reshape(X[0,:].shape), s=40, cmap=plt.cm.Spectral);

小红花
3. 现在,我们可以来处理这些数据了,比如,先看看这些矩阵的大小

  1. ### START CODE HERE ### (≈ 3 lines of code)
  2. shape_X = X.shape
  3. shape_Y = Y.shape
  4. m = X.shape[1] # training set size
  5. ### END CODE HERE ###
  6. print ('The shape of X is: ' + str(shape_X))
  7. print ('The shape of Y is: ' + str(shape_Y))
  8. print ('I have m = %d training examples!' % (m))
  1. 然后呢,老师贴心地给了训练好了的单个logistic分类器,我们可以试试
  1. # Train the logistic regression classifier(这里先用写好的分类器训练一下)
  2. clf = sklearn.linear_model.LogisticRegressionCV();
  3. clf.fit(X.T, Y.T);
  1. 但是呢,你会发现,这个的分类效果并不好,准确率只有百分之四十九
  1. # Plot the decision boundary for logistic regression
  2. plot_decision_boundary(lambda x: clf.predict(x), X, Y)
  3. plt.title("Logistic Regression")
  4. # Print accuracy,现在这里画出这些点的分类边界(好吧这里有点小问题,还是上面那个画图的问题,)
  5. LR_predictions = clf.predict(X.T)
  6. print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*100) +
  7. '% ' + "(percentage of correctly labelled datapoints)")
  8. #可以看出,这个线性分类器效果并不好,就算是训练集,准确率也很低所以这里就要用bp网络了
  1. #这是输出
  2. Accuracy of logistic regression: 47 % (percentage of correctly labelled datapoints)

现在开始真正的弄bp神经网络的各层啦

  1. 首先,我们设计一个定义网络结构的函数
  1. #首先定义各层网络的结构
  2. def layer_sizes(X, Y):
  3. """
  4. Arguments:
  5. X -- input dataset of shape (input size, number of examples)
  6. Y -- labels of shape (output size, number of examples)
  7. Returns:
  8. n_x -- the size of the input layer
  9. n_h -- the size of the hidden layer
  10. n_y -- the size of the output layer
  11. """
  12. ### START CODE HERE ### (≈ 3 lines of code)
  13. n_x = X.shape[0] # size of input layer
  14. n_h = 4
  15. n_y = Y.shape[0] # size of output layer
  16. ### END CODE HERE ###
  17. return (n_x, n_h, n_y)

返回的是X输入的参数个数,隐藏层的神经元个数,输出层神经元个数,现在我们来输出网络看一看

  1. #现在输出来看看我们的网络结构
  2. X_assess, Y_assess = layer_sizes_test_case() #这里是将数据导入
  3. (n_x, n_h, n_y) = layer_sizes(X_assess, Y_assess)
  4. print("The size of the input layer is: n_x = " + str(n_x))
  5. print("The size of the hidden layer is: n_h = " + str(n_h))
  6. print("The size of the output layer is: n_y = " + str(n_y))

输出是这样(就不截图了。。。)

  1. The size of the input layer is: n_x = 5
  2. The size of the hidden layer is: n_h = 4
  3. The size of the output layer is: n_y = 2

2 . 现在来初始化(函数里面本身就写了随机的种子,这里为2)

  1. #接下来是初始化函数
  2. # GRADED FUNCTION: initialize_parameters
  3. def initialize_parameters(n_x, n_h, n_y):
  4. """
  5. Argument:
  6. n_x -- size of the input layer
  7. n_h -- size of the hidden layer
  8. n_y -- size of the output layer
  9. Returns:
  10. params -- python dictionary containing your parameters:
  11. W1 -- weight matrix of shape (n_h, n_x)
  12. b1 -- bias vector of shape (n_h, 1)
  13. W2 -- weight matrix of shape (n_y, n_h)
  14. b2 -- bias vector of shape (n_y, 1)
  15. """
  16. np.random.seed(2) # we set up a seed so that your output matches ours although the initialization is random.
  17. ### START CODE HERE ### (≈ 4 lines of code)
  18. W1 = np.random.randn(n_h , n_x) * 0.01
  19. b1 = np.zeros((n_h , 1)) #记着这里是两个括号
  20. W2 = np.random.randn(n_y , n_h) * 0.01
  21. b2 = np.zeros((n_y , 1))
  22. ### END CODE HERE ###
  23. assert (W1.shape == (n_h, n_x))
  24. assert (b1.shape == (n_h, 1))
  25. assert (W2.shape == (n_y, n_h))
  26. assert (b2.shape == (n_y, 1))
  27. parameters = {"W1": W1,
  28. "b1": b1,
  29. "W2": W2,
  30. "b2": b2}
  31. return parameters

然后现在来看看初始化的样子
代码长这样:

  1. #现在可以看看初始化结构咋样
  2. n_x, n_h, n_y = initialize_parameters_test_case()
  3. parameters = initialize_parameters(n_x, n_h, n_y)
  4. print("W1 = " + str(parameters["W1"]))
  5. print("b1 = " + str(parameters["b1"]))
  6. print("W2 = " + str(parameters["W2"]))
  7. print("b2 = " + str(parameters["b2"]))

输出是

  1. W1 = [[-0.00416758 -0.00056267]
  2. [-0.02136196 0.01640271]
  3. [-0.01793436 -0.00841747]
  4. [ 0.00502881 -0.01245288]]
  5. b1 = [[ 0.]
  6. [ 0.]
  7. [ 0.]
  8. [ 0.]]
  9. W2 = [[-0.01057952 -0.00909008 0.00551454 0.02292208]]
  10. b2 = [[ 0.]]
  1. 前期准备算是做的差不多啦,现在开始正向传播啦
    先上公式:
    前向传播
    大家注意看23到26行,那里是正向传播的精髓之处
  1. #OK,现在开始正向传播啦
  2. # GRADED FUNCTION: forward_propagation​
  3. def forward_propagation(X, parameters):
  4. """
  5. Argument:
  6. X -- input data of size (n_x, m)
  7. parameters -- python dictionary containing your parameters (output of initialization function)
  8. Returns:
  9. A2 -- The sigmoid output of the second activation
  10. cache -- a dictionary containing "Z1", "A1", "Z2" and "A2"
  11. """
  12. # Retrieve each parameter from the dictionary "parameters"
  13. ### START CODE HERE ### (≈ 4 lines of code)
  14. W1 = parameters['W1']
  15. b1 = parameters['b1']
  16. W2 = parameters['W2']
  17. b2 = parameters['b2']
  18. ### END CODE HERE ###
  19. # Implement Forward Propagation to calculate A2 (probabilities)
  20. ### START CODE HERE ### (≈ 4 lines of code)
  21. Z1 = np.dot(W1 , X) + b1
  22. A1 = np.tanh(Z1)
  23. Z2 = np.dot(W2 , A1) + b2
  24. A2 = sigmoid(Z2)
  25. ### END CODE HERE ###
  26. assert (A2.shape == (1, X.shape[1]))
  27. cache = {"Z1": Z1,
  28. "A1": A1,
  29. "Z2": Z2,
  30. "A2": A2}
  31. return A2, cache

好了,正向传播完毕后,我们来看看结果,结果输出的代码如下:

  1. #现在来看看正向传播的结果
  2. X_assess, parameters = forward_propagation_test_case()
  3. A2, cache = forward_propagation(X_assess, parameters)
  4. # Note: we use the mean here just to make sure that your output matches ours.
  5. print(np.mean(cache['Z1']) ,np.mean(cache['A1']),np.mean(cache['Z2']),np.mean(cache['A2']))

然后,结果如下:

  1. -0.000499755777742 -0.000496963353232 0.000438187450959 0.500109546852
  1. 到了这里,我们可以来看看cost函数了,
    先看看公式:

下面是他的代码(重点关注28,29行)

  1. #现在来算算代价函数J
  2. #GRADED
  3. #FUNCTION: compute_cost
  4. def compute_cost(A2, Y, parameters):
  5. """
  6. Computes the cross-entropy cost given in equation (13)
  7. Arguments:
  8. A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
  9. Y -- "true" labels vector of shape (1, number of examples)
  10. parameters -- python dictionary containing your parameters W1, b1, W2 and b2
  11. Returns:
  12. cost -- cross-entropy cost given equation (13)
  13. """
  14. m = Y.shape[1] # number of example
  15. # Retrieve W1 and W2 from parameters
  16. ### START CODE HERE ### (≈ 2 lines of code)
  17. W1 = parameters['W1']
  18. W2 = parameters['W2']
  19. ### END CODE HERE ###
  20. # Compute the cross-entropy cost
  21. ### START CODE HERE ### (≈ 2 lines of code)
  22. logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), 1 - Y)
  23. cost = -np.sum(logprobs) / m
  24. ### END CODE HERE ###
  25. cost = np.squeeze(cost) # makes sure cost is the dimension we expect.
  26. # E.g., turns [[17]] into 17
  27. assert (isinstance(cost, float))
  28. return cost

我在完成这个的时候通过这个发现了一个前面犯的一个错误,程序一直警告logprobs和cost这两个参数运算的时候不可用,于是我怀疑是不是有小于零的参数存在式子中,最后发现,A2在前面的计算中我已开始用的tanh函数,和A1混啦,其实A2要用sigmoid函数,A1是tanh函数

OK,我们已经完成了cost函数的代码,我么来看看效果
下面是输出代码

  1. #现在来检测下代价函数的计算
  2. A2, Y_assess, parameters = compute_cost_test_case()
  3. print("cost = " + str(compute_cost(A2, Y_assess, parameters)))

输出是这样

  1. cost = 0.692919893776
  1. 难点来了,反向传播。(重点是32-37行,这是精髓)
  1. #难点来了,反向传播
  2. # GRADED FUNCTION: backward_propagation
  3. def backward_propagation(parameters, cache, X, Y):
  4. """
  5. Implement the backward propagation using the instructions above.
  6. Arguments:
  7. parameters -- python dictionary containing our parameters
  8. cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
  9. X -- input data of shape (2, number of examples)
  10. Y -- "true" labels vector of shape (1, number of examples)
  11. Returns:
  12. grads -- python dictionary containing your gradients with respect to different parameters
  13. """
  14. m = X.shape[1]
  15. # First, retrieve W1 and W2 from the dictionary "parameters".
  16. ### START CODE HERE ### (≈ 2 lines of code)
  17. W1 = parameters['W1']
  18. W2 = parameters['W2']
  19. ### END CODE HERE ###
  20. # Retrieve also A1 and A2 from dictionary "cache".
  21. ### START CODE HERE ### (≈ 2 lines of code)
  22. A1 = cache['A1']
  23. A2 = cache['A2']
  24. ### END CODE HERE ###
  25. # Backward propagation: calculate dW1, db1, dW2, db2.
  26. ### START CODE HERE ### (≈ 6 lines of code, corresponding to 6 equations on slide above)
  27. dZ2 = A2 - Y
  28. dW2 = np.dot(dZ2 , A1.T) / m
  29. db2 = np.sum(dZ2 , axis = 1 , keepdims = True) / m
  30. dZ1 = np.dot(W2.T , dZ2) * (1 - A1**2)
  31. dW1 = np.dot(dZ1 , X.T) / m
  32. db1 = np.sum(dZ1 , axis = 1 , keepdims = True) / m
  33. ### END CODE HERE ###
  34. grads = {"dW1": dW1,
  35. "db1": db1,
  36. "dW2": dW2,
  37. "db2": db2}
  38. return grads

对于此,我们完成了反向传播,
现在来看看输出代码

  1. #反向传播完毕,我们来看看
  2. parameters, cache, X_assess, Y_assess = backward_propagation_test_case()
  3. grads = backward_propagation(parameters, cache, X_assess, Y_assess)
  4. print ("dW1 = "+ str(grads["dW1"]))
  5. print ("db1 = "+ str(grads["db1"]))
  6. print ("dW2 = "+ str(grads["dW2"]))
  7. print ("db2 = "+ str(grads["db2"]))

输出是这样的

  1. dW1 = [[ 0.01018708 -0.00708701]
  2. [ 0.00873447 -0.0060768 ]
  3. [-0.00530847 0.00369379]
  4. [-0.02206365 0.01535126]]
  5. db1 = [[-0.00069728]
  6. [-0.00060606]
  7. [ 0.000364 ]
  8. [ 0.00151207]]
  9. dW2 = [[ 0.00363613 0.03153604 0.01162914 -0.01318316]]
  10. db2 = [[ 0.06589489]]
  1. 好了,反向传播页做完了,现在开始更新参数矩阵吧!!!
  1. #反向传播完毕后,开始更新参数
  2. # GRADED FUNCTION: update_parameters​
  3. def update_parameters(parameters, grads, learning_rate=1.2):
  4. """
  5. Updates parameters using the gradient descent update rule given above
  6. Arguments:
  7. parameters -- python dictionary containing your parameters
  8. grads -- python dictionary containing your gradients
  9. Returns:
  10. parameters -- python dictionary containing your updated parameters
  11. """
  12. # Retrieve each parameter from the dictionary "parameters"
  13. ### START CODE HERE ### (≈ 4 lines of code)
  14. W1 = parameters['W1']
  15. b1 = parameters['b1']
  16. W2 = parameters['W2']
  17. b2 = parameters['b2']
  18. ### END CODE HERE ###
  19. # Retrieve each gradient from the dictionary "grads"
  20. ### START CODE HERE ### (≈ 4 lines of code)
  21. dW1 = grads['dW1']
  22. db1 = grads['db1']
  23. dW2 = grads['dW2']
  24. db2 = grads['db2']
  25. ## END CODE HERE ###
  26. # Update rule for each parameter
  27. ### START CODE HERE ### (≈ 4 lines of code)
  28. W1 = W1 - learning_rate * dW1
  29. b1 = b1 - learning_rate * db1
  30. W2 = W2 - learning_rate * dW2
  31. b2 = b2 - learning_rate * db2
  32. ### END CODE HERE ###
  33. parameters = {"W1": W1,
  34. "b1": b1,
  35. "W2": W2,
  36. "b2": b2}
  37. return parameters

老规矩,跑一跑(代码如下)

  1. #现在验证一下反向传播算法的参数更新
  2. parameters, grads = update_parameters_test_case()
  3. parameters = update_parameters(parameters, grads)
  4. print("W1 = " + str(parameters["W1"]))
  5. print("b1 = " + str(parameters["b1"]))
  6. print("W2 = " + str(parameters["W2"]))
  7. print("b2 = " + str(parameters["b2"]))

结果长这样:

  1. W1 = [[-0.00643025 0.01936718]
  2. [-0.02410458 0.03978052]
  3. [-0.01653973 -0.02096177]
  4. [ 0.01046864 -0.05990141]]
  5. b1 = [[ -1.02420756e-06]
  6. [ 1.27373948e-05]
  7. [ 8.32996807e-07]
  8. [ -3.20136836e-06]]
  9. W2 = [[-0.01041081 -0.04463285 0.01758031 0.04747113]]
  10. b2 = [[ 0.00010457]]

ODK,各种功能函数终于可以说是写的差不多啦,现在来整合一个model函数吧

  1. #好了,所有的函数都写完了,现在来整合一下,组成一个分类器模型
  2. # GRADED FUNCTION: nn_model​
  3. def nn_model(X, Y, n_h, num_iterations=10000, print_cost=False):
  4. """
  5. Arguments:
  6. X -- dataset of shape (2, number of examples)
  7. Y -- labels of shape (1, number of examples)
  8. n_h -- size of the hidden layer
  9. num_iterations -- Number of iterations in gradient descent loop
  10. print_cost -- if True, print the cost every 1000 iterations
  11. Returns:
  12. parameters -- parameters learnt by the model. They can then be used to predict.
  13. """
  14. np.random.seed(3)
  15. n_x = layer_sizes(X, Y)[0]
  16. n_y = layer_sizes(X, Y)[2]
  17. # Initialize parameters, then retrieve W1, b1, W2, b2. Inputs: "n_x, n_h, n_y". Outputs = "W1, b1, W2, b2, parameters".
  18. ### START CODE HERE ### (≈ 5 lines of code)
  19. parameters = initialize_parameters(n_x , n_h , n_y)
  20. W1 = parameters['W1']
  21. b1 = parameters['b1']
  22. W2 = parameters['W2']
  23. b2 = parameters['b2']
  24. ### END CODE HERE ###
  25. # Loop (gradient descent)
  26. import pdb
  27. for i in range(0, num_iterations):
  28. ### START CODE HERE ### (≈ 4 lines of code)
  29. # Forward propagation. Inputs: "X, parameters". Outputs: "A2, cache".
  30. A2, cache = forward_propagation(X , parameters)
  31. # Cost function. Inputs: "A2, Y, parameters". Outputs: "cost".
  32. cost = compute_cost(A2 , Y , parameters)
  33. # Backpropagation. Inputs: "parameters, cache, X, Y". Outputs: "grads".
  34. grads = backward_propagation(parameters, cache, X, Y)
  35. # Gradient descent parameter update. Inputs: "parameters, grads". Outputs: "parameters".
  36. parameters = update_parameters(parameters, grads)
  37. ### END CODE HERE ###
  38. # Print the cost every 1000 iterations
  39. if print_cost and i % 1000 == 0:
  40. print ("Cost after iteration %i: %f" % (i, cost))
  41. return parameters

接着,调用一下这个函数,看看效果,还不是美滋滋(调用代码如下)

  1. #现在我们来跑一跑这个模型
  2. X_assess, Y_assess = nn_model_test_case()
  3. parameters = nn_model(X_assess, Y_assess, 4, num_iterations=10000, print_cost=False)
  4. print("W1 = " + str(parameters['W1']))
  5. print("b1 = " + str(parameters['b1']))
  6. print("W2 = " + str(parameters['W2']))
  7. print("b2 = " + str(parameters['b2']))

上面设置的隐藏层是4个,迭代次数是10000
输出以下结果:

  1. W1 = [[-4.18493855 5.33220875]
  2. [-7.52989335 1.24306212]
  3. [-4.19297397 5.32630669]
  4. [ 7.52983568 -1.24309519]]
  5. b1 = [[ 2.32926551]
  6. [ 3.79459096]
  7. [ 2.33002105]
  8. [-3.79469147]]
  9. W2 = [[-6033.83673001 -6008.12981298 -6033.1009627 6008.06639333]]
  10. b2 = [[-52.66607002]]

最后,跑一下预测函数

  1. #现在来写一写预测函数
  2. # GRADED FUNCTION: predict
  3. def predict(parameters, X):
  4. """
  5. Using the learned parameters, predicts a class for each example in X
  6. Arguments:
  7. parameters -- python dictionary containing your parameters
  8. X -- input data of size (n_x, m)
  9. Returns
  10. predictions -- vector of predictions of our model (red: 0 / blue: 1)
  11. """
  12. # Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold.
  13. ### START CODE HERE ### (≈ 2 lines of code)
  14. A2, cache = forward_propagation(X , parameters)
  15. predictions = np.array([0 if i <= 0.5 else 1 for i in np.squeeze(A2)])
  16. ### END CODE HERE ###
  17. return predictions

看看预测值吧

  1. #来看看预测值
  2. parameters, X_assess = predict_test_case()
  3. predictions = predict(parameters, X_assess)
  4. print("predictions mean = " + str(np.mean(predictions)))

结果长这样:

  1. predictions mean = 0.666666666667

最后,没有对比就没有伤害,,,来看看用这个模型训练的效果之前用单个logistic回归训练的效果的比较吧

  1. #现在用刚才那个用单个逻辑回归只有百分之47的例子来训练
  2. parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)
  3. # Plot the decision boundary
  4. plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
  5. plt.title("Decision Boundary for hidden layer size " + str(4))
  6. pylab.show()
  7. predictions=predict(parameters,X)
  8. print ('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) + '%')
  9. #可以看到,预测准确率达到了百分之89,

果然美滋滋,准确度达到了百分之九十,秒啊。上图

  1. Cost after iteration 0: 0.693048
  2. Cost after iteration 1000: 0.288083
  3. Cost after iteration 2000: 0.254385
  4. Cost after iteration 3000: 0.233864
  5. Cost after iteration 4000: 0.226792
  6. Cost after iteration 5000: 0.222644
  7. Cost after iteration 6000: 0.219731
  8. Cost after iteration 7000: 0.217504
  9. Cost after iteration 8000: 0.219501
  10. Cost after iteration 9000: 0.218620
  11. Accuracy: 90%

训练后图片

另外,好像当隐藏层有5个神经元的时候,效果最好噢,大家可以自己试试的。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注