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/Gradient_Checking.ipynb
Views: 34197
Gradient Checking
Welcome to the final assignment for this week! In this assignment you'll be implementing gradient checking.
By the end of this notebook, you'll be able to:
Implement gradient checking to verify the accuracy of your backprop implementation.
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.
2 - Problem Statement
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.
You already know that 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 proof that your backpropagation is actually working!" To give this reassurance, you are going to use "gradient checking."
Let's do it!
3 - 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."
You 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. Let's use equation (1) and a small value for to convince your CEO that your code for computing is correct!
4 - 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 1 - forward_propagation
Implement forward propagation
. For this simple function compute
J = 8
All tests passed.
dtheta = 2
All tests passed.
Exercise 3 - gradient_check
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.
Your backward propagation works perfectly fine! difference = 2.919335883291695e-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!
The following figure describes the forward and backward propagation of your fraud detection model.
Let's look at your implementations for forward propagation and backward propagation.
Now, run backward propagation.
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 Section 3 and 4, 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". The function "dictionary_to_vector()
" has been implemented 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.
The "gradients" dictionary has also been converted into a vector "grad" using gradients_to_vector(), so you don't need to worry about that.
Now, for every single parameter in your vector, you will apply the same procedure as for the gradient_check exercise. You will store each gradient approximation in a vector gradapprox
. If the check goes as expected, each value in this approximation must match the real gradient values stored in the grad
vector.
Note that grad
is calculated using the function gradients_to_vector
, which uses the gradients outputs of the backward_propagation_n
function.
Exercise 4 - gradient_check_n
Implement the function below.
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(
))
.
To compute
J_minus[i]
: do the same thing withCompute
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:
Note: Use np.linalg.norm
to get the norms
There is a mistake in the backward propagation! difference = 0.2850931567761623
Expected output:
There is a mistake in the backward propagation! | difference = 0.2850931567761623 |
It seems that there were errors in the backward_propagation_n
code! Good thing 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, you should try to find the bug and re-run gradient check until you're convinced backprop is now correctly implemented.
Notes
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! Now 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 you don't want to 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.