Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/main/deep-learning-specialization/course-2-deep-neural-network/Regularization.ipynb
Views: 34201
Regularization
Welcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity that overfitting can be a serious problem, if the training dataset is not big enough. Sure it does well on the training set, but the learned network doesn't generalize to new examples that it has never seen!
You will learn to: Use regularization in your deep learning models.
Let's get started!
Important Note on Submission to the AutoGrader
Before submitting your assignment to the AutoGrader, please make sure you are not doing the following:
You have not added any extra
print
statement(s) in the assignment.You have not added any extra code cell(s) in the assignment.
You have not changed any of the function parameters.
You are not using any global variables inside your graded exercises. Unless specifically instructed to do so, please refrain from it and use the local variables instead.
You are not changing the assignment code where it is not required, like creating extra variables.
If you do any of the following, you will get something like, Grader not found
(or similarly unexpected) error upon submitting your assignment. Before asking for help/debugging the errors in your assignment, check for these first. If this is the case, and you don't remember the changes you have made, you can get a fresh copy of the assignment by following these instructions.
Table of Contents
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.
They give you the following 2D dataset from France's past 10 games.
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.
4 - 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.
Let's train the model without any regularization, and observe the accuracy on the train/test sets.
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.
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.
5 - L2 Regularization
The standard way to avoid overfitting is called L2 regularization. It consists of appropriately modifying your cost function, from: To:
Let's modify your cost and observe the consequences.
Exercise 1 - compute_cost_with_regularization
Implement compute_cost_with_regularization()
which computes the cost given by formula (2). To calculate , use :
Note that you have to do this for , and , then sum the three terms and multiply by .
cost = 1.7864859451590758
All tests passed.
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 2 - backward_propagation_with_regularization
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 ().
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]]
All tests passed.
Let's now run the model with L2 regularization . The model()
function will call:
compute_cost_with_regularization
instead ofcompute_cost
backward_propagation_with_regularization
instead ofbackward_propagation
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.
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.
6 - Dropout
Finally, dropout is 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!
At each iteration, you shut down (= set to zero) each neuron of a layer with probability or keep it with probability (50% here). The dropped neurons don't contribute to the training in both the forward and backward propagations of the iteration.
layer: we shut down on average 40% of the neurons. 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.
6.1 - Forward Propagation with Dropout
Exercise 3 - forward_propagation_with_dropout
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 with the same shape as using
np.random.rand()
to randomly get numbers between 0 and 1. Here, you will use a vectorized implementation, so create a random matrix of the same dimension as .Set each entry of to be 1 with probability (
keep_prob
), and 0 otherwise.
Hint: Let's say that keep_prob = 0.8, which means that we want to keep about 80% of the neurons and drop out about 20% of them. We want to generate a vector that has 1's and 0's, where about 80% of them are 1 and about 20% are 0. This python statement:
X = (X < keep_prob).astype(int)
is conceptually the same as this if-else statement (for the simple case of a one-dimensional array) :
Note that the X = (X < keep_prob).astype(int)
works with multi-dimensional arrays, and the resulting output preserves the dimensions of the input array.
Also note that without using .astype(int)
, the result is an array of booleans True
and False
, which Python automatically converts to 1 and 0 if we multiply it with numbers. (However, it's better practice to convert data into the data type that we intend, so try using .astype(int)
.)
Set to . (You are shutting down some neurons). You can think of as a mask, so that when it is multiplied with another matrix, it shuts down some of the values.
Divide 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.)
A3 = [[0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]]
All tests passed.
6.2 - Backward Propagation with Dropout
Exercise 4 - backward_propagation_with_dropout
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 and 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 to
A1
. In backpropagation, you will have to shut down the same neurons, by reapplying the same mask todA1
.During forward propagation, you had divided
A1
bykeep_prob
. In backpropagation, you'll therefore have to dividedA1
bykeep_prob
again (the calculus interpretation is that if is scaled bykeep_prob
, then its derivative is also scaled by the samekeep_prob
).
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. ]]
All tests passed.
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 14% probability. The function model()
will now call:
forward_propagation_with_dropout
instead offorward_propagation
.backward_propagation_with_dropout
instead ofbackward_propagation
.
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.
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.
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.