[关闭]
@Perfect-Demo 2018-05-01T08:42:42.000000Z 字数 20161 阅读 1296

deep_learning_month2_week1

机器学习深度学习

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


这是一个包含三个优化方案的作业文案,包括:参数初始化,正则化,梯度检验。下面将一个个实现。


1. 参数初始化

说明:我们目前其实已经知道了,对于一个神经网络,参数W , b是随机初始化的(尤其是我们一般都已经了解,是绝对不能简单地将其初始化为0的),下面我们将分别对比:初始化为0 , 随机初始化 , "He"初始化

在此之前,我们先写一下他们共同要用到的

  1. #先导入包
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import sklearn
  5. import sklearn.datasets
  6. from init_utils import sigmoid, relu, compute_loss, forward_propagation, backward_propagation
  7. from init_utils import update_parameters, predict, load_dataset, plot_decision_boundary, predict_dec
  8. #%matplotlib inline
  9. plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
  10. plt.rcParams['image.interpolation'] = 'nearest'
  11. plt.rcParams['image.cmap'] = 'gray'
  12. # load image dataset: blue/red dots in circles
  13. #导入数据
  14. train_X, train_Y, test_X, test_Y = load_dataset()

然后是公用的model函数

  1. def model(X, Y, learning_rate=0.01, num_iterations=15000, print_cost=True, initialization="he"):
  2. """
  3. Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.
  4. Arguments:
  5. X -- input data, of shape (2, number of examples)
  6. Y -- true "label" vector (containing 0 for red dots; 1 for blue dots), of shape (1, number of examples)
  7. learning_rate -- learning rate for gradient descent
  8. num_iterations -- number of iterations to run gradient descent
  9. print_cost -- if True, print the cost every 1000 iterations
  10. initialization -- flag to choose which initialization to use ("zeros","random" or "he")
  11. Returns:
  12. parameters -- parameters learnt by the model
  13. """
  14. grads = {}
  15. costs = [] # to keep track of the loss
  16. m = X.shape[1] # number of examples
  17. layers_dims = [X.shape[0], 10, 5, 1]
  18. # Initialize parameters dictionary.
  19. if initialization == "zeros":
  20. parameters = initialize_parameters_zeros(layers_dims)
  21. elif initialization == "random":
  22. parameters = initialize_parameters_random(layers_dims)
  23. elif initialization == "he":
  24. parameters = initialize_parameters_he(layers_dims)
  25. # Loop (gradient descent)
  26. for i in range(0, num_iterations):
  27. # Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID.
  28. a3, cache = forward_propagation(X, parameters)
  29. # Loss
  30. cost = compute_loss(a3, Y)
  31. # Backward propagation.
  32. grads = backward_propagation(X, Y, cache)
  33. # Update parameters.
  34. parameters = update_parameters(parameters, grads, learning_rate)
  35. # Print the loss every 1000 iterations
  36. if print_cost and i % 1000 == 0:
  37. print("Cost after iteration {}: {}".format(i, cost))
  38. costs.append(cost)
  39. # plot the loss
  40. plt.plot(costs)
  41. plt.ylabel('cost')
  42. plt.xlabel('iterations (per hundreds)')
  43. plt.title("Learning rate =" + str(learning_rate))
  44. plt.show()
  45. return parameters

1.先看初始化为0.

就是把所有函数初始化为0,话不多说,原理很简单,上代码

  1. #首先来写吧所有变量初始值为0的函数
  2. # GRADED FUNCTION: initialize_parameters_zeros
  3. def initialize_parameters_zeros(layers_dims):
  4. """
  5. Arguments:
  6. layer_dims -- python array (list) containing the size of each layer.
  7. Returns:
  8. parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
  9. W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
  10. b1 -- bias vector of shape (layers_dims[1], 1)
  11. ...
  12. WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
  13. bL -- bias vector of shape (layers_dims[L], 1)
  14. """
  15. parameters = {}
  16. L = len(layers_dims) # number of layers in the network
  17. for l in range(1, L):
  18. ### START CODE HERE ### (≈ 2 lines of code)
  19. parameters['W' + str(l)] = np.zeros((layers_dims[l] , layers_dims[l-1]))
  20. parameters['b' + str(l)] = np.zeros((layers_dims[l], 1))
  21. ### END CODE HERE ###
  22. return parameters

调用会发现全是0,,,这里就不赘述了。

