Abstract
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! This article will use regularization in our deep learning models.
Implement
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.
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
Our 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.
I will first try a nonregularized model. Then I will show you how to regularize it and decide which model we will choose to solve the French Football Corporation’s problem.
Nonregularized model
I will use the following neural network. This model can be used:
 in regularization mode — by setting the
lambd
input to a nonzero 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
I will first try the model without any regularization. Then, I 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, I will run this model with the correct inputs so that it calls the functions I’ve implemented:
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) 
Output:
Cost after iteration 0: 0.6557412523481002
Cost after iteration 10000: 0.16329987525724216
Cost after iteration 20000: 0.13851642423255986
On the training set:
Accuracy: 0.947867298578
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 (I will observe the impact of regularization on this model).
The nonregularized model is obviously overfitting the training set. It is fitting the noisy points! Lets now look at two techniques to reduce overfitting.
L2 Regularization
The standard way to avoid overfitting is called L2 regularization. It consists of appropriately modifying our cost function, from:
To:
Let’s modify out cost and observe the consequences.
compute_cost_with_regularization
I will implement compute_cost_with_regularization()
which computes the cost given by formula (2). To calculate $\sum\limitsk\sum\limits_j W{k,j}^{[l]2}$ , I will use np.sum(np.square(Wl))
1  def compute_cost_with_regularization(A3, Y, parameters, lambd): 
Of course, because I changed the cost, we have to change backward propagation as well! All the gradients have to be computed with respect to this new cost.
I will implement the changes needed in backward propagation to take into account regularization. The changes only concern dW1, dW2 and dW3. For each, we have to add the regularization term’s gradient ($\frac{d}{dW} ( \frac{1}{2}\frac{\lambda}{m} W^2) = \frac{\lambda}{m} W$).
1 

Let’s now run the model with L2 regularization $(\lambda = 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.2680916337127301
Congrats, the test set accuracy increased to 93%. We have saved the French football team!
Observations
 The value of $\lambda$ is a hyperparameter that we can tune using a dev set.
 L2 regularization makes our decision boundary smoother. If $\lambda$ is too large, it is also possible to “oversmooth”, resulting in a model with high bias.
What is L2regularization actually doing?
L2regularization 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 L2regularization 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.
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, we 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.
When we shut some neurons down, we actually modify our model. The idea behind dropout is that at each iteration, we train a different model that uses only a subset of our neurons. With dropout, our neurons thus become less sensitive to the activation of one other specific neuron, because that other neuron might be shut down at any time.
Forward propagation with dropout
I will implement the forward propagation with dropout. I am 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:
I would like to shut down some neurons in the first and second layers. To do that, I am 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, I 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]}$.  Set each entry of $D^{[1]}$ to be 0 with probability (
1keep_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) I 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]}$. (I am shutting down some neurons). We 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 I am assuring that the result of the cost will still have the same expected value as without dropout. (This technique is also called inverted dropout.)
1 

Backward propagation with dropout
I will implement the backward propagation with dropout. As before, I am 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. I will have to carry out 2 Steps:
 I had previously shut down some neurons during forward propagation, by applying a mask $D^{[1]}$ to
A1
. In backpropagation, I will have to shut down the same neurons, by reapplying the same mask $D^{[1]}$ todA1
.  During forward propagation, I had divided
A1
bykeep_prob
. In backpropagation, I’ll therefore have to dividedA1
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 

Let’s now run the model with dropout (keep_prob = 0.86
). It means at every iteration I 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
.
1  parameters = model(train_X, train_Y, keep_prob = 0.86, learning_rate = 0.3) 
Output:
Cost after iteration 0: 0.6543912405149825
Cost after iteration 10000: 0.06101698657490559
Cost after iteration 20000: 0.060582435798513114
On the train set:
Accuracy: 0.928909952607
On the test set:
Accuracy: 0.95
Dropout works great! The test accuracy has increased again (to 95%)! Our 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 we!
Note
 A common mistake when using dropout is to use it both in training and testing. We 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——we will soon learn some of these frameworks.
What you should remember about dropout:Dropout is a regularization technique.
 We 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. We can check that this works even when keep_prob is other values than 0.5.
Conclusions
Here are the results of our three models:
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.
What we want you to remember from this article:
 Regularization will help we reduce overfitting.
 Regularization will drive our weights to lower values.
 L2 regularization and Dropout are two very effective regularization techniques.