300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 吴恩达 02.改善深层神经网络:超参数调试 正则化以及优化 第一周作业

吴恩达 02.改善深层神经网络:超参数调试 正则化以及优化 第一周作业

时间:2018-08-28 18:27:34

相关推荐

吴恩达    02.改善深层神经网络:超参数调试 正则化以及优化    第一周作业

Initialization

Welcome to the first assignment of “Improving Deep Neural Networks”.

Training your neural network requires specifying an initial value of the weights. A well chosen initialization method will help learning.

If you completed the previous course of this specialization, you probably followed our instructions for weight initialization, and it has worked out so far. But how do you choose the initialization for a new neural network? In this notebook, you will see how different initializations lead to different results.

A well chosen initialization can:

Speed up the convergence of gradient descentIncrease the odds of gradient descent converging to a lower training (and generalization) error

To get started, run the following cell to load the packages and the planar dataset you will try to classify.

import numpy as npimport matplotlib.pyplot as pltimport sklearnimport sklearn.datasetsfrom init_utils import sigmoid, relu, compute_loss, forward_propagation, backward_propagation #初始化库from init_utils import update_parameters, predict, load_dataset, plot_decision_boundary, predict_dec%matplotlib inlineplt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plotsplt.rcParams['image.interpolation'] = 'nearest'plt.rcParams['image.cmap'] = 'gray'# load image dataset: blue/red dots in circlestrain_X, train_Y, test_X, test_Y = load_dataset()#导入写法二#import init_utils#train_X, train_Y, test_X, test_Y = init_utils.load_dataset()

[外链图片转存失败(img-bWosgVt9-1565859111256)(output_1_0.png)]

You would like a classifier to separate the blue dots from the red dots.

1 - Neural Network model 神经网络模型程序如下

You will use a 3-layer neural network (already implemented for you). Here are the initialization methods you will experiment with:

Zeros initialization– settinginitialization = "zeros"in the input argument.Random initialization– settinginitialization = "random"in the input argument. This initializes the weights to large random values.He initialization– settinginitialization = "he"in the input argument. This initializes the weights to random values scaled according to a paper by He et al., .

Instructions: Please quickly read over the code below, and run it. In the next part you will implement the three initialization methods that thismodel()calls.

#神经网络模型程序def model(X, Y, learning_rate = 0.01, num_iterations = 15000, print_cost = True, initialization = "he"):"""Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.Arguments:X -- input data, of shape (2, number of examples)Y -- true "label" vector (containing 0 for red dots; 1 for blue dots), of shape (1, number of examples)learning_rate -- learning rate for gradient descent num_iterations -- number of iterations to run gradient descentprint_cost -- if True, print the cost every 1000 iterationsinitialization -- flag to choose which initialization to use ("zeros","random" or "he")Returns:parameters -- parameters learnt by the model"""grads = {}costs = [] # to keep track of the lossm = X.shape[1] # number of exampleslayers_dims = [X.shape[0], 10, 5, 1]# Initialize parameters dictionary.if initialization == "zeros":parameters = initialize_parameters_zeros(layers_dims) #以下这三个初始化函数已经编好了,在下方elif initialization == "random":parameters = initialize_parameters_random(layers_dims)elif initialization == "he":parameters = initialize_parameters_he(layers_dims)else :print("错误的初始化参数!程序退出")# Loop (gradient descent)for i in range(0, num_iterations):# Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID.a3, cache = forward_propagation(X, parameters)# Losscost = compute_loss(a3, Y)# Backward propagation.grads = backward_propagation(X, Y, cache)# Update parameters.parameters = update_parameters(parameters, grads, learning_rate)# Print the loss every 1000 iterationsif print_cost and i % 1000 == 0:print("Cost after iteration {}: {}".format(i, cost))costs.append(cost)# plot the lossplt.plot(costs)plt.ylabel('cost')plt.xlabel('iterations (per hundreds)')plt.title("Learning rate =" + str(learning_rate))plt.show()return parameters

2 - Zero initialization

There are two types of parameters to initialize in a neural network:

the weight matrices (W[1],W[2],W[3],...,W[L−1],W[L])(W^{[1]}, W^{[2]}, W^{[3]}, ..., W^{[L-1]}, W^{[L]})(W[1],W[2],W[3],...,W[L−1],W[L])the bias vectors (b[1],b[2],b[3],...,b[L−1],b[L])(b^{[1]}, b^{[2]}, b^{[3]}, ..., b^{[L-1]}, b^{[L]})(b[1],b[2],b[3],...,b[L−1],b[L])

Exercise: Implement the following function to initialize all parameters to zeros. You’ll see later that this does not work well since it fails to “break symmetry”, but lets try it anyway and see what happens. Use np.zeros((…,…)) with the correct shapes.

明知道初始化为0,是不可行的,但是还是给大家演示一下。(无论多么复杂的神经网络,若参数w初始值是一样的,又因为dw是一样的,那么由于无法打破对称性性问题,因此最后的效果会特别的糟糕)

# GRADED FUNCTION: initialize_parameters_zeros def initialize_parameters_zeros(layers_dims):"""Arguments:layer_dims -- python array (list) containing the size of each layer.Returns:parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])b1 -- bias vector of shape (layers_dims[1], 1)...WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])bL -- bias vector of shape (layers_dims[L], 1)"""parameters = {}L = len(layers_dims) # number of layers in the networkfor l in range(1, L):### START CODE HERE ### (≈ 2 lines of code)parameters['W' + str(l)] = np.zeros((layers_dims[l],layers_dims[l-1]))parameters['b' + str(l)] = np.zeros((layers_dims[l],1))### END CODE HERE ###return parameters

parameters = initialize_parameters_zeros([3,2,1])print("W1 = " + str(parameters["W1"]))print("b1 = " + str(parameters["b1"]))print("W2 = " + str(parameters["W2"]))print("b2 = " + str(parameters["b2"]))

W1 = [[0. 0. 0.][0. 0. 0.]]b1 = [[0.][0.]]W2 = [[0. 0.]]b2 = [[0.]]

Expected Output:

Run the following code to train your model on 15,000 iterations using zeros initialization.

parameters = model(train_X, train_Y, initialization = "zeros")print ("On the train set:")predictions_train = predict(train_X, train_Y, parameters)print ("On the test set:")predictions_test = predict(test_X, test_Y, parameters)

Cost after iteration 0: 0.6931471805599453Cost after iteration 1000: 0.6931471805599453Cost after iteration 2000: 0.6931471805599453Cost after iteration 3000: 0.6931471805599453Cost after iteration 4000: 0.6931471805599453Cost after iteration 5000: 0.6931471805599453Cost after iteration 6000: 0.6931471805599453Cost after iteration 7000: 0.6931471805599453Cost after iteration 8000: 0.6931471805599453Cost after iteration 9000: 0.6931471805599453Cost after iteration 10000: 0.6931471805599455Cost after iteration 11000: 0.6931471805599453Cost after iteration 12000: 0.6931471805599453Cost after iteration 13000: 0.6931471805599453Cost after iteration 14000: 0.6931471805599453

[外链图片转存失败(img-smqslJzT-1565859111257)(output_11_1.png)]

On the train set:Accuracy: 0.5On the test set:Accuracy: 0.5

The performance is really bad, and the cost does not really decrease, and the algorithm performs no better than random guessing. Why? Lets look at the details of the predictions and the decision boundary:

print ("predictions_train = " + str(predictions_train))print ("predictions_test = " + str(predictions_test))

predictions_train = [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0]]predictions_test = [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]

plt.title("Model with Zeros initialization")axes = plt.gca()axes.set_xlim([-1.5,1.5])axes.set_ylim([-1.5,1.5])#下方语句会报错#方法一:把train_Y改为train_Y[0]就可以plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y[0])#方法二:改动nit_utils.py 中的 plot_decision_boundary()函数,具体的此处忽略

[外链图片转存失败(img-OOV4u6BC-1565859111257)(output_14_0.png)]

The model is predicting 0 for every example.