然后用model函数跑一下。。。发现没有任何训练效果

  1. #下面用model函数跑一下
  2. parameters = model(train_X, train_Y, initialization = "zeros")
  3. print ("On the train set:")
  4. predictions_train = predict(train_X, train_Y, parameters)
  5. print ("On the test set:")
  6. predictions_test = predict(test_X, test_Y, parameters)
  7. #可以看到,cost函数没有一点点下降,是平的,可以说是小狗相当差,
  8. #所以神经网络的参数不能初始化为0(这在机器学习力已经讲了,可以去看看手稿笔记)
  9. print("==================================")
  10. #输出一下对于训练集和测试集的预测
  11. print ("predictions_train = " + str(predictions_train))
  12. print ("predictions_test = " + str(predictions_test))
  13. #发现全是0
  14. print("===========================")
  15. #我们再来看看边界
  16. plt.title("Model with Zeros initialization")
  17. axes = plt.gca()
  18. axes.set_xlim([-1.5,1.5])
  19. axes.set_ylim([-1.5,1.5])
  20. plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
  21. #发现并没有边界
  22. print("=============================")

结果是这样就是上面注释写的那样
下面是图片:
cost值没有一点下降

没有边界

2. 现在看看随机初始化

  1. #下面看看随机初始化(也就是我们平常用的那一种)
  2. # GRADED FUNCTION: initialize_parameters_random
  3. def initialize_parameters_random(layers_dims):
  4. """
  5. Arguments:
  6. layer_dims -- python array (list) containing the size of each layer.
  7. Returns:
  8. parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
  9. W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
  10. b1 -- bias vector of shape (layers_dims[1], 1)
  11. ...
  12. WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
  13. bL -- bias vector of shape (layers_dims[L], 1)
  14. """
  15. np.random.seed(3) # This seed makes sure your "random" numbers will be the as ours
  16. parameters = {}
  17. L = len(layers_dims) # integer representing the number of layers
  18. for l in range(1, L):
  19. ### START CODE HERE ### (≈ 2 lines of code)
  20. parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l - 1]) * 10
  21. parameters['b' + str(l)] = np.zeros((layers_dims[l], 1))
  22. ### END CODE HERE ###
  23. return parameters

我们之前就讲过很多次随机初始化的例子,此不赘述
看看训练结果的检验

  1. #输出看看效果
  2. parameters = initialize_parameters_random([3, 2, 1])
  3. print("W1 = " + str(parameters["W1"]))
  4. print("b1 = " + str(parameters["b1"]))
  5. print("W2 = " + str(parameters["W2"]))
  6. print("b2 = " + str(parameters["b2"]))
  7. #用model函数跑一下
  8. parameters = model(train_X, train_Y, initialization = "random")
  9. print ("On the train set:")
  10. predictions_train = predict(train_X, train_Y, parameters)
  11. print ("On the test set:")
  12. predictions_test = predict(test_X, test_Y, parameters)
  13. print("==================================")
  14. #输出一下预测
  15. print (predictions_train)
  16. print (predictions_test)
  17. print("=================================")
  18. #看看边界
  19. plt.title("Model with large random initialization")
  20. axes = plt.gca()
  21. axes.set_xlim([-1.5,1.5])
  22. axes.set_ylim([-1.5,1.5])
  23. plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
  24. print("=======================================")
  25. #我只能说,这个效果比上面那个好多了,并且是预料之中(之前都是用的这个嘛)

下面看看其cost曲线以及分类边界
cost
doundary

3. 现在来看看之前从没见过的"He"初始化方法

该方法的公式是:

  1. #最后来看看一个奇妙的方法(貌似是2015年的一片论文中的)
  2. # He初始方法
  3. # GRADED FUNCTION: initialize_parameters_he
  4. def initialize_parameters_he(layers_dims):
  5. """
  6. Arguments:
  7. layer_dims -- python array (list) containing the size of each layer.
  8. Returns:
  9. parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
  10. W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
  11. b1 -- bias vector of shape (layers_dims[1], 1)
  12. ...
  13. WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
  14. bL -- bias vector of shape (layers_dims[L], 1)
  15. """
  16. np.random.seed(3)
  17. parameters = {}
  18. L = len(layers_dims) - 1 # integer representing the number of layers
  19. for l in range(1, L + 1):
  20. ### START CODE HERE ### (≈ 2 lines of code)
  21. parameters['W' + str(l)] = np.random.randn(layers_dims[l] , layers_dims[l-1]) * np.sqrt(2/layers_dims[l - 1])
  22. parameters['b' + str(l)] = np.zeros((layers_dims[l] , 1))
  23. ### END CODE HERE ###
  24. return parameters

