deeplearning.ai homework:Class 2 Week 1 3.Gradient Checking
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!
1 | # Packages |
1) How does gradient checking work?
Backpropagation computes the gradients , where denotes the parameters of the model. 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 correctly. Thus, you can use your code for computing to verify the code for computing .
Let’s look back at the definition of a derivative (or gradient):
If you’re not familiar with the “” notation, it’s just a way of saying “when is really really small.”
We know the following:
- is what you want to make sure you’re computing correctly.
- You can compute and (in the case that is a real number), since you’re confident your implementation for is correct.
Lets use equation (1) and a small value for to convince your CEO that your code for computing is correct!
2) 1-dimensional gradient checking
Consider a 1D linear function . The model contains only a single real-valued parameter , and takes as input.
You will implement code to compute and its derivative . You will then use gradient checking to make sure your derivative computation for is correct.
The diagram above shows the key computation steps: First start with , then evaluate the function (“forward propagation”). Then compute the derivative (“backward propagation”).
Exercise: implement “forward propagation” and “backward propagation” for this simple function. I.e., compute both (“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
Expected Output:
J | 8 |
Exercise: Now, implement the backward propagation step (derivative computation) of Figure 1. That is, compute the derivative of with respect to . To save you from doing the calculus, you should get .
1 | # GRADED FUNCTION: backward_propagation |
1 | x, theta = 2, 4 |
dtheta = 2
Expected Output:
dtheta | 2 |
Exercise: To show that the backward_propagation()
function is correctly computing the gradient , 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:
- 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:
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 ), 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.91933588329e-10
Expected Output:
The gradient is correct!
difference | 2.9193358103083e-10 |
Congrats, the difference is smaller than the 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 has more than a single 1D input. When you are training a neural network, actually consists of multiple matrices and biases ! 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.
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:
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.
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 to
- Calculate using to
forward_propagation_n(x, y, vector_to_dictionary(
))
.
- Set to
- To compute
J_minus[i]
: do the same thing with - Compute
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:
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.285093156776[0m
Expected output:
There is a mistake in the backward propagation! | difference = 0.285093156781 |
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). Rerun 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 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.