In general, initializing all the weights to zero results in the network failing to break symmetry. This means that every neuron in each layer will learn the same thing, and you might as well be training a neural network with n[l]=1n^{[l]}=1n[l]=1 for every layer, and the network is no more powerful than a linear classifier such as logistic regression.

**What you should remember**: - The weights $W^{[l]}$ should be initialized randomly to break symmetry. - It is however okay to initialize the biases $b^{[l]}$ to zeros. Symmetry is still broken so long as $W^{[l]}$ is initialized randomly.

说白了一句话,一定要打破W的对称性。

3 - Random initialization

To break symmetry, lets intialize the weights randomly. Following random initialization, each neuron can then proceed to learn a different function of its inputs. In this exercise, you will see what happens if the weights are intialized randomly, but to very large values.

Exercise: Implement the following function to initialize your weights to large random values (scaled by *10) and your biases to zeros. Usenp.random.randn(..,..) * 10for weights andnp.zeros((.., ..))for biases. We are using a fixednp.random.seed(..)to make sure your “random” weights match ours, so don’t worry if running several times your code gives you always the same initial values for the parameters.

# GRADED FUNCTION: initialize_parameters_randomdef initialize_parameters_random(layers_dims):"""Arguments:layer_dims -- python array (list) containing the size of each layer.Returns:parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])b1 -- bias vector of shape (layers_dims[1], 1)...WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])bL -- bias vector of shape (layers_dims[L], 1)"""np.random.seed(3)# This seed makes sure your "random" numbers will be the as oursparameters = {}L = len(layers_dims) # integer representing the number of layersfor l in range(1, L):### START CODE HERE ### (≈ 2 lines of code)parameters['W' + str(l)] = np.random.randn(layers_dims[l],layers_dims[l-1])*10 #使用10倍缩放parameters['b' + str(l)] = np.zeros((layers_dims[l],1))#b仍初始化为0### END CODE HERE ####使用断言确保我的数据格式是正确的assert(parameters["W" + str(l)].shape == (layers_dims[l],layers_dims[l-1]))assert(parameters["b" + str(l)].shape == (layers_dims[l],1))return parameters

parameters = initialize_parameters_random([3, 2, 1])print("W1 = " + str(parameters["W1"]))print("b1 = " + str(parameters["b1"]))print("W2 = " + str(parameters["W2"]))print("b2 = " + str(parameters["b2"]))

W1 = [[ 17.88628473 4.36509851 0.96497468][-18.63492703 -2.77388203 -3.54758979]]b1 = [[0.][0.]]W2 = [[-0.82741481 -6.27000677]]b2 = [[0.]]

Expected Output:

Run the following code to train your model on 15,000 iterations using random initialization.

parameters = model(train_X, train_Y, initialization = "random")print ("On the train set:")predictions_train = predict(train_X, train_Y, parameters)print ("On the test set:")predictions_test = predict(test_X, test_Y, parameters)

E:\jupyter\吴恩达深度学习第二课第一周作业\初始化Initialization\init_utils.py:145: RuntimeWarning: divide by zero encountered in loglogprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y)E:\jupyter\吴恩达深度学习第二课第一周作业\初始化Initialization\init_utils.py:145: RuntimeWarning: invalid value encountered in multiplylogprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y)Cost after iteration 0: infCost after iteration 1000: 0.6250982793959966Cost after iteration 2000: 0.5981216596703697Cost after iteration 3000: 0.5638417572298645Cost after iteration 4000: 0.5501703049199763Cost after iteration 5000: 0.5444632909664456Cost after iteration 6000: 0.5374513807000807Cost after iteration 7000: 0.4764042074074983Cost after iteration 8000: 0.39781492295092263Cost after iteration 9000: 0.3934764028765484Cost after iteration 10000: 0.3920295461882659Cost after iteration 11000: 0.38924598135108Cost after iteration 12000: 0.3861547485712325Cost after iteration 13000: 0.384984728909703Cost after iteration 14000: 0.3827828308349524

[外链图片转存失败(img-aQFcANDN-1565859111258)(output_22_2.png)]

On the train set:Accuracy: 0.83On the test set:Accuracy: 0.86

If you see “inf” as the cost after the iteration 0, this is because of numerical roundoff; a more numerically sophisticated implementation would fix this. But this isn’t worth worrying about for our purposes.

Anyway, it looks like you have broken symmetry, and this gives better results. than before. The model is no longer outputting all 0s.

print (predictions_train)print (predictions_test)

[[1 0 1 1 0 0 1 1 1 1 1 0 1 0 0 1 0 1 1 0 0 0 1 0 1 1 1 1 1 1 0 1 1 0 0 11 1 1 1 1 1 1 0 1 1 1 1 0 1 0 1 1 1 1 0 0 1 1 1 1 0 1 1 0 1 0 1 1 1 1 00 0 0 0 1 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 0 1 1 1 0 1 1 0 1 0 1 1 0 1 1 01 0 1 1 0 0 1 0 0 1 1 0 1 1 1 0 1 0 0 1 0 1 1 1 1 1 1 1 0 1 1 0 0 1 1 00 0 1 0 1 0 1 0 1 1 1 0 0 1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 1 1 1 1 0 1 1 11 0 1 0 1 0 1 1 1 1 0 1 1 0 1 1 0 1 1 0 1 0 1 1 1 0 1 1 1 0 1 0 1 0 0 10 1 1 0 1 1 0 1 1 0 1 1 1 0 1 1 1 1 0 1 0 0 1 1 0 1 1 1 0 0 0 1 1 0 1 11 1 0 1 1 0 1 1 1 0 0 1 0 0 0 1 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 11 1 1 1 0 0 0 1 1 1 1 0]][[1 1 1 1 0 1 0 1 1 0 1 1 1 0 0 0 0 1 0 1 0 0 1 0 1 0 1 1 1 1 1 0 0 0 0 10 1 1 0 0 1 1 1 1 1 0 1 1 1 0 1 0 1 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 0 1 01 1 1 1 1 0 1 0 0 1 0 0 0 1 1 0 1 1 0 0 0 1 1 0 1 1 0 0]]

plt.title("Model with large random initialization")axes = plt.gca()axes.set_xlim([-1.5,1.5])axes.set_ylim([-1.5,1.5])plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y[0])

[外链图片转存失败(img-HTQcw2Ur-1565859111259)(output_25_0.png)]

Observations:

The cost starts very high. This is because with large random-valued weights, the last activation (sigmoid) outputs results that are very close to 0 or 1 for some examples, and when it gets that example wrong it incurs a very high loss for that example. Indeed, when log⁡(a[3])=log⁡(0)\log(a^{[3]}) = \log(0)log(a[3])=log(0), the loss goes to infinity.Poor initialization can lead to vanishing/exploding gradients, which also slows down the optimization algorithm.If you train this network longer you will see better results, but initializing with overly large random numbers slows down the optimization. **In summary**: - Initializing weights to very large random values does not work well. - Hopefully intializing with small random values does better. The important question is: how small should be these random values be? Lets find out in the next part!

4 - He initialization

Finally, try “He Initialization”; this is named for the first author of He et al., . (If you have heard of “Xavier initialization”, this is similar except Xavier initialization uses a scaling factor for the weights W[l]W^{[l]}W[l] ofsqrt(1./layers_dims[l-1])where He initialization would usesqrt(2./layers_dims[l-1]).)

Exercise: Implement the following function to initialize your parameters with He initialization.

Hint: This function is similar to the previousinitialize_parameters_random(...). The only difference is that instead of multiplyingnp.random.randn(..,..)by 10, you will multiply it by 2dimensionofthepreviouslayer\sqrt{\frac{2}{\text{dimension of the previous layer}}}dimensionofthepreviouslayer2​​, which is what He initialization recommends for layers with a ReLU activation.