我们来看看效果

  1. #输出一下参数看看效果
  2. parameters = initialize_parameters_he([2, 4, 1])
  3. print("W1 = " + str(parameters["W1"]))
  4. print("b1 = " + str(parameters["b1"]))
  5. print("W2 = " + str(parameters["W2"]))
  6. print("b2 = " + str(parameters["b2"]))
  7. print("==============================")

输出长这样

  1. W1 = [[ 1.78862847 0.43650985]
  2. [ 0.09649747 -1.8634927 ]
  3. [-0.2773882 -0.35475898]
  4. [-0.08274148 -0.62700068]]
  5. b1 = [[ 0.]
  6. [ 0.]
  7. [ 0.]
  8. [ 0.]]
  9. W2 = [[-0.03098412 -0.33744411 -0.92904268 0.62552248]]
  10. b2 = [[ 0.]]

然后现在来输出一下训练效果看看。

  1. #用model函数调用一下,看看那cost函数下降
  2. parameters = model(train_X, train_Y, initialization = "he")
  3. print ("On the train set:")
  4. predictions_train = predict(train_X, train_Y, parameters)
  5. print ("On the test set:")
  6. predictions_test = predict(test_X, test_Y, parameters)
  7. print("====================================")
  8. #看看边界
  9. plt.title("Model with He initialization")
  10. axes = plt.gca()
  11. axes.set_xlim([-1.5,1.5])
  12. axes.set_ylim([-1.5,1.5])
  13. plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
  14. #效果也很好,可以说和第二个随机初始化的效果一样

看看长这样

  1. Cost after iteration 0: 0.8830537463419761
  2. Cost after iteration 1000: 0.6879825919728063
  3. Cost after iteration 2000: 0.6751286264523371
  4. Cost after iteration 3000: 0.6526117768893807
  5. Cost after iteration 4000: 0.6082958970572937
  6. Cost after iteration 5000: 0.5304944491717495
  7. Cost after iteration 6000: 0.4138645817071793
  8. Cost after iteration 7000: 0.3117803464844441
  9. Cost after iteration 8000: 0.23696215330322556
  10. Cost after iteration 9000: 0.18597287209206828
  11. Cost after iteration 10000: 0.15015556280371808
  12. Cost after iteration 11000: 0.12325079292273548
  13. Cost after iteration 12000: 0.09917746546525937
  14. Cost after iteration 13000: 0.08457055954024274
  15. Cost after iteration 14000: 0.07357895962677366

看看图片
cost
cost
这个边界拟合,,,真的是秒啊,,,(虽然应该是过拟合了,不过这里也没有进行正则化,没啥,不慌)


2. 正则化

1. 老样子,先导入包和数据,然后写一个model

  1. #老样子,先导入包
  2. # import packages
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec
  6. from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
  7. import sklearn
  8. import sklearn.datasets
  9. import scipy.io
  10. from testCases import *
  11. #%matplotlib inline
  12. plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
  13. plt.rcParams['image.interpolation'] = 'nearest'
  14. plt.rcParams['image.cmap'] = 'gray'
  15. #导入数据
  16. train_X, train_Y, test_X, test_Y = load_2D_dataset()

