Note
These are my personal programming assignments at the 1th week after studying the course Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimization and the copyright belongs to deeplearning.ai.
Part 1:Initialization
A well chosen initialization can:
- Speed up the convergence of gradient descent
- Increase 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.
1 | import numpy as np |
There are some import function:
1 | def sigmoid(x): |
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 – setting initialization = “zeros” in the input argument.
- Random initialization – setting initialization = “random” in the input argument. This initializes the weights to large random values.
- He initialization – setting initialization = “he” in the input argument. This initializes the weights to random values scaled according to a paper by He et al., 2015.
Instructions: Please quickly read over the code below, and run it. In the next part you will implement the three initialization methods that this model()
calls.
1 | def model(X, Y, learning_rate = 0.01, num_iterations = 15000, print_cost = True, initialization = "he"): |
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]})$
- the bias vectors $(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.
1 | # GRADED FUNCTION: initialize_parameters_zeros |
1 | parameters = initialize_parameters_zeros([3,2,1]); |
W1 = [[0. 0. 0.]
[0. 0. 0.]]
b1 = [[0.]
[0.]]
W2 = [[0. 0.]]
b2 = [[0.]]
Run the following code to train your model on 15,000 iterations using zeros initialization.
1 | parameters = model(train_X, train_Y, initialization = "zeros"); |
Cost after iteration 0: 0.6931471805599453
Cost after iteration 1000: 0.6931471805599453
Cost after iteration 2000: 0.6931471805599453
Cost after iteration 3000: 0.6931471805599453
Cost after iteration 4000: 0.6931471805599453
Cost after iteration 5000: 0.6931471805599453
Cost after iteration 6000: 0.6931471805599453
Cost after iteration 7000: 0.6931471805599453
Cost after iteration 8000: 0.6931471805599453
Cost after iteration 9000: 0.6931471805599453
Cost after iteration 10000: 0.6931471805599455
Cost after iteration 11000: 0.6931471805599453
Cost after iteration 12000: 0.6931471805599453
Cost after iteration 13000: 0.6931471805599453
Cost after iteration 14000: 0.6931471805599453
On the train set:
Accuracy: 0.5
On 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:
1 | print ("predictions_train = " + str(predictions_train)); |
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 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 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 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 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 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 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 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 0 0 0 0 0 0 0 0
0 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 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 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]]
1 | plt.title("Model with Zeros initialization"); |
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]} = 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.
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. Use np.random.randn(...) * 10
for weights and np.zeros((...))
for biases. We are using a fixed np.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.
1 | # GRADED FUNCTION: initialize_parameters_random |
1 | parameters = initialize_parameters_random([3, 2, 1]); |
W1 = [[ 17.88628473 4.36509851 0.96497468]
[-18.63492703 -2.77388203 -3.54758979]]
b1 = [[0.]
[0.]]
W2 = [[-0.82741481 -6.27000677]]
b2 = [[0.]]
Run the following code to train your model on 15,000 iterations using random initialization.
1 | parameters = model(train_X, train_Y, initialization = "random"); |
Cost after iteration 0: inf
C:\Anaconda3\lib\site-packages\ipykernel\__main__.py:44: RuntimeWarning: divide by zero encountered in log
C:\Anaconda3\lib\site-packages\ipykernel\__main__.py:44: RuntimeWarning: invalid value encountered in multiply
Cost after iteration 1000: 0.6243339944795463
Cost after iteration 2000: 0.5983698376976234
Cost after iteration 3000: 0.5640713641303857
Cost after iteration 4000: 0.5502225777263651
Cost after iteration 5000: 0.5445189912897229
Cost after iteration 6000: 0.5374939942050982
Cost after iteration 7000: 0.47927872911735586
Cost after iteration 8000: 0.39787508336662053
Cost after iteration 9000: 0.3934925383461005
Cost after iteration 10000: 0.3920373161708829
Cost after iteration 11000: 0.38930570830972355
Cost after iteration 12000: 0.3861562072516527
Cost after iteration 13000: 0.38499595295812233
Cost after iteration 14000: 0.38280923039736164
On the train set:
Accuracy: 0.83
On 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.
1 | print (predictions_train); |
[[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 1
1 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 0
0 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 0
1 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 0
0 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 1
1 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 1
0 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 1
1 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 1
1 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 1
0 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 0
1 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]]
1 | plt.title("Model with large random initialization"); |
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)$, 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., 2015. (If you have heard of “Xavier initialization”, this is similar except Xavier initialization uses a scaling factor for the weights $W^{[l]}$ of sqrt(1./layers_dims[l-1])
where He initialization would use sqrt(2./layers_dims[l-1])
.)
Exercise:
Implement the following function to initialize your parameters with He initialization.
Hint:
This function is similar to the previous initialize_parameters_random()
. The only difference is that instead of multiplying np.random.randn(..,..)
by 10, you will multiply it by 2dimension of the previous layer $\sqrt{\frac{2}{\text{dimension of the previous layer}}}$, which is what He initialization recommends for layers with a ReLU activation.
1 | # GRADED FUNCTION: initialize_parameters_he |
1 | parameters = initialize_parameters_he([2, 4, 1]); |
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.]]
Run the following code to train your model on 15,000 iterations using He initialization.
1 | parameters = model(train_X, train_Y, initialization = "he"); |
Cost after iteration 0: 0.8830537463419761
Cost after iteration 1000: 0.6879825919728063
Cost after iteration 2000: 0.6751286264523371
Cost after iteration 3000: 0.6526117768893807
Cost after iteration 4000: 0.6082958970572938
Cost after iteration 5000: 0.5304944491717495
Cost after iteration 6000: 0.4138645817071795
Cost after iteration 7000: 0.31178034648444414
Cost after iteration 8000: 0.23696215330322562
Cost after iteration 9000: 0.18597287209206836
Cost after iteration 10000: 0.15015556280371808
Cost after iteration 11000: 0.12325079292273551
Cost after iteration 12000: 0.09917746546525934
Cost after iteration 13000: 0.08457055954024277
Cost after iteration 14000: 0.07357895962677363
On the train set:
Accuracy: 0.9933333333333333
On the test set:
Accuracy: 0.96
1 | plt.title("Model with He initialization"); |
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:
comparison is:
Model | Train accuracy | Problem/Comment |
---|---|---|
3-layer NN with zeros initialization | 50% | fails to break symmetry |
3-layer NN with large random initialization | 83% | too large weights |
3-layer NN with He initialization | 99% | recommended method |
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.
Part 2:Regularization
Let’s first import the packages you are going to use.
1 | # import packages |
C:\Anaconda3\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
There are some function imported:
1 | def initialize_parameters(layer_dims): |
<ipython-input-2-41dc022e1c22>:27: SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert(parameters['W' + str(l)].shape == layer_dims[l], layer_dims[l-1])
<ipython-input-2-41dc022e1c22>:28: SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert(parameters['W' + str(l)].shape == layer_dims[l], 1)
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.
$$\text{Figure 1 : Football field}$$
$$\text{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.
1 | train_X, train_Y, test_X, test_Y = load_2D_dataset(); |
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 head
- If 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:
- in regularization mode – by setting the lambd input to a non-zero value. We use “lambd” instead of “lambda” because “lambda” is a reserved keyword in Python.
- in dropout mode – by setting the keep_prob to 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.
1 | def model(X, Y, learning_rate = 0.3, num_iterations = 30000, print_cost = True, lambd = 0, keep_prob = 1): |
Let’s train the model without any regularization, and observe the accuracy on the train/test sets.
1 | parameters = model(train_X, train_Y) |
Cost after iteration 0: 0.6557412523481002
Cost after iteration 10000: 0.16329987525724218
Cost after iteration 20000: 0.13851642423267105
On the training set:
Accuracy: 0.9478672985781991
On the test set:
Accuracy: 0.915
The train accuracy is 94.8% while the test accuracy is 91.5%. This is the baseline model (you will observe the impact of regularization on this model). Run the following code to plot the decision boundary of your model.
1 | plt.title("Model without regularization") |
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 called L2 regularization. It consists of appropriately modifying your cost function, from:
$$J = -\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{L}\right) + (1-y^{(i)})\log\left(1- a^{L}\right) \large{)} \tag{1}$$
to:
$$J_{regularized} = \small \underbrace{-\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{L}\right) + (1-y^{(i)})\log\left(1- a^{L}\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}$$
Let’s modify your cost and observe the consequences.
Exercise: Implement compute_cost_with_regularization()
which computes the cost given by formula (2). To calculate $\sum\limits_k\sum\limits_j W_{k,j}^{[l]2}$, use : np.sum(np.square(Wl))
Note that you have to do this for $W^{[1]}$, $W^{[2]}$ and $W^{[3]}$, then sum the three terms and multiply by $\frac{1}{m}\frac{\lambda}{2}$.
1 | # GRADED FUNCTION: compute_cost_with_regularization |
1 | A3, Y_assess, parameters = compute_cost_with_regularization_test_case(); |
cost = 1.7864859451590758
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 $(\frac{d}{dW} ( \frac{1}{2}\frac{\lambda}{m} W^2) = \frac{\lambda}{m} W)$
1 | # GRADED FUNCTION: backward_propagation_with_regularization |
1 | X_assess, Y_assess, cache = backward_propagation_with_regularization_test_case() |
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]]
Let’s now run the model with L2 regularization $(λ=0.7)$. The model()
function will call:
compute_cost_with_regularization
instead ofcompute_cost
backward_propagation_with_regularization
instead ofbackward_propagation
1 | parameters = model(train_X, train_Y, lambd = 0.7); |
Cost after iteration 0: 0.6974484493131264
Cost after iteration 10000: 0.2684918873282239
Cost after iteration 20000: 0.26809163371273004
On the train set:
Accuracy: 0.9383886255924171
On 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.
1 | plt.title("Model with L2-regularization"); |
Observations:
- The value of $λ$ is a hyperparameter that you can tune using a dev set.
- L2 regularization makes your decision boundary smoother. If $λ$ 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, dropout is a widely used regularization technique that is specific to deep learning.
It randomly shuts down some neurons in each iteration.
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]}$ with the same shape as $a^{[1]}$ using
np.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]}{(1)}d^{[1]}{(2)}…d^{[1]}_{(m)}]$ of the same dimension as $A^{[1]}$.Set each entry of $D^{[1]}$ to be 0 with probability (
1 - keep_prob
) or 1 with probability (keep_prob
), by thresholding values in $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]}$ to $A^{[1]}∗ D^{[1]}$. (You are shutting down some neurons). You can think of $D^{[1]}$ as a mask, so that when it is multiplied with another matrix, it shuts down some of the values.
Divide $A^{[1]}$ by
keep_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.)
1 | # GRADED FUNCTION: forward_propagation_with_dropout |
1 | X_assess, parameters = forward_propagation_with_dropout_test_case(); |
A3 = [[0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]]
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]}$ and $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]}$ to A1. In backpropagation, you will have to shut down the same neurons, by reapplying the same mask $D^{[1]}$ to dA1.
- During forward propagation, you had divided A1 by
keep_prob
. In backpropagation, you’ll therefore have to divide dA1 bykeep_prob
again (the calculus interpretation is that if $A^{[1]}$ is scaled bykeep_prob
, then its derivative $dA^{[1]}$ is also scaled by the samekeep_prob
).
1 | # GRADED FUNCTION: backward_propagation_with_dropout |
1 | X_assess, Y_assess, cache = backward_propagation_with_dropout_test_case(); |
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. ]]
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 function model()
will now call:
forward_propagation_with_dropout
instead offorward_propagation
.backward_propagation_with_dropout
instead ofbackward_propagation
.
1 | parameters = model(train_X, train_Y, keep_prob = 0.86, learning_rate = 0.3); |
Cost after iteration 0: 0.6543912405149825
C:\Anaconda3\lib\site-packages\ipykernel\__main__.py:47: RuntimeWarning: divide by zero encountered in log
C:\Anaconda3\lib\site-packages\ipykernel\__main__.py:47: RuntimeWarning: invalid value encountered in multiply
Cost after iteration 10000: 0.061016986574905584
Cost after iteration 20000: 0.060582435798513114
On the train set:
Accuracy: 0.9289099526066351
On 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.
1 | plt.title("Model with dropout"); |
Note:
- A common mistake when using dropout is to use it both in training and testing. You should use dropout (randomly eliminate nodes) only in training.
- 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:
model | train accuracy | test accuracy |
---|---|---|
3-layer NN without regularization | 95% | 91.5% |
3-layer NN with L2-regularization | 94% | 93% |
3-layer NN with dropout | 93% | 95% |
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.
Part 3: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!
First import the libs which you will need.
1 | # Packages |
1. How does gradient checking work?
Backpropagation computes the gradients $\frac{∂J}{∂θ}$ , where $θ$ denotes the parameters of the model. $J$ 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 $J$ correctly. Thus, you can use your code for computing $J$ to verify the code for computing $\frac{∂J}{∂θ}$.
Let’s look back at the definition of a derivative (or gradient):
$$\frac{\partial J}{\partial \theta} = \lim_{\varepsilon \to 0} \frac{J(\theta + \varepsilon) - J(\theta - \varepsilon)}{2 \varepsilon} \tag{1}$$
If you’re not familiar with the “$limε→0$” notation, it’s just a way of saying “when $ε$ is really really small.”
We know the following:
$\frac{∂J}{∂θ}$ is what you want to make sure you’re computing correctly.
You can compute $J(θ+ε)$ and $J(θ−ε)$ (in the case that $θ$ is a real number), since you’re confident your implementation for $J$ is correct.
Lets use equation (1) and a small value for $ε$ to convince your CEO that your code for computing $\frac{∂J}{∂θ}$ is correct!
2. 1-dimensional gradient checking
Consider a 1D linear function $J(θ)=θx$. The model contains only a single real-valued parameter $θ$, and takes $x$ as input.
You will implement code to compute $J(.)$ and its derivative $\frac{∂J}{∂θ}$. You will then use gradient checking to make sure your derivative computation for $J$ is correct.
$$\text{Figure 1 : 1D linear model}$$
The diagram above shows the key computation steps: First start with $x$, then evaluate the function $J(x)$ (“forward propagation”). Then compute the derivative $\frac{∂J}{∂θ}$ (“backward propagation”).
Exercise: implement “forward propagation
” and “backward propagation
” for this simple function. I.e., compute both $J(.)$ (“forward propagation
”) and its derivative with respect to $θ$ (“backward propagation
”), in two separate functions.
1 | # GRADED FUNCTION: forward_propagation |
1 | x, theta = 2, 4 |
J = 8
Exercise: Now, implement the backward propagation step (derivative computation) of Figure 1. That is, compute the derivative of $J(θ)=θx$ with respect to $θ$. To save you from doing the calculus, you should get $d\theta=\frac{∂J}{∂θ}=x$.
1 | # GRADED FUNCTION: backward_propagation |
1 | x, theta = 2, 4 |
dtheta = 2
Exercise: To show that the backward_propagation()
function is correctly computing the gradient $\frac{∂J}{∂θ}$, let’s implement gradient checking.
Instructions:
- First compute “
gradapprox
” using the formula above (1) and a small value of $ε$. Here are the Steps to follow:- $\theta^+ = \theta + \epsilon$
- $\theta^- = \theta - \epsilon$
- $J^+ = J(\theta^+)$
- $J^- = J(\theta^-)$
- $gradapprox=\frac{J^+-J^-}{2\epsilon}$
- 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:
$$difference = \frac {\mid\mid grad - gradapprox \mid\mid_2}{\mid\mid grad \mid\mid_2 + \mid\mid gradapprox \mid\mid_2} \tag{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−7), you can be quite confident that you have computed your gradient correctly. Otherwise, there may be a mistake in the gradient computation.
1 | # GRADED FUNCTION: gradient_check |
1 | x, theta = 2, 4 |
The gradient is correct!
difference = 2.919335883291695e-10
Congrats, the difference is smaller than the $10^{−7}$ threshold. So you can have high confidence that you’ve correctly computed the gradient in backward_propagation()
.
Now, in the more general case, your cost function $J$ has more than a single 1D input. When you are training a neural network, $θ$ actually consists of multiple matrices $W^{[l]}$ and biases $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.
$$\text{Figure 2 : deep neural network} \ LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID$$
Let’s look at your implementations for forward propagation and backward propagation.
1 | def forward_propagation_n(X, Y, parameters): |
Now, run backward propagation.
1 | def backward_propagation_n(X, Y, cache): |
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:
$$\frac{\partial J}{\partial \theta} = \lim_{\varepsilon \to 0} \frac{J(\theta + \varepsilon) - J(\theta - \varepsilon)}{2 \varepsilon} \tag{1}$$
However, $θ$ 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.
$$\text{Figure 2 : dictionary_to_vector() and vector_to_dictionary()} \ \text{ 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 compute
J_plus[i]
:- Set $θ^+$ to
np.copy(parameters_values)
- Set $θ^+_i$ to $θ^+_i+ε$
- Calculate $J^+_i$ using to
forward_propagation_n(x, y, vector_to_dictionary(theta_plus))
.
- Set $θ^+$ to
- To compute
J_minus[i]
: do the same thing with $θ^−$ - Compute
gradapprox[i]
=$\frac{J^+_i−J^-_i}{2ε}$
Thus, you get a vector gradapprox, where gradapprox[i]
is an approximation of the gradient with respect to parameter_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:
$$difference = \frac {| grad - gradapprox |_2}{| grad |_2 + | gradapprox |_2 } \tag{2}$$
1 | # GRADED FUNCTION: gradient_check_n |
1 | X, Y, parameters = gradient_check_n_test_case() |
[93mThere is a mistake in the backward propagation! difference = 0.28509315678069896[0m
It seems that there were errors in the backward_propagation_n
code we gave you! Good that you’ve implemented the gradient check. Go back to backward_propagation and try to find/correct the errors (Hint: check dW2 and db1). Return the gradient check when you think you’ve fixed it. Remember you’ll need to re-execute the cell defining backward_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 $\frac{∂J}{∂θ}≈\frac{J(θ+ε)−J(θ−ε)}{2ε}$ 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.
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.