# GRADED FUNCTION: initialize_parameters_hedef initialize_parameters_he(layers_dims):"""Arguments:layer_dims -- python array (list) containing the size of each layer.Returns:parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])b1 -- bias vector of shape (layers_dims[1], 1)...WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])bL -- bias vector of shape (layers_dims[L], 1)"""np.random.seed(3)parameters = {}L = len(layers_dims) - 1 # integer representing the number of layersfor l in range(1, L + 1):### START CODE HERE ### (≈ 2 lines of code)parameters['W' + str(l)] = np.random.randn(layers_dims[l],layers_dims[l-1])*np.sqrt(2./layers_dims[l-1])parameters['b' + str(l)] = np.zeros((layers_dims[l],1))### END CODE HERE ###return parameters

parameters = initialize_parameters_he([2, 4, 1])print("W1 = " + str(parameters["W1"]))print("b1 = " + str(parameters["b1"]))print("W2 = " + str(parameters["W2"]))print("b2 = " + str(parameters["b2"]))

W1 = [[ 1.78862847 0.43650985][ 0.09649747 -1.8634927 ][-0.2773882 -0.35475898][-0.08274148 -0.62700068]]b1 = [[0.][0.][0.][0.]]W2 = [[-0.03098412 -0.33744411 -0.92904268 0.62552248]]b2 = [[0.]]

Expected Output:

Run the following code to train your model on 15,000 iterations using He initialization.

parameters = model(train_X, train_Y, initialization = "he")print ("On the train set:")predictions_train = predict(train_X, train_Y, parameters)print ("On the test set:")predictions_test = predict(test_X, test_Y, parameters)

Cost after iteration 0: 0.8830537463419761Cost after iteration 1000: 0.6879825919728063Cost after iteration 2000: 0.6751286264523371Cost after iteration 3000: 0.6526117768893807Cost after iteration 4000: 0.6082958970572937Cost after iteration 5000: 0.5304944491717495Cost after iteration 6000: 0.4138645817071793Cost after iteration 7000: 0.3117803464844441Cost after iteration 8000: 0.23696215330322556Cost after iteration 9000: 0.18597287209206828Cost after iteration 10000: 0.15015556280371808Cost after iteration 11000: 0.12325079292273548Cost after iteration 12000: 0.09917746546525937Cost after iteration 13000: 0.08457055954024274Cost after iteration 14000: 0.07357895962677366

[外链图片转存失败(img-XsEgWHCC-1565859111259)(output_32_1.png)]

On the train set:Accuracy: 0.9933333333333333On the test set:Accuracy: 0.96

#本来这个函数在init_units包里有,但是每次调用的时候我都要在train_y后加[0],为了避免这种情况#于是更改plot_decision_boundary(model, X, y)函数,但是更改以后不能用,因此我就直接在这个文件夹里定义了。def plot_decision_boundary(model, X, y):# Set min and max values and give it some paddingx_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1h = 0.01# Generate a grid of points with distance h between themxx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))# Predict the function value for the whole gridZ = model(np.c_[xx.ravel(), yy.ravel()])Z = Z.reshape(xx.shape)# Plot the contour and training examplesplt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)plt.ylabel('x2')plt.xlabel('x1')plt.scatter(X[0, :], X[1, :], c=np.squeeze(y), cmap=plt.cm.Spectral)plt.show()

plt.title("Model with He initialization")axes = plt.gca()axes.set_xlim([-1.5,1.5])axes.set_ylim([-1.5,1.5])plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)

[外链图片转存失败(img-s9rWthQy-1565859111260)(output_34_0.png)]

Observations:

The model with He initialization separates the blue and the red dots very well in a small number of iterations.

5 - Conclusions

You have seen three different types of initializations. For the same number of iterations and same hyperparameters the comparison is:

</tr><td>3-layer NN with zeros initialization</td><td>50%</td><td>fails to break symmetry</td><tr><td>3-layer NN with large random initialization</td><td>83%</td><td>too large weights </td></tr><tr><td>3-layer NN with He initialization</td><td>99%</td><td>recommended method</td></tr>

**What you should remember from this notebook**: - Different initializations lead to different results - Random initialization is used to break symmetry and make sure different hidden units can learn different things - Don't intialize to values that are too large - He initialization works well for networks with ReLU activations.

Regularization

Welcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity thatoverfitting can be a serious problem, if the training dataset is not big enough. Sure it does well on the training set, but the learned networkdoesn’t generalize to new examplesthat it has never seen!

You will learn to:Use regularization in your deep learning models.

Let’s first import the packages you are going to use.

# import packagesimport numpy as npimport matplotlib.pyplot as pltfrom reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_decfrom reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parametersimport sklearnimport sklearn.datasetsimport scipy.iofrom testCases import *%matplotlib inlineplt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plotsplt.rcParams['image.interpolation'] = 'nearest'plt.rcParams['image.cmap'] = 'gray'

Problem Statement: You have just been hired as an AI expert by the French Football Corporation. They would like you to recommend positions where France’s goal keeper should kick the ball so that the French team’s players can then hit it with their head.

**Figure 1**: **Football field**

The goal keeper kicks the ball in the air, the players of each team are fighting to hit the ball with their head

They give you the following 2D dataset from France’s past 10 games.

def load_2D_dataset():data = scipy.io.loadmat('datasets/data.mat')train_X = data['X'].Ttrain_Y = data['y'].Ttest_X = data['Xval'].Ttest_Y = data['yval'].T## np.squeeze()从数组的形状中删除单维条目,即把shape中为1的维度去掉plt.scatter(train_X[0, :], train_X[1, :], c=np.squeeze(train_Y), s=40, cmap=plt.cm.Spectral);return train_X, train_Y, test_X, test_Y

train_X, train_Y, test_X, test_Y = load_2D_dataset()

[外链图片转存失败(img-HtshZsrt-1565859062686)(output_4_0.png)]

Each dot corresponds to a position on the football field where a football player has hit the ball with his/her head after the French goal keeper has shot the ball from the left side of the football field.

If the dot is blue, it means the French player managed to hit the ball with his/her headIf the dot is red, it means the other team’s player hit the ball with their head

Your goal: Use a deep learning model to find the positions on the field where the goalkeeper should kick the ball.

Analysis of the dataset: This dataset is a little noisy, but it looks like a diagonal line separating the upper left half (blue) from the lower right half (red) would work well.

You will first try a non-regularized model. Then you’ll learn how to regularize it and decide which model you will choose to solve the French Football Corporation’s problem.

1 - Non-regularized model

You will use the following neural network (already implemented for you below). This model can be used:

inregularization mode– by setting thelambdinput to a non-zero value. We use “lambd” instead of “lambda” because “lambda” is a reserved keyword in Python.indropout mode– by setting thekeep_probto a value less than one

You will first try the model without any regularization. Then, you will implement:

L2 regularization– functions: “compute_cost_with_regularization()” and “backward_propagation_with_regularization()”Dropout– functions: “forward_propagation_with_dropout()” and “backward_propagation_with_dropout()

In each part, you will run this model with the correct inputs so that it calls the functions you’ve implemented. Take a look at the code below to familiarize yourself with the model.

def model(X, Y, learning_rate = 0.3, num_iterations = 30000, print_cost = True, lambd = 0, keep_prob = 1):"""Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.Arguments:X -- input data, of shape (input size, number of examples)Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (output size, number of examples)learning_rate -- learning rate of the optimizationnum_iterations -- number of iterations of the optimization loopprint_cost -- If True, print the cost every 10000 iterationslambd -- regularization hyperparameter, scalarkeep_prob - probability of keeping a neuron active during drop-out, scalar.Returns:parameters -- parameters learned by the model. They can then be used to predict."""grads = {}costs = [] # to keep track of the costm = X.shape[1] # number of exampleslayers_dims = [X.shape[0], 20, 3, 1]# Initialize parameters dictionary.parameters = initialize_parameters(layers_dims)# Loop (gradient descent)for i in range(0, num_iterations):# Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID.if keep_prob == 1:a3, cache = forward_propagation(X, parameters)elif keep_prob < 1:a3, cache = forward_propagation_with_dropout(X, parameters, keep_prob)# Cost functionif lambd == 0:cost = compute_cost(a3, Y)else:cost = compute_cost_with_regularization(a3, Y, parameters, lambd)# Backward propagation.##可以同时使用L2正则化和随机删除节点,但是本次实验不同时使用。assert(lambd==0 or keep_prob==1) # it is possible to use both L2 regularization and dropout, # but this assignment will only explore one at a time##两个参数的使用情况if lambd == 0 and keep_prob == 1:grads = backward_propagation(X, Y, cache)### 不使用L2正则化和不使用随机删除节点elif lambd != 0:grads = backward_propagation_with_regularization(X, Y, cache, lambd)### 不使用L2正则化和不使用随机删除节点elif keep_prob < 1:grads = backward_propagation_with_dropout(X, Y, cache, keep_prob)### 不使用L2正则化和不使用随机删除节点# Update parameters.parameters = update_parameters(parameters, grads, learning_rate)# Print the loss every 10000 iterationsif print_cost and i % 10000 == 0:print("Cost after iteration {}: {}".format(i, cost))if print_cost and i % 1000 == 0:costs.append(cost)## 记录成本# plot the cost绘制成本曲线图plt.plot(costs)plt.ylabel('cost')plt.xlabel('iterations (x1,000)')plt.title("Learning rate =" + str(learning_rate))plt.show()return parameters