然后model函数:

  1. #下面我们来训练一个没有正则化过的模型(其实就是和之前做过的那种一样)
  2. def model(X, Y, learning_rate=0.3, num_iterations=30000, print_cost=True, lambd=0, keep_prob=1):
  3. """
  4. Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.
  5. Arguments:
  6. X -- input data, of shape (input size, number of examples)
  7. Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (output size, number of examples)
  8. learning_rate -- learning rate of the optimization
  9. num_iterations -- number of iterations of the optimization loop
  10. print_cost -- If True, print the cost every 10000 iterations
  11. lambd -- regularization hyperparameter, scalar
  12. keep_prob - probability of keeping a neuron active during drop-out, scalar.
  13. Returns:
  14. parameters -- parameters learned by the model. They can then be used to predict.
  15. """
  16. grads = {}
  17. costs = [] # to keep track of the cost
  18. m = X.shape[1] # number of examples
  19. layers_dims = [X.shape[0], 20, 3, 1]
  20. # Initialize parameters dictionary.
  21. parameters = initialize_parameters(layers_dims)
  22. # Loop (gradient descent)
  23. for i in range(0, num_iterations):
  24. # Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID.
  25. if keep_prob == 1:
  26. a3, cache = forward_propagation(X, parameters)
  27. elif keep_prob < 1:
  28. a3, cache = forward_propagation_with_dropout(X, parameters, keep_prob)
  29. # Cost function
  30. if lambd == 0:
  31. cost = compute_cost(a3, Y)
  32. else:
  33. cost = compute_cost_with_regularization(a3, Y, parameters, lambd)
  34. # Backward propagation.
  35. assert (lambd == 0 or keep_prob == 1) # it is possible to use both L2 regularization and dropout,
  36. # but this assignment will only explore one at a time
  37. if lambd == 0 and keep_prob == 1:
  38. grads = backward_propagation(X, Y, cache)
  39. elif lambd != 0:
  40. grads = backward_propagation_with_regularization(X, Y, cache, lambd)
  41. elif keep_prob < 1:
  42. grads = backward_propagation_with_dropout(X, Y, cache, keep_prob)
  43. # Update parameters.
  44. parameters = update_parameters(parameters, grads, learning_rate)
  45. # Print the loss every 10000 iterations
  46. if print_cost and i % 10000 == 0:
  47. print("Cost after iteration {}: {}".format(i, cost))
  48. if print_cost and i % 1000 == 0:
  49. costs.append(cost)
  50. # plot the cost
  51. plt.plot(costs)
  52. plt.ylabel('cost')
  53. plt.xlabel('iterations (x1,000)')
  54. plt.title("Learning rate =" + str(learning_rate))
  55. plt.show()
  56. return parameters

2. 注意,上面这个model函数用的各个函数,都没有进行正则化,我们现在来看看没有正则化的效果

  1. #现在来输出检测一下,看看准确率:
  2. parameters = model(train_X, train_Y)
  3. print ("On the training set:")
  4. predictions_train = predict(train_X, train_Y, parameters)
  5. print ("On the test set:")
  6. predictions_test = predict(test_X, test_Y, parameters)
  7. #你会发现效果还不错(至少不算差)
  8. # On the training set:
  9. # Accuracy: 0.947867298578
  10. # On the test set:
  11. # Accuracy: 0.915
  12. print("=============================================")
  13. #下面来用图看看边界
  14. plt.title("Model without regularization")
  15. axes = plt.gca()
  16. axes.set_xlim([-0.75,0.40])
  17. axes.set_ylim([-0.75,0.65])
  18. plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
  19. #由图中可以看出,显然overfitting啦。所以,需要正则化

然后我们现在来看看cost曲线以及分类边界图
cost
boundary
训练集和测试集的准确度分别变为

  1. On the training set:
  2. Accuracy: 0.947867298578
  3. On the test set:
  4. Accuracy: 0.915
  5. 并且可以说是显然的overfitting

3. L2方式的正则化

1. 现在开始进行cost的正则化
  1. #下面先来看看cost函数的正则化
  2. # GRADED FUNCTION: compute_cost_with_regularization
  3. def compute_cost_with_regularization(A3, Y, parameters, lambd):
  4. """
  5. Implement the cost function with L2 regularization. See formula (2) above.
  6. Arguments:
  7. A3 -- post-activation, output of forward propagation, of shape (output size, number of examples)
  8. Y -- "true" labels vector, of shape (output size, number of examples)
  9. parameters -- python dictionary containing parameters of the model
  10. Returns:
  11. cost - value of the regularized loss function (formula (2))
  12. """
  13. m = Y.shape[1]
  14. W1 = parameters["W1"]
  15. W2 = parameters["W2"]
  16. W3 = parameters["W3"]
  17. cross_entropy_cost = compute_cost(A3, Y) # This gives you the cross-entropy part of the cost
  18. #上一行的到了未正则化的cost函数
  19. ### START CODE HERE ### (approx. 1 line)
  20. L2_regularization_cost = (np.sum(np.square(W1)) + np.sum(np.square(W2)) + np.sum(np.square(W3))) * lambd / (2 * m)
  21. ### END CODER HERE ###
  22. cost = cross_entropy_cost + L2_regularization_cost #把未正则化的cost和正则化项加起来
  23. return cost