Let’s train the model without any regularization, and observe the accuracy on the train/test sets.

parameters = model(train_X, train_Y) #调用的是上方的函数,虽然上方函数有7个参数,其中五个有缺省值print ("On the training set:")predictions_train = predict(train_X, train_Y, parameters)print ("On the test set:")predictions_test = predict(test_X, test_Y, parameters)

Cost after iteration 0: 0.6557412523481002Cost after iteration 10000: 0.1632998752572419Cost after iteration 20000: 0.13851642423239133

[外链图片转存失败(img-z1zH2IIp-1565859062687)(output_10_1.png)]

On the training set:Accuracy: 0.9478672985781991On the test set:Accuracy: 0.915

The train accuracy is 94.8% while the test accuracy is 91.5%. This is thebaseline model(you will observe the impact of regularization on this model). Run the following code to plot the decision boundary of your model.

plt.title("Model without regularization")axes = plt.gca()axes.set_xlim([-0.75,0.40])axes.set_ylim([-0.75,0.65])plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y[0]) #此处train_Y改为train_Y[0]

[外链图片转存失败(img-29MBn46D-1565859062687)(output_12_0.png)]

The non-regularized model is obviously overfitting the training set. It is fitting the noisy points! Lets now look at two techniques to reduce overfitting.

2 - L2 Regularization

The standard way to avoid overfitting is calledL2 regularization. It consists of appropriately modifying your cost function, from:

(1)J=−1m∑i=1m(y(i)log⁡(a[L](i))+(1−y(i))log⁡(1−a[L](i)))J = -\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{[L](i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right) \large{)} \tag{1}J=−m1​i=1∑m​(y(i)log(a[L](i))+(1−y(i))log(1−a[L](i)))(1)

To:

(2)Jregularized=−1m∑i=1m(y(i)log⁡(a[L](i))+(1−y(i))log⁡(1−a[L](i)))⎵cross-entropycost+1mλ2∑l∑k∑jWk,j[l]2⎵L2regularizationcostJ_{regularized} = \small \underbrace{-\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{[L](i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right) \large{)} }_\text{cross-entropy cost} + \underbrace{\frac{1}{m} \frac{\lambda}{2} \sum\limits_l\sum\limits_k\sum\limits_j W_{k,j}^{[l]2} }_\text{L2 regularization cost} \tag{2}Jregularized​=cross-entropycost−m1​i=1∑m​(y(i)log(a[L](i))+(1−y(i))log(1−a[L](i)))​​+L2regularizationcostm1​2λ​l∑​k∑​j∑​Wk,j[l]2​​​(2)

Let’s modify your cost and observe the consequences.

Exercise: Implementcompute_cost_with_regularization()which computes the cost given by formula (2). To calculate ∑k∑jWk,j[l]2\sum\limits_k\sum\limits_j W_{k,j}^{[l]2}k∑​j∑​Wk,j[l]2​ , use :

np.sum(np.square(Wl))

Note that you have to do this for W[1]W^{[1]}W[1], W[2]W^{[2]}W[2] and W[3]W^{[3]}W[3], then sum the three terms and multiply by $ \frac{1}{m} \frac{\lambda}{2} $.

# GRADED FUNCTION: compute_cost_with_regularizationdef compute_cost_with_regularization(A3, Y, parameters, lambd):"""Implement the cost function with L2 regularization. See formula (2) above.Arguments:A3 -- post-activation, output of forward propagation, of shape (output size, number of examples)Y -- "true" labels vector, of shape (output size, number of examples)parameters -- python dictionary containing parameters of the modelReturns:cost - value of the regularized loss function (formula (2))"""m = Y.shape[1]W1 = parameters["W1"]W2 = parameters["W2"]W3 = parameters["W3"]cross_entropy_cost = compute_cost(A3, Y) # This gives you the cross-entropy part of the cost### START CODE HERE ### (approx. 1 line)L2_regularization_cost = (np.sum(np.square(W1))+np.sum(np.square(W2))+np.sum(np.square(W3)))*(lambd/(2*m))### END CODER HERE ###cost = cross_entropy_cost + L2_regularization_costreturn cost

A3, Y_assess, parameters = compute_cost_with_regularization_test_case()print("cost = " + str(compute_cost_with_regularization(A3, Y_assess, parameters, lambd = 0.1)))

cost = 1.7864859451590758

Expected Output:

</tr>

Of course, because you changed the cost, you have to change backward propagation as well! All the gradients have to be computed with respect to this new cost.

Exercise: Implement the changes needed in backward propagation to take into account regularization. The changes only concern dW1, dW2 and dW3. For each, you have to add the regularization term’s gradient (ddW(12λmW2)=λmW\frac{d}{dW} ( \frac{1}{2}\frac{\lambda}{m} W^2) = \frac{\lambda}{m} WdWd​(21​mλ​W2)=mλ​W).

# GRADED FUNCTION: backward_propagation_with_regularizationdef backward_propagation_with_regularization(X, Y, cache, lambd):"""Implements the backward propagation of our baseline model to which we added an L2 regularization.Arguments:X -- input dataset, of shape (input size, number of examples)Y -- "true" labels vector, of shape (output size, number of examples)cache -- cache output from forward_propagation()lambd -- regularization hyperparameter, scalarReturns:gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables"""m = X.shape[1](Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cachedZ3 = A3 - Y### START CODE HERE ### (approx. 1 line)dW3 = 1./m * np.dot(dZ3, A2.T) + W3*lambd/m### END CODE HERE ###db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)dA2 = np.dot(W3.T, dZ3)dZ2 = np.multiply(dA2, np.int64(A2 > 0))### START CODE HERE ### (approx. 1 line)dW2 = 1./m * np.dot(dZ2, A1.T) + + W2*lambd/m### END CODE HERE ###db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)dA1 = np.dot(W2.T, dZ2)dZ1 = np.multiply(dA1, np.int64(A1 > 0))### START CODE HERE ### (approx. 1 line)dW1 = 1./m * np.dot(dZ1, X.T) + + W1*lambd/m### END CODE HERE ###db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True)gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,"dA2": dA2,"dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1}return gradients

X_assess, Y_assess, cache = backward_propagation_with_regularization_test_case()grads = backward_propagation_with_regularization(X_assess, Y_assess, cache, lambd = 0.7)print ("dW1 = "+ str(grads["dW1"]))print ("dW2 = "+ str(grads["dW2"]))print ("dW3 = "+ str(grads["dW3"]))

dW1 = [[-0.25604646 0.12298827 -0.28297129][-0.17706303 0.34536094 -0.4410571 ]]dW2 = [[ 0.79276486 0.85133918][-0.0957219 -0.01720463][-0.13100772 -0.03750433]]dW3 = [[-1.77691347 -0.11832879 -0.09397446]]

Expected Output:

Let’s now run the model with L2 regularization (λ=0.7)(\lambda = 0.7)(λ=0.7). Themodel()function will call:

compute_cost_with_regularizationinstead ofcompute_costbackward_propagation_with_regularizationinstead ofbackward_propagation

parameters = model(train_X, train_Y, lambd = 0.7)print ("On the train set:")predictions_train = predict(train_X, train_Y, parameters)print ("On the test set:")predictions_test = predict(test_X, test_Y, parameters)

Cost after iteration 0: 0.6974484493131264Cost after iteration 10000: 0.2684918873282239Cost after iteration 20000: 0.2680916337127301

[外链图片转存失败(img-npo2FjyR-1565859062687)(output_23_1.png)]

On the train set:Accuracy: 0.9383886255924171On the test set:Accuracy: 0.93

Congrats, the test set accuracy increased to 93%. You have saved the French football team!

You are not overfitting the training data anymore. Let’s plot the decision boundary.

plt.title("Model with L2-regularization")axes = plt.gca()axes.set_xlim([-0.75,0.40])axes.set_ylim([-0.75,0.65])plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y[0]) #改train_Y[0]

[外链图片转存失败(img-tpNTULV6-1565859062688)(output_25_0.png)]

Observations:

The value of λ\lambdaλ is a hyperparameter that you can tune using a dev set.L2 regularization makes your decision boundary smoother. If λ\lambdaλ is too large, it is also possible to “oversmooth”, resulting in a model with high bias.

What is L2-regularization actually doing?:

L2-regularization relies on the assumption that a model with small weights is simpler than a model with large weights. Thus, by penalizing the square values of the weights in the cost function you drive all the weights to smaller values. It becomes too costly for the cost to have large weights! This leads to a smoother model in which the output changes more slowly as the input changes.

**What you should remember** -- the implications of L2-regularization on: - The cost computation: - A regularization term is added to the cost - The backpropagation function: - There are extra terms in the gradients with respect to weight matrices - Weights end up smaller ("weight decay"): - Weights are pushed to smaller values.

3 - Dropout

Finally,dropoutis a widely used regularization technique that is specific to deep learning.

It randomly shuts down some neurons in each iteration.Watch these two videos to see what this means!

Figure 2: Drop-out on the second hidden layer.

At each iteration, you shut down (= set to zero) each neuron of a layer with probability $1 - keep\_prob$ or keep it with probability $keep\_prob$ (50% here). The dropped neurons don't contribute to the training in both the forward and backward propagations of the iteration.Figure 3: Drop-out on the first and third hidden layers.

$1^{st}$ layer: we shut down on average 40% of the neurons. $3^{rd}$ layer: we shut down on average 20% of the neurons.

When you shut some neurons down, you actually modify your model. The idea behind drop-out is that at each iteration, you train a different model that uses only a subset of your neurons. With dropout, your neurons thus become less sensitive to the activation of one other specific neuron, because that other neuron might be shut down at any time.

3.1 - Forward propagation with dropout

Exercise: Implement the forward propagation with dropout. You are using a 3 layer neural network, and will add dropout to the first and second hidden layers. We will not apply dropout to the input layer or output layer.

Instructions:

You would like to shut down some neurons in the first and second layers. To do that, you are going to carry out 4 Steps:

In lecture, we dicussed creating a variable d[1]d^{[1]}d[1] with the same shape as a[1]a^{[1]}a[1] usingnp.random.rand()to randomly get numbers between 0 and 1. Here, you will use a vectorized implementation, so create a random matrix $D^{[1]} = [d^{1} d^{1} … d^{1}] $ of the same dimension as A[1]A^{[1]}A[1].Set each entry of D[1]D^{[1]}D[1] to be 0 with probability (1-keep_prob) or 1 with probability (keep_prob), by thresholding values in D[1]D^{[1]}D[1] appropriately. Hint: to set all the entries of a matrix X to 0 (if entry is less than 0.5) or 1 (if entry is more than 0.5) you would do:X = (X < 0.5). Note that 0 and 1 are respectively equivalent to False and True.Set A[1]A^{[1]}A[1] to A[1]∗D[1]A^{[1]} * D^{[1]}A[1]∗D[1]. (You are shutting down some neurons). You can think of D[1]D^{[1]}D[1] as a mask, so that when it is multiplied with another matrix, it shuts down some of the values.Divide A[1]A^{[1]}A[1] bykeep_prob. By doing this you are assuring that the result of the cost will still have the same expected value as without drop-out. (This technique is also called inverted dropout.)

# GRADED FUNCTION: forward_propagation_with_dropoutdef forward_propagation_with_dropout(X, parameters, keep_prob = 0.5):"""Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.Arguments:X -- input dataset, of shape (2, number of examples)parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":W1 -- weight matrix of shape (20, 2)b1 -- bias vector of shape (20, 1)W2 -- weight matrix of shape (3, 20)b2 -- bias vector of shape (3, 1)W3 -- weight matrix of shape (1, 3)b3 -- bias vector of shape (1, 1)keep_prob - probability of keeping a neuron active during drop-out, scalarReturns:A3 -- last activation value, output of the forward propagation, of shape (1,1)cache -- tuple, information stored for computing the backward propagation"""np.random.seed(1)# retrieve parametersW1 = parameters["W1"]b1 = parameters["b1"]W2 = parameters["W2"]b2 = parameters["b2"]W3 = parameters["W3"]b3 = parameters["b3"]# LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOIDZ1 = np.dot(W1, X) + b1A1 = relu(Z1)### START CODE HERE ### (approx. 4 lines) # Steps 1-4 below correspond to the Steps 1-4 described above. #numpy.random.randn(d0, d1, …, dn)是从标准正态分布中返回一个或多个样本值。 #numpy.random.rand(d0, d1, …, dn)的随机样本位于[0, 1)中。D1 = np.random.rand(A1.shape[0],A1.shape[1]) # Step 1: initialize matrix D1 = np.random.rand(..., ...)D1 = D1 < keep_prob# Step 2: convert entries of D1 to 0 or 1 (using keep_prob as the threshold)A1 = np.multiply(A1,D1) # Step 3: shut down some neurons of A1A1 = A1/keep_prob # Step 4: scale the value of neurons that haven't been shut down### END CODE HERE ###Z2 = np.dot(W2, A1) + b2A2 = relu(Z2)### START CODE HERE ### (approx. 4 lines)D2 = np.random.rand(A2.shape[0],A2.shape[1]) # Step 1: initialize matrix D2 = np.random.rand(..., ...)D2 = D2 < keep_prob# Step 2: convert entries of D2 to 0 or 1 (using keep_prob as the threshold)A2 = np.multiply(A2,D2) # Step 3: shut down some neurons of A2A2 = A2/keep_prob # Step 4: scale the value of neurons that haven't been shut down### END CODE HERE ###Z3 = np.dot(W3, A2) + b3A3 = sigmoid(Z3)cache = (Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3)return A3, cache

X_assess, parameters = forward_propagation_with_dropout_test_case()A3, cache = forward_propagation_with_dropout(X_assess, parameters, keep_prob = 0.7)print ("A3 = " + str(A3))

A3 = [[0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]]

Expected Output:

</tr>

3.2 - Backward propagation with dropout

Exercise: Implement the backward propagation with dropout. As before, you are training a 3 layer network. Add dropout to the first and second hidden layers, using the masks D[1]D^{[1]}D[1] and D[2]D^{[2]}D[2] stored in the cache.

Instruction:

Backpropagation with dropout is actually quite easy. You will have to carry out 2 Steps:

You had previously shut down some neurons during forward propagation, by applying a mask D[1]D^{[1]}D[1] toA1. In backpropagation, you will have to shut down the same neurons, by reapplying the same mask D[1]D^{[1]}D[1] todA1.During forward propagation, you had dividedA1bykeep_prob. In backpropagation, you’ll therefore have to dividedA1bykeep_probagain (the calculus interpretation is that if A[1]A^{[1]}A[1] is scaled bykeep_prob, then its derivative dA[1]dA^{[1]}dA[1] is also scaled by the samekeep_prob).

# GRADED FUNCTION: backward_propagation_with_dropoutdef backward_propagation_with_dropout(X, Y, cache, keep_prob):"""Implements the backward propagation of our baseline model to which we added dropout.Arguments:X -- input dataset, of shape (2, number of examples)Y -- "true" labels vector, of shape (output size, number of examples)cache -- cache output from forward_propagation_with_dropout()keep_prob - probability of keeping a neuron active during drop-out, scalarReturns:gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables"""m = X.shape[1](Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3) = cachedZ3 = A3 - YdW3 = 1./m * np.dot(dZ3, A2.T)db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)dA2 = np.dot(W3.T, dZ3)### START CODE HERE ### (≈ 2 lines of code)dA2 = dA2*D2# Step 1: Apply mask D2 to shut down the same neurons as during the forward propagationdA2 = dA2/keep_prob # Step 2: Scale the value of neurons that haven't been shut down### END CODE HERE ###dZ2 = np.multiply(dA2, np.int64(A2 > 0))dW2 = 1./m * np.dot(dZ2, A1.T)db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)dA1 = np.dot(W2.T, dZ2)### START CODE HERE ### (≈ 2 lines of code)dA1 = dA1*D1 # Step 1: Apply mask D1 to shut down the same neurons as during the forward propagationdA1 = dA1/keep_prob # Step 2: Scale the value of neurons that haven't been shut down### END CODE HERE ###dZ1 = np.multiply(dA1, np.int64(A1 > 0))dW1 = 1./m * np.dot(dZ1, X.T)db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True)gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,"dA2": dA2,"dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1}return gradients

X_assess, Y_assess, cache = backward_propagation_with_dropout_test_case()gradients = backward_propagation_with_dropout(X_assess, Y_assess, cache, keep_prob = 0.8)print ("dA1 = " + str(gradients["dA1"]))print ("dA2 = " + str(gradients["dA2"]))

dA1 = [[ 0.36544439 0. -0.00188233 0. -0.17408748][ 0.65515713 0. -0.00337459 0. -0. ]]dA2 = [[ 0.58180856 0. -0.00299679 0. -0.27715731][ 0.0.53159854 -0.0.53159854 -0.34089673][ 0.0. -0.00292733 0. -0. ]]

Expected Output:

</tr><tr><td>**dA2**</td><td>[[ 0.58180856 0. -0.00299679 0. -0.27715731]

[ 0. 0.53159854 -0. 0.53159854 -0.34089673]

[ 0. 0. -0.00292733 0. -0. ]]

</tr>

Let’s now run the model with dropout (keep_prob = 0.86). It means at every iteration you shut down each neurons of layer 1 and 2 with 24% probability. The functionmodel()will now call:

forward_propagation_with_dropoutinstead offorward_propagation.backward_propagation_with_dropoutinstead ofbackward_propagation.

parameters = model(train_X, train_Y, keep_prob = 0.86, learning_rate = 0.3)print ("On the train set:")predictions_train = predict(train_X, train_Y, parameters)print ("On the test set:")predictions_test = predict(test_X, test_Y, parameters)

Cost after iteration 0: 0.6543912405149825E:\jupyter\吴恩达深度学习第二课第一周作业\正则化Regularization\reg_utils.py:236: RuntimeWarning: divide by zero encountered in loglogprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y)E:\jupyter\吴恩达深度学习第二课第一周作业\正则化Regularization\reg_utils.py:236: RuntimeWarning: invalid value encountered in multiplylogprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y)Cost after iteration 10000: 0.061016986574905605Cost after iteration 20000: 0.060582435798513114

[外链图片转存失败(img-w4s5gLSI-1565859062688)(output_36_3.png)]

On the train set:Accuracy: 0.9289099526066351On the test set:Accuracy: 0.95

Dropout works great! The test accuracy has increased again (to 95%)! Your model is not overfitting the training set and does a great job on the test set. The French football team will be forever grateful to you!

Run the code below to plot the decision boundary.

plt.title("Model with dropout")axes = plt.gca()axes.set_xlim([-0.75,0.40])axes.set_ylim([-0.75,0.65])plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y[0])

[外链图片转存失败(img-GLdXlqov-1565859062689)(output_38_0.png)]

Note:

Acommon mistakewhen using dropout is to use it both in training and testing. You should use dropout (randomly eliminate nodes) only in training.

只在训练的时候使用dropout,最终测试的时候,不使用dropout,还使用原来的模型,所有神经元一起上。但是请注意,当使用Dropout时,因为神经元个数变为了keep_prob,因此参数除以keep_prob,最后测试时,因为所有神经元全上,所以不用除以keep_prob了。否则最终z值会偏大。

Deep learning frameworks like tensorflow, PaddlePaddle, keras or caffe come with a dropout layer implementation. Don’t stress - you will soon learn some of these frameworks. **What you should remember about dropout:** - Dropout is a regularization technique. - You only use dropout during training. Don't use dropout (randomly eliminate nodes) during test time. - Apply dropout both during forward and backward propagation. - During training time, divide each dropout layer by keep_prob to keep the same expected value for the activations. For example, if keep_prob is 0.5, then we will on average shut down half the nodes, so the output will be scaled by 0.5 since only the remaining half are contributing to the solution. Dividing by 0.5 is equivalent to multiplying by 2. Hence, the output now has the same expected value. You can check that this works even when keep_prob is other values than 0.5.

4 - Conclusions

Here are the results of our three models:

</tr><td>3-layer NN without regularization</td><td>95%</td><td>91.5%</td><tr><td>3-layer NN with L2-regularization</td><td>94%</td><td>93%</td></tr><tr><td>3-layer NN with dropout</td><td>93%</td><td>95%</td></tr>

Note that regularization hurts training set performance! This is because it limits the ability of the network to overfit to the training set. But since it ultimately gives better test accuracy, it is helping your system.

Congratulations for finishing this assignment! And also for revolutionizing French football. ?

**What we want you to remember from this notebook**: - Regularization will help you reduce overfitting. - Regularization will drive your weights to lower values. - L2 regularization and Dropout are two very effective regularization techniques.

Gradient Checking

Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking.

You are part of a team working to make mobile payments available globally, and are asked to build a deep learning model to detect fraud–whenever someone makes a payment, you want to see if the payment might be fraudulent, such as if the user’s account has been taken over by a hacker.

But backpropagation is quite challenging to implement, and sometimes has bugs. Because this is a mission-critical application, your company’s CEO wants to be really certain that your implementation of backpropagation is correct. Your CEO says, “Give me a proof that your backpropagation is actually working!” To give this reassurance, you are going to use “gradient checking”.

Let’s do it!

# Packagesimport numpy as npfrom testCases import *from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector

1) How does gradient checking work?

Backpropagation computes the gradients ∂J∂θ\frac{\partial J}{\partial \theta}∂θ∂J​, where θ\thetaθ denotes the parameters of the model. JJJ is computed using forward propagation and your loss function.

Because forward propagation is relatively easy to implement, you’re confident you got that right, and so you’re almost 100% sure that you’re computing the cost JJJ correctly. Thus, you can use your code for computing JJJ to verify the code for computing ∂J∂θ\frac{\partial J}{\partial \theta}∂θ∂J​.

Let’s look back at the definition of a derivative (or gradient):

(1)∂J∂θ=lim⁡ε→0J(θ+ε)−J(θ−ε)2ε\frac{\partial J}{\partial \theta} = \lim_{\varepsilon \to 0} \frac{J(\theta + \varepsilon) - J(\theta - \varepsilon)}{2 \varepsilon} \tag{1}∂θ∂J​=ε→0lim​2εJ(θ+ε)−J(θ−ε)​(1)

If you’re not familiar with the “lim⁡ε→0\displaystyle \lim_{\varepsilon \to 0}ε→0lim​” notation, it’s just a way of saying “when ε\varepsilonε is really really small.”

We know the following:

∂J∂θ\frac{\partial J}{\partial \theta}∂θ∂J​ is what you want to make sure you’re computing correctly.You can compute J(θ+ε)J(\theta + \varepsilon)J(θ+ε) and J(θ−ε)J(\theta - \varepsilon)J(θ−ε) (in the case that θ\thetaθ is a real number), since you’re confident your implementation for JJJ is correct.

Lets use equation (1) and a small value for ε\varepsilonε to convince your CEO that your code for computing ∂J∂θ\frac{\partial J}{\partial \theta}∂θ∂J​ is correct!

2) 1-dimensional gradient checking

Consider a 1D linear function J(θ)=θxJ(\theta) = \theta xJ(θ)=θx. The model contains only a single real-valued parameter θ\thetaθ, and takes xxx as input.

You will implement code to compute J(.)J(.)J(.) and its derivative ∂J∂θ\frac{\partial J}{\partial \theta}∂θ∂J​. You will then use gradient checking to make sure your derivative computation for JJJ is correct.

**Figure 1**: **1D linear model**

The diagram above shows the key computation steps: First start with xxx, then evaluate the function J(x)J(x)J(x) (“forward propagation”). Then compute the derivative ∂J∂θ\frac{\partial J}{\partial \theta}∂θ∂J​ (“backward propagation”).

Exercise: implement “forward propagation” and “backward propagation” for this simple function. I.e., compute both J(.)J(.)J(.) (“forward propagation”) and its derivative with respect to θ\thetaθ (“backward propagation”), in two separate functions.

# GRADED FUNCTION: forward_propagationdef forward_propagation(x, theta):"""Implement the linear forward propagation (compute J) presented in Figure 1 (J(theta) = theta * x)Arguments:x -- a real-valued inputtheta -- our parameter, a real number as wellReturns:J -- the value of function J, computed using the formula J(theta) = theta * x"""### START CODE HERE ### (approx. 1 line)J = np.dot(theta,x)### END CODE HERE ###return J

x, theta = 2, 4J = forward_propagation(x, theta)print ("J = " + str(J))

J = 8

Expected Output:

Exercise: Now, implement the backward propagation step (derivative computation) of Figure 1. That is, compute the derivative of J(θ)=θxJ(\theta) = \theta xJ(θ)=θx with respect to θ\thetaθ. To save you from doing the calculus, you should get dtheta=∂J∂θ=xdtheta = \frac { \partial J }{ \partial \theta} = xdtheta=∂θ∂J​=x.

# GRADED FUNCTION: backward_propagationdef backward_propagation(x, theta):"""Computes the derivative of J with respect to theta (see Figure 1).Arguments:x -- a real-valued inputtheta -- our parameter, a real number as wellReturns:dtheta -- the gradient of the cost with respect to theta"""### START CODE HERE ### (approx. 1 line)dtheta = x### END CODE HERE ###return dtheta

x, theta = 2, 4dtheta = backward_propagation(x, theta)print ("dtheta = " + str(dtheta))

dtheta = 2

Expected Output:

Exercise: To show that thebackward_propagation()function is correctly computing the gradient ∂J∂θ\frac{\partial J}{\partial \theta}∂θ∂J​, let’s implement gradient checking.

Instructions:

First compute “gradapprox” using the formula above (1) and a small value of ε\varepsilonε. Here are the Steps to follow: θ+=θ+ε\theta^{+} = \theta + \varepsilonθ+=θ+εθ−=θ−ε\theta^{-} = \theta - \varepsilonθ−=θ−εJ+=J(θ+)J^{+} = J(\theta^{+})J+=J(θ+)J−=J(θ−)J^{-} = J(\theta^{-})J−=J(θ−)gradapprox=J+−J−2εgradapprox = \frac{J^{+} - J^{-}}{2 \varepsilon}gradapprox=2εJ+−J−​ Then compute the gradient using backward propagation, and store the result in a variable “grad”Finally, compute the relative difference between “gradapprox” and the “grad” using the following formula:

(2)difference=∣∣grad−gradapprox∣∣2∣∣grad∣∣2+∣∣gradapprox∣∣2difference = \frac {\mid\mid grad - gradapprox \mid\mid_2}{\mid\mid grad \mid\mid_2 + \mid\mid gradapprox \mid\mid_2} \tag{2}difference=∣∣grad∣∣2​+∣∣gradapprox∣∣2​∣∣grad−gradapprox∣∣2​​(2)

You will need 3 Steps to compute this formula: 1’. compute the numerator using np.linalg.norm(…)2’. compute the denominator. You will need to call np.linalg.norm(…) twice.3’. divide them. If this difference is small (say less than 10−710^{-7}10−7), you can be quite confident that you have computed your gradient correctly. Otherwise, there may be a mistake in the gradient computation.

# GRADED FUNCTION: gradient_checkdef gradient_check(x, theta, epsilon = 1e-7):"""Implement the backward propagation presented in Figure 1.Arguments:x -- a real-valued inputtheta -- our parameter, a real number as wellepsilon -- tiny shift to the input to compute approximated gradient with formula(1)Returns:difference -- difference (2) between the approximated gradient and the backward propagation gradient"""# Compute gradapprox using left side of formula (1). epsilon is small enough, you don't need to worry about the limit.### START CODE HERE ### (approx. 5 lines)thetaplus = theta + epsilon # Step 1thetaminus = theta - epsilon # Step 2J_plus = forward_propagation(x, thetaplus) # Step 3J_minus = forward_propagation(x, thetaminus) # Step 4gradapprox = (J_plus - J_minus)/(2*epsilon) # Step 5### END CODE HERE #### Check if gradapprox is close enough to the output of backward_propagation()### START CODE HERE ### (approx. 1 line)grad = backward_propagation(x,theta)### END CODE HERE ###### START CODE HERE ### (approx. 1 line)#linalg=linear(线性)+algebra(代数),norm则表示范数。numerator = np.linalg.norm(grad-gradapprox) # Step 1'denominator = np.linalg.norm(grad)+ np.linalg.norm(gradapprox) # Step 2'difference = numerator/denominator# Step 3'### END CODE HERE ###if difference < 1e-7:print ("The gradient is correct!")else:print ("The gradient is wrong!")return difference

x, theta = 2, 4difference = gradient_check(x, theta)print("difference = " + str(difference))

The gradient is correct!difference = 2.919335883291695e-10

Expected Output:

The gradient is correct!

Congrats, the difference is smaller than the 10−710^{-7}10−7 threshold. So you can have high confidence that you’ve correctly computed the gradient inbackward_propagation().

Now, in the more general case, your cost function JJJ has more than a single 1D input. When you are training a neural network, θ\thetaθ actually consists of multiple matrices W[l]W^{[l]}W[l] and biases b[l]b^{[l]}b[l]! It is important to know how to do a gradient check with higher-dimensional inputs. Let’s do it!

3) N-dimensional gradient checking

The following figure describes the forward and backward propagation of your fraud detection model.

**Figure 2**: **deep neural network**

*LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID*

Let’s look at your implementations for forward propagation and backward propagation.

def forward_propagation_n(X, Y, parameters):"""Implements the forward propagation (and computes the cost) presented in Figure 3.Arguments:X -- training set for m examplesY -- labels for m examples parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":W1 -- weight matrix of shape (5, 4)b1 -- bias vector of shape (5, 1)W2 -- weight matrix of shape (3, 5)b2 -- bias vector of shape (3, 1)W3 -- weight matrix of shape (1, 3)b3 -- bias vector of shape (1, 1)Returns:cost -- the cost function (logistic cost for one example)"""# retrieve parametersm = X.shape[1]W1 = parameters["W1"]b1 = parameters["b1"]W2 = parameters["W2"]b2 = parameters["b2"]W3 = parameters["W3"]b3 = parameters["b3"]# LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOIDZ1 = np.dot(W1, X) + b1A1 = relu(Z1)Z2 = np.dot(W2, A1) + b2A2 = relu(Z2)Z3 = np.dot(W3, A2) + b3A3 = sigmoid(Z3)# Costlogprobs = np.multiply(-np.log(A3),Y) + np.multiply(-np.log(1 - A3), 1 - Y)cost = 1./m * np.sum(logprobs)cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3)return cost, cache

Now, run backward propagation.

def backward_propagation_n(X, Y, cache):"""Implement the backward propagation presented in figure 2.Arguments:X -- input datapoint, of shape (input size, 1)Y -- true "label"cache -- cache output from forward_propagation_n()Returns:gradients -- A dictionary with the gradients of the cost with respect to each parameter, activation and pre-activation variables."""m = X.shape[1](Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cachedZ3 = A3 - YdW3 = 1./m * np.dot(dZ3, A2.T)db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)dA2 = np.dot(W3.T, dZ3)dZ2 = np.multiply(dA2, np.int64(A2 > 0))dW2 = 1./m * np.dot(dZ2, A1.T) * 2db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)dA1 = np.dot(W2.T, dZ2)dZ1 = np.multiply(dA1, np.int64(A1 > 0))dW1 = 1./m * np.dot(dZ1, X.T)db1 = 4./m * np.sum(dZ1, axis=1, keepdims = True)gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,"dA2": dA2, "dZ2": dZ2, "dW2": dW2, "db2": db2,"dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1}return gradients

You obtained some results on the fraud detection test set but you are not 100% sure of your model. Nobody’s perfect! Let’s implement gradient checking to verify if your gradients are correct.

How does gradient checking work?.

As in 1) and 2), you want to compare “gradapprox” to the gradient computed by backpropagation. The formula is still:

(1)∂J∂θ=lim⁡ε→0J(θ+ε)−J(θ−ε)2ε\frac{\partial J}{\partial \theta} = \lim_{\varepsilon \to 0} \frac{J(\theta + \varepsilon) - J(\theta - \varepsilon)}{2 \varepsilon} \tag{1}∂θ∂J​=ε→0lim​2εJ(θ+ε)−J(θ−ε)​(1)

However, θ\thetaθ is not a scalar anymore. It is a dictionary called “parameters”. We implemented a function “dictionary_to_vector()” for you. It converts the “parameters” dictionary into a vector called “values”, obtained by reshaping all parameters (W1, b1, W2, b2, W3, b3) into vectors and concatenating them.

The inverse function is “vector_to_dictionary” which outputs back the “parameters” dictionary.

**Figure 2**: **dictionary_to_vector() and vector_to_dictionary()**

You will need these functions in gradient_check_n()

We have also converted the “gradients” dictionary into a vector “grad” using gradients_to_vector(). You don’t need to worry about that.

Exercise: Implement gradient_check_n().

Instructions: Here is pseudo-code that will help you implement the gradient check.

For each i in num_parameters:

To computeJ_plus[i]: Set θ+\theta^{+}θ+ tonp.copy(parameters_values)Set θi+\theta^{+}_iθi+​ to θi++ε\theta^{+}_i + \varepsilonθi+​+εCalculate Ji+J^{+}_iJi+​ using toforward_propagation_n(x, y, vector_to_dictionary(θ+\theta^{+}θ+)). To computeJ_minus[i]: do the same thing with θ−\theta^{-}θ−Compute gradapprox[i]=Ji+−Ji−2εgradapprox[i] = \frac{J^{+}_i - J^{-}_i}{2 \varepsilon}gradapprox[i]=2εJi+​−Ji−​​

Thus, you get a vector gradapprox, where gradapprox[i] is an approximation of the gradient with respect toparameter_values[i]. You can now compare this gradapprox vector to the gradients vector from backpropagation. Just like for the 1D case (Steps 1’, 2’, 3’), compute:

(3)difference=∥grad−gradapprox∥2∥grad∥2+∥gradapprox∥2difference = \frac {\| grad - gradapprox \|_2}{\| grad \|_2 + \| gradapprox \|_2 } \tag{3}difference=∥grad∥2​+∥gradapprox∥2​∥grad−gradapprox∥2​​(3)

# GRADED FUNCTION: gradient_check_ndef gradient_check_n(parameters, gradients, X, Y, epsilon = 1e-7):"""Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_nArguments:parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":grad -- output of backward_propagation_n, contains gradients of the cost with respect to the parameters. x -- input datapoint, of shape (input size, 1)y -- true "label"epsilon -- tiny shift to the input to compute approximated gradient with formula(1)Returns:difference -- difference (2) between the approximated gradient and the backward propagation gradient"""# Set-up variablesparameters_values, _ = dictionary_to_vector(parameters)grad = gradients_to_vector(gradients)num_parameters = parameters_values.shape[0]J_plus = np.zeros((num_parameters, 1))J_minus = np.zeros((num_parameters, 1))gradapprox = np.zeros((num_parameters, 1))# Compute gradapproxfor i in range(num_parameters):# Compute J_plus[i]. Inputs: "parameters_values, epsilon". Output = "J_plus[i]".# "_" is used because the function you have to outputs two parameters but we only care about the first one### START CODE HERE ### (approx. 3 lines)thetaplus = np.copy(parameters_values) # Step 1thetaplus[i][0] += epsilon # Step 2J_plus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaplus)) # Step 3### END CODE HERE #### Compute J_minus[i]. Inputs: "parameters_values, epsilon". Output = "J_minus[i]".### START CODE HERE ### (approx. 3 lines)thetaminus = np.copy(parameters_values)# Step 1thetaminus[i][0] -= epsilon# Step 2 J_minus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaminus)) # Step 3### END CODE HERE #### Compute gradapprox[i]### START CODE HERE ### (approx. 1 line)gradapprox[i] = (J_plus[i] - J_minus[i])/(2 * epsilon)### END CODE HERE #### Compare gradapprox to backward propagation gradients by computing difference.### START CODE HERE ### (approx. 1 line)numerator = np.linalg.norm(grad-gradapprox)# Step 1'denominator = np.linalg.norm(grad)+np.linalg.norm(gradapprox) # Step 2'difference = numerator/denominator # Step 3'### END CODE HERE ###if difference > 2e-7:print ("\033[93m" + "There is a mistake in the backward propagation! difference = " + str(difference) + "\033[0m")else:print ("\033[92m" + "Your backward propagation works perfectly fine! difference = " + str(difference) + "\033[0m")return difference

X, Y, parameters = gradient_check_n_test_case()cost, cache = forward_propagation_n(X, Y, parameters)gradients = backward_propagation_n(X, Y, cache)difference = gradient_check_n(parameters, gradients, X, Y)

[93mThere is a mistake in the backward propagation! difference = 0.2850931566540251[0m

Expected output:

It seems that there were errors in thebackward_propagation_ncode we gave you! Good that you’ve implemented the gradient check. Go back tobackward_propagationand try to find/correct the errors(Hint: check dW2 and db1). Rerun the gradient check when you think you’ve fixed it. Remember you’ll need to re-execute the cell definingbackward_propagation_n()if you modify the code.

Can you get gradient check to declare your derivative computation correct? Even though this part of the assignment isn’t graded, we strongly urge you to try to find the bug and re-run gradient check until you’re convinced backprop is now correctly implemented.

Note

Gradient Checking is slow! Approximating the gradient with ∂J∂θ≈J(θ+ε)−J(θ−ε)2ε\frac{\partial J}{\partial \theta} \approx \frac{J(\theta + \varepsilon) - J(\theta - \varepsilon)}{2 \varepsilon}∂θ∂J​≈2εJ(θ+ε)−J(θ−ε)​ is computationally costly. For this reason, we don’t run gradient checking at every iteration during training. Just a few times to check if the gradient is correct.Gradient Checking, at least as we’ve presented it, doesn’t work with dropout. You would usually run the gradient check algorithm without dropout to make sure your backprop is correct, then add dropout.

dropout和gradient checking不同时运行,先进行梯度检验,然后再dropout,为了保证在梯度检验时backward的正确

Congrats, you can be confident that your deep learning model for fraud detection is working correctly! You can even use this to convince your CEO. ?

**What you should remember from this notebook**: - Gradient checking verifies closeness between the gradients from backpropagation and the numerical approximation of the gradient (computed using forward propagation). - Gradient checking is slow, so we don't run it in every iteration of training. You would usually run it only to make sure your code is correct, then turn it off and use backprop for the actual learning process.

梯度检验运行特别慢,仅用来检查代码的正确定,当检验完毕,然后再使用dropout进行正则化

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。