可看到,主要的正则化步骤,其实是23行的,对于23行,这个公式为:

我们现在输出检测一下

  1. cost = 1.78648594516
2. 现在开始看看反向传播的函数了
  1. #改变了cost函数,现在开始当然要开始改变梯度下降函数啦
  2. def backward_propagation_with_regularization(X, Y, cache, lambd):
  3. """
  4. Implements the backward propagation of our baseline model to which we added an L2 regularization.
  5. Arguments:
  6. X -- input dataset, of shape (input size, number of examples)
  7. Y -- "true" labels vector, of shape (output size, number of examples)
  8. cache -- cache output from forward_propagation()
  9. lambd -- regularization hyperparameter, scalar
  10. Returns:
  11. gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables
  12. """
  13. m = X.shape[1]
  14. (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache #把各个值从cache取出,以便后面的函数使用(因为当时我们的函数设置的就是这样)
  15. dZ3 = A3 - Y
  16. ### START CODE HERE ### (approx. 1 line)
  17. dW3 = 1. / m * np.dot(dZ3, A2.T) + (lambd / m) * W3
  18. ### END CODE HERE ###
  19. db3 = 1. / m * np.sum(dZ3, axis=1, keepdims=True)
  20. dA2 = np.dot(W3.T, dZ3)
  21. dZ2 = np.multiply(dA2, np.int64(A2 > 0))
  22. ### START CODE HERE ### (approx. 1 line)
  23. dW2 = 1. / m * np.dot(dZ2, A1.T) + (lambd / m) * W2
  24. ### END CODE HERE ###
  25. db2 = 1. / m * np.sum(dZ2, axis=1, keepdims=True)
  26. dA1 = np.dot(W2.T, dZ2)
  27. dZ1 = np.multiply(dA1, np.int64(A1 > 0))
  28. ### START CODE HERE ### (approx. 1 line)
  29. dW1 = 1. / m * np.dot(dZ1, X.T) + (lambd / m) * W1
  30. ### END CODE HERE ###
  31. db1 = 1. / m * np.sum(dZ1, axis=1, keepdims=True)
  32. gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3, "dA2": dA2,
  33. "dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1,
  34. "dZ1": dZ1, "dW1": dW1, "db1": db1}
  35. return gradients

现在看看输出的效果

  1. #现在开始输出看看效果
  2. X_assess, Y_assess, cache = backward_propagation_with_regularization_test_case()
  3. grads = backward_propagation_with_regularization(X_assess, Y_assess, cache, lambd = 0.7)
  4. print ("dW1 = "+ str(grads["dW1"]))
  5. print ("dW2 = "+ str(grads["dW2"]))
  6. print ("dW3 = "+ str(grads["dW3"]))
  1. dW1 = [[-0.25604646 0.12298827 -0.28297129]
  2. [-0.17706303 0.34536094 -0.4410571 ]]
  3. dW2 = [[ 0.79276486 0.85133918]
  4. [-0.0957219 -0.01720463]
  5. [-0.13100772 -0.03750433]]
  6. dW3 = [[-1.77691347 -0.11832879 -0.09397446]]

然后现在用同样的数据跑一边(这次进行了正则化)

  1. #我们现在在跑一下那个之前没有正则化的模型看看效果
  2. parameters = model(train_X, train_Y, lambd = 0.7)
  3. print ("On the train set:")
  4. predictions_train = predict(train_X, train_Y, parameters)
  5. print ("On the test set:")
  6. predictions_test = predict(test_X, test_Y, parameters)
  7. print("===============================")
  8. # On the train set:
  9. # Accuracy: 0.938388625592
  10. # On the test set:
  11. # Accuracy: 0.93
  12. #果然,训练集误差上升了,但是测试集误差下降了,这就是效果
  13. #现在来看看这个边界现在是怎么样的
  14. plt.title("Model with L2-regularization")
  15. axes = plt.gca()
  16. axes.set_xlim([-0.75,0.40])
  17. axes.set_ylim([-0.75,0.65])
  18. plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
  19. #果然,没有之前的那样明显的overfitting

输出是这样

  1. Cost after iteration 0: 0.6974484493131264
  2. Cost after iteration 10000: 0.2684918873282239
  3. Cost after iteration 20000: 0.268091633712730

然后cost图:
cost

边界图:
boundary
可以看到,之前的overfitting可以说是没有了,效果还是不错的
对于训练集和测试集的准确率如下:
On the train set:
Accuracy: 0.938388625592
On the test set:
Accuracy: 0.93

4.dropout方法的正则化

说明:对于dropout方法的正则化,其实就是随机一些矩阵记作D,然后设置一个阈值,大于的就是1,小于的就是0,所以最后得到一些0,1矩阵,然后这些矩阵的规模应该和神经网络节点的每层规模一模一样。之后对于每一个神经网络节点,与之对应的D如果为0,则相当于去掉该神经网络节点,等于1则保留。
下面看代码:

1. 前向传播以及D矩阵的形成
  1. #下面来看看在前传播中使用dropout方法的正则化
  2. # GRADED FUNCTION: forward_propagation_with_dropout
  3. def forward_propagation_with_dropout(X, parameters, keep_prob=0.5):
  4. """
  5. Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.
  6. Arguments:
  7. X -- input dataset, of shape (2, number of examples)
  8. parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":
  9. W1 -- weight matrix of shape (20, 2)
  10. b1 -- bias vector of shape (20, 1)
  11. W2 -- weight matrix of shape (3, 20)
  12. b2 -- bias vector of shape (3, 1)
  13. W3 -- weight matrix of shape (1, 3)
  14. b3 -- bias vector of shape (1, 1)
  15. keep_prob - probability of keeping a neuron active during drop-out, scalar
  16. Returns:
  17. A3 -- last activation value, output of the forward propagation, of shape (1,1)
  18. cache -- tuple, information stored for computing the backward propagation
  19. """
  20. np.random.seed(1) #设置一下随机种子
  21. # retrieve parameters
  22. W1 = parameters["W1"]
  23. b1 = parameters["b1"]
  24. W2 = parameters["W2"]
  25. b2 = parameters["b2"]
  26. W3 = parameters["W3"]
  27. b3 = parameters["b3"]
  28. # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID
  29. Z1 = np.dot(W1, X) + b1
  30. A1 = relu(Z1)
  31. ### START CODE HERE ### (approx. 4 lines) # Steps 1-4 below correspond to the Steps 1-4 described above.
  32. D1 = np.random.rand(A1.shape[0] , A1.shape[1]) # Step 1: initialize matrix D1 = np.random.rand(..., ...)
  33. D1 = np.where(D1 <= keep_prob, 1, 0) # Step 2: convert entries of D1 to 0 or 1 (using keep_prob as the threshold)
  34. A1 = A1 * D1 # 或者直接 A1 = A1 * D1 # # Step 3: shut down some neurons of A1
  35. A1 = A1 / keep_prob # Step 4: scale the value of neurons that haven't been shut down
  36. ### END CODE HERE ###
  37. Z2 = np.dot(W2, A1) + b2
  38. A2 = relu(Z2)
  39. ### START CODE HERE ### (approx. 4 lines)
  40. D2 = np.random.rand(A2.shape[0] , A2.shape[1]) # Step 1: initialize matrix D2 = np.random.rand(..., ...)
  41. D2 = np.where(D2 <= keep_prob , 1 , 0) # Step 2: convert entries of D2 to 0 or 1 (using keep_prob as the threshold)
  42. A2 = A2 * D2 # Step 3: shut down some neurons of A2
  43. A2 = A2 / keep_prob # Step 4: scale the value of neurons that haven't been shut down
  44. ### END CODE HERE ###
  45. Z3 = np.dot(W3, A2) + b3
  46. A3 = sigmoid(Z3)
  47. cache = (Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3)
  48. return A3, cache

注意第40行,那里作除法是为了

现在我们试试看效果

  1. #现在我们来输出一下
  2. X_assess, parameters = forward_propagation_with_dropout_test_case()
  3. A3, cache = forward_propagation_with_dropout(X_assess, parameters, keep_prob = 0.7)
  4. print ("A3 = " + str(A3))
  5. print("===========================")

输出为:

  1. A3 = [[ 0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]]
2. 反向传播

接下来看看dropout的反向传播,并且记住,在反向传播的时候,关闭的结点必须和前向传播时一样,并且也需要在后面dA /= keep_prob
下面看代码

  1. # GRADED FUNCTION: backward_propagation_with_dropout
  2. def backward_propagation_with_dropout(X, Y, cache, keep_prob):
  3. """
  4. Implements the backward propagation of our baseline model to which we added dropout.
  5. Arguments:
  6. X -- input dataset, of shape (2, number of examples)
  7. Y -- "true" labels vector, of shape (output size, number of examples)
  8. cache -- cache output from forward_propagation_with_dropout()
  9. keep_prob - probability of keeping a neuron active during drop-out, scalar
  10. Returns:
  11. gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables
  12. """
  13. m = X.shape[1]
  14. (Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3) = cache
  15. dZ3 = A3 - Y
  16. dW3 = 1. / m * np.dot(dZ3, A2.T)
  17. db3 = 1. / m * np.sum(dZ3, axis=1, keepdims=True)
  18. dA2 = np.dot(W3.T, dZ3)
  19. ### START CODE HERE ### (≈ 2 lines of code)
  20. dA2 = D2 * dA2 # Step 1: Apply mask D2 to shut down the same neurons as during the forward propagation
  21. dA2 = dA2 / keep_prob # Step 2: Scale the value of neurons that haven't been shut down
  22. ### END CODE HERE ###
  23. dZ2 = np.multiply(dA2, np.int64(A2 > 0))
  24. dW2 = 1. / m * np.dot(dZ2, A1.T)
  25. db2 = 1. / m * np.sum(dZ2, axis=1, keepdims=True)
  26. dA1 = np.dot(W2.T, dZ2)
  27. ### START CODE HERE ### (≈ 2 lines of code)
  28. dA1 = D1 * dA1 # Step 1: Apply mask D1 to shut down the same neurons as during the forward propagation
  29. dA1 = dA1 / keep_prob # Step 2: Scale the value of neurons that haven't been shut down
  30. ### END CODE HERE ###
  31. dZ1 = np.multiply(dA1, np.int64(A1 > 0))
  32. dW1 = 1. / m * np.dot(dZ1, X.T)
  33. db1 = 1. / m * np.sum(dZ1, axis=1, keepdims=True)
  34. gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3, "dA2": dA2,
  35. "dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1,
  36. "dZ1": dZ1, "dW1": dW1, "db1": db1}
  37. return gradients

现在来看看效果:

  1. #好了我们来测试一下
  2. X_assess, Y_assess, cache = backward_propagation_with_dropout_test_case()
  3. gradients = backward_propagation_with_dropout(X_assess, Y_assess, cache, keep_prob = 0.8)
  4. print ("dA1 = " + str(gradients["dA1"]))
  5. print ("dA2 = " + str(gradients["dA2"]))
  6. print("===============================")

下面是输出结果:

  1. dA1 = [[ 0.36544439 0. -0.00188233 0. -0.17408748]
  2. [ 0.65515713 0. -0.00337459 0. -0. ]]
  3. dA2 = [[ 0.58180856 0. -0.00299679 0. -0.27715731]
  4. [ 0. 0.53159854 -0. 0.53159854 -0.34089673]
  5. [ 0. 0. -0.00292733 0. -0. ]]

在这里我们再用同样的数据跑一边看看训练效果:

  1. #最后我们来吧之前的模型用dropout正则化方法来跑一下
  2. parameters = model(train_X, train_Y, keep_prob = 0.86, learning_rate = 0.3)
  3. print ("On the train set:")
  4. predictions_train = predict(train_X, train_Y, parameters)
  5. print ("On the test set:")
  6. predictions_test = predict(test_X, test_Y, parameters)
  7. #哇,你会惊奇地发现,效果更好,达到了百分之九十五的验证集准确度
  8. # On the train set:
  9. # Accuracy: 0.928909952607
  10. # On the test set:
  11. # Accuracy: 0.95
  12. #接下来来看看边界划分图
  13. plt.title("Model with dropout")
  14. axes = plt.gca()
  15. axes.set_xlim([-0.75,0.40])
  16. axes.set_ylim([-0.75,0.65])
  17. plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)

然后结果就像注释里写的,如下:

  1. Cost after iteration 0: 0.6543912405149825
  2. Cost after iteration 10000: 0.061016986574905605
  3. Cost after iteration 20000: 0.060582435798513114
  4. On the train set:
  5. Accuracy: 0.928909952607
  6. On the test set:
  7. Accuracy: 0.95

cost曲线为:

边界图为

总的来说,这个效果也是很好的

3. 梯度检验

1.

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