├── .DS_Store ├── README.md ├── week-1 ├── Gradient_Checking.ipynb ├── Initialization.ipynb ├── Quiz-1.pdf └── Regularization.ipynb ├── week-2 ├── Optimization_methods.ipynb └── Quiz-2.pdf └── week-3 ├── Quiz3.pdf └── Tensorflow_introduction.ipynb /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jialincheoh/coursera-improving-deep-neural-networks/9f73fba63edcf59f1e0d013c42211ee1eba578e1/.DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coursera Improving Deep Neural Networks: Hyperparameter Tuning, Regularization and Optimization 2 | 3 | ## My Certificate 4 | 5 | https://coursera.org/share/e655dda9576bd4140383c8bd1beec99a 6 | 7 | Screenshot 2021-08-13 at 2 16 16 PM 8 | 9 | ## Projects Completed 10 | 11 | - Initialization 12 | 13 | - Regularization 14 | 15 | - Gradient Checking 16 | 17 | - Optimization Methods 18 | 19 | - TensorFlow Introduction 20 | 21 | -------------------------------------------------------------------------------- /week-1/Gradient_Checking.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Gradient Checking\n", 8 | "\n", 9 | "Welcome to the final assignment for this week! In this assignment you'll be implementing gradient checking.\n", 10 | "\n", 11 | "By the end of this notebook, you'll be able to:\n", 12 | "\n", 13 | "Implement gradient checking to verify the accuracy of your backprop implementation" 14 | ] 15 | }, 16 | { 17 | "cell_type": "markdown", 18 | "metadata": {}, 19 | "source": [ 20 | "## Table of Contents\n", 21 | "- [1 - Packages](#1)\n", 22 | "- [2 - Problem Statement](#2)\n", 23 | "- [3 - How does Gradient Checking work?](#3)\n", 24 | "- [4 - 1-Dimensional Gradient Checking](#4)\n", 25 | " - [Exercise 1 - forward_propagation](#ex-1)\n", 26 | " - [Exercise 2 - backward_propagation](#ex-2)\n", 27 | " - [Exercise 3 - gradient_check](#ex-3)\n", 28 | "- [5 - N-Dimensional Gradient Checking](#5)\n", 29 | " - [Exercise 4 - gradient_check_n](#ex-4)" 30 | ] 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "metadata": {}, 35 | "source": [ 36 | "\n", 37 | "## 1 - Packages" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 1, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "import numpy as np\n", 47 | "from testCases import *\n", 48 | "from public_tests import *\n", 49 | "from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector\n", 50 | "\n", 51 | "%load_ext autoreload\n", 52 | "%autoreload 2" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "\n", 60 | "## 2 - Problem Statement\n", 61 | "\n", 62 | "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.\n", 63 | "\n", 64 | "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.\"\n", 65 | "\n", 66 | "Let's do it!" 67 | ] 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "metadata": {}, 72 | "source": [ 73 | "\n", 74 | "## 3 - How does Gradient Checking work?\n", 75 | "Backpropagation computes the gradients $\\frac{\\partial J}{\\partial \\theta}$, where $\\theta$ denotes the parameters of the model. $J$ is computed using forward propagation and your loss function.\n", 76 | "\n", 77 | "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{\\partial J}{\\partial \\theta}$.\n", 78 | "\n", 79 | "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} $$\n", 80 | "\n", 81 | "If you're not familiar with the \"$\\displaystyle \\lim_{\\varepsilon \\to 0}$\" notation, it's just a way of saying \"when $\\varepsilon$ is really, really small.\"\n", 82 | "\n", 83 | "You know the following:\n", 84 | "\n", 85 | "$\\frac{\\partial J}{\\partial \\theta}$ is what you want to make sure you're computing correctly.\n", 86 | "You can compute $J(\\theta + \\varepsilon)$ and $J(\\theta - \\varepsilon)$ (in the case that $\\theta$ is a real number), since you're confident your implementation for $J$ is correct.\n", 87 | "Let's use equation (1) and a small value for $\\varepsilon$ to convince your CEO that your code for computing $\\frac{\\partial J}{\\partial \\theta}$ is correct!" 88 | ] 89 | }, 90 | { 91 | "cell_type": "markdown", 92 | "metadata": {}, 93 | "source": [ 94 | "\n", 95 | "## 4 - 1-Dimensional Gradient Checking\n", 96 | "\n", 97 | "Consider a 1D linear function $J(\\theta) = \\theta x$. The model contains only a single real-valued parameter $\\theta$, and takes $x$ as input.\n", 98 | "\n", 99 | "You will implement code to compute $J(.)$ and its derivative $\\frac{\\partial J}{\\partial \\theta}$. You will then use gradient checking to make sure your derivative computation for $J$ is correct. \n", 100 | "\n", 101 | "\n", 102 | "
Figure 1:1D linear model
\n", 103 | "\n", 104 | "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{\\partial J}{\\partial \\theta}$ (\"backward propagation\"). \n", 105 | "\n", 106 | "\n", 107 | "### Exercise 1 - forward_propagation\n", 108 | "\n", 109 | "Implement `forward propagation`. For this simple function compute $J(.)$" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": 2, 115 | "metadata": { 116 | "deletable": false, 117 | "nbgrader": { 118 | "cell_type": "code", 119 | "checksum": "0f934d7a5ec9e6a41fc9ece5ec6a07fa", 120 | "grade": false, 121 | "grade_id": "cell-a4be88c5c0419ab7", 122 | "locked": false, 123 | "schema_version": 3, 124 | "solution": true, 125 | "task": false 126 | } 127 | }, 128 | "outputs": [], 129 | "source": [ 130 | "# GRADED FUNCTION: forward_propagation\n", 131 | "\n", 132 | "def forward_propagation(x, theta):\n", 133 | " \"\"\"\n", 134 | " Implement the linear forward propagation (compute J) presented in Figure 1 (J(theta) = theta * x)\n", 135 | " \n", 136 | " Arguments:\n", 137 | " x -- a real-valued input\n", 138 | " theta -- our parameter, a real number as well\n", 139 | " \n", 140 | " Returns:\n", 141 | " J -- the value of function J, computed using the formula J(theta) = theta * x\n", 142 | " \"\"\"\n", 143 | " \n", 144 | " # (approx. 1 line)\n", 145 | " J = theta * x\n", 146 | " # YOUR CODE STARTS HERE\n", 147 | " \n", 148 | " \n", 149 | " # YOUR CODE ENDS HERE\n", 150 | " \n", 151 | " return J" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": 3, 157 | "metadata": { 158 | "deletable": false, 159 | "editable": false, 160 | "nbgrader": { 161 | "cell_type": "code", 162 | "checksum": "c775107f8d8491592913f1991d0fc3da", 163 | "grade": true, 164 | "grade_id": "cell-805a7fd19d554221", 165 | "locked": true, 166 | "points": 10, 167 | "schema_version": 3, 168 | "solution": false, 169 | "task": false 170 | } 171 | }, 172 | "outputs": [ 173 | { 174 | "name": "stdout", 175 | "output_type": "stream", 176 | "text": [ 177 | "J = 8\n", 178 | "\u001b[92m All tests passed.\n" 179 | ] 180 | } 181 | ], 182 | "source": [ 183 | "x, theta = 2, 4\n", 184 | "J = forward_propagation(x, theta)\n", 185 | "print (\"J = \" + str(J))\n", 186 | "forward_propagation_test(forward_propagation)" 187 | ] 188 | }, 189 | { 190 | "cell_type": "markdown", 191 | "metadata": {}, 192 | "source": [ 193 | "\n", 194 | "### Exercise 2 - backward_propagation\n", 195 | "\n", 196 | "Now, implement the `backward propagation` step (derivative computation) of Figure 1. That is, compute the derivative of $J(\\theta) = \\theta x$ with respect to $\\theta$. To save you from doing the calculus, you should get $dtheta = \\frac { \\partial J }{ \\partial \\theta} = x$." 197 | ] 198 | }, 199 | { 200 | "cell_type": "code", 201 | "execution_count": 4, 202 | "metadata": { 203 | "deletable": false, 204 | "nbgrader": { 205 | "cell_type": "code", 206 | "checksum": "7315e45824efc41770654b46c64c1c14", 207 | "grade": false, 208 | "grade_id": "cell-c06a1275399b210f", 209 | "locked": false, 210 | "schema_version": 3, 211 | "solution": true, 212 | "task": false 213 | } 214 | }, 215 | "outputs": [], 216 | "source": [ 217 | "# GRADED FUNCTION: backward_propagation\n", 218 | "\n", 219 | "def backward_propagation(x, theta):\n", 220 | " \"\"\"\n", 221 | " Computes the derivative of J with respect to theta (see Figure 1).\n", 222 | " \n", 223 | " Arguments:\n", 224 | " x -- a real-valued input\n", 225 | " theta -- our parameter, a real number as well\n", 226 | " \n", 227 | " Returns:\n", 228 | " dtheta -- the gradient of the cost with respect to theta\n", 229 | " \"\"\"\n", 230 | " \n", 231 | " # (approx. 1 line)\n", 232 | " dtheta = x\n", 233 | " # YOUR CODE STARTS HERE\n", 234 | " \n", 235 | " \n", 236 | " # YOUR CODE ENDS HERE\n", 237 | " \n", 238 | " return dtheta" 239 | ] 240 | }, 241 | { 242 | "cell_type": "code", 243 | "execution_count": 5, 244 | "metadata": { 245 | "deletable": false, 246 | "editable": false, 247 | "nbgrader": { 248 | "cell_type": "code", 249 | "checksum": "79ac4ec84141d381d3f9fffccc19b723", 250 | "grade": true, 251 | "grade_id": "cell-7b67ed84ac8bfd91", 252 | "locked": true, 253 | "points": 10, 254 | "schema_version": 3, 255 | "solution": false, 256 | "task": false 257 | } 258 | }, 259 | "outputs": [ 260 | { 261 | "name": "stdout", 262 | "output_type": "stream", 263 | "text": [ 264 | "dtheta = 2\n", 265 | "\u001b[92m All tests passed.\n" 266 | ] 267 | } 268 | ], 269 | "source": [ 270 | "x, theta = 2, 4\n", 271 | "dtheta = backward_propagation(x, theta)\n", 272 | "print (\"dtheta = \" + str(dtheta))\n", 273 | "backward_propagation_test(backward_propagation)" 274 | ] 275 | }, 276 | { 277 | "cell_type": "markdown", 278 | "metadata": {}, 279 | "source": [ 280 | "\n", 281 | "### Exercise 3 - gradient_check\n", 282 | "\n", 283 | "To show that the `backward_propagation()` function is correctly computing the gradient $\\frac{\\partial J}{\\partial \\theta}$, let's implement gradient checking.\n", 284 | "\n", 285 | "**Instructions**:\n", 286 | "- First compute \"gradapprox\" using the formula above (1) and a small value of $\\varepsilon$. Here are the Steps to follow:\n", 287 | " 1. $\\theta^{+} = \\theta + \\varepsilon$\n", 288 | " 2. $\\theta^{-} = \\theta - \\varepsilon$\n", 289 | " 3. $J^{+} = J(\\theta^{+})$\n", 290 | " 4. $J^{-} = J(\\theta^{-})$\n", 291 | " 5. $gradapprox = \\frac{J^{+} - J^{-}}{2 \\varepsilon}$\n", 292 | "- Then compute the gradient using backward propagation, and store the result in a variable \"grad\"\n", 293 | "- Finally, compute the relative difference between \"gradapprox\" and the \"grad\" using the following formula:\n", 294 | "$$ difference = \\frac {\\mid\\mid grad - gradapprox \\mid\\mid_2}{\\mid\\mid grad \\mid\\mid_2 + \\mid\\mid gradapprox \\mid\\mid_2} \\tag{2}$$\n", 295 | "You will need 3 Steps to compute this formula:\n", 296 | " - 1'. compute the numerator using np.linalg.norm(...)\n", 297 | " - 2'. compute the denominator. You will need to call np.linalg.norm(...) twice.\n", 298 | " - 3'. divide them.\n", 299 | "- 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. \n" 300 | ] 301 | }, 302 | { 303 | "cell_type": "code", 304 | "execution_count": 6, 305 | "metadata": { 306 | "deletable": false, 307 | "nbgrader": { 308 | "cell_type": "code", 309 | "checksum": "5545d5ca718b8580e72da217b49516ae", 310 | "grade": false, 311 | "grade_id": "cell-ed57ede577f9d607", 312 | "locked": false, 313 | "schema_version": 3, 314 | "solution": true, 315 | "task": false 316 | } 317 | }, 318 | "outputs": [], 319 | "source": [ 320 | "# GRADED FUNCTION: gradient_check\n", 321 | "\n", 322 | "def gradient_check(x, theta, epsilon=1e-7, print_msg=False):\n", 323 | " \"\"\"\n", 324 | " Implement the backward propagation presented in Figure 1.\n", 325 | " \n", 326 | " Arguments:\n", 327 | " x -- a float input\n", 328 | " theta -- our parameter, a float as well\n", 329 | " epsilon -- tiny shift to the input to compute approximated gradient with formula(1)\n", 330 | " \n", 331 | " Returns:\n", 332 | " difference -- difference (2) between the approximated gradient and the backward propagation gradient. Float output\n", 333 | " \"\"\"\n", 334 | " \n", 335 | " # Compute gradapprox using left side of formula (1). epsilon is small enough, you don't need to worry about the limit.\n", 336 | " # (approx. 5 lines)\n", 337 | " theta_plus = theta + epsilon # Step 1\n", 338 | " theta_minus = theta - epsilon # Step 2\n", 339 | " J_plus = forward_propagation(x, theta_plus) # Step 3\n", 340 | " J_minus = forward_propagation(x, theta_minus) # Step 4\n", 341 | " gradapprox = ( J_plus - J_minus ) / ( 2 * epsilon ) # Step 5\n", 342 | " # YOUR CODE STARTS HERE\n", 343 | " \n", 344 | " \n", 345 | " # YOUR CODE ENDS HERE\n", 346 | " \n", 347 | " # Check if gradapprox is close enough to the output of backward_propagation()\n", 348 | " #(approx. 1 line) DO NOT USE \"grad = gradapprox\"\n", 349 | " grad = backward_propagation(x, theta)\n", 350 | " # YOUR CODE STARTS HERE\n", 351 | " \n", 352 | " \n", 353 | " # YOUR CODE ENDS HERE\n", 354 | " \n", 355 | " #(approx. 1 line)\n", 356 | " numerator = np.linalg.norm(grad - gradapprox) # Step 1'\n", 357 | " denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) # Step 2'\n", 358 | " difference = numerator / denominator # Step 3'\n", 359 | " # YOUR CODE STARTS HERE\n", 360 | " \n", 361 | " \n", 362 | " # YOUR CODE ENDS HERE\n", 363 | " if print_msg:\n", 364 | " if difference > 2e-7:\n", 365 | " print (\"\\033[93m\" + \"There is a mistake in the backward propagation! difference = \" + str(difference) + \"\\033[0m\")\n", 366 | " else:\n", 367 | " print (\"\\033[92m\" + \"Your backward propagation works perfectly fine! difference = \" + str(difference) + \"\\033[0m\")\n", 368 | " \n", 369 | " return difference" 370 | ] 371 | }, 372 | { 373 | "cell_type": "code", 374 | "execution_count": 7, 375 | "metadata": { 376 | "deletable": false, 377 | "editable": false, 378 | "nbgrader": { 379 | "cell_type": "code", 380 | "checksum": "d337f8314fabea08c817cdf32fdbcfb3", 381 | "grade": true, 382 | "grade_id": "cell-be0338be7d50dd11", 383 | "locked": true, 384 | "points": 10, 385 | "schema_version": 3, 386 | "solution": false, 387 | "task": false 388 | } 389 | }, 390 | "outputs": [ 391 | { 392 | "name": "stdout", 393 | "output_type": "stream", 394 | "text": [ 395 | "\u001b[92mYour backward propagation works perfectly fine! difference = 2.919335883291695e-10\u001b[0m\n" 396 | ] 397 | } 398 | ], 399 | "source": [ 400 | "x, theta = 2, 4\n", 401 | "difference = gradient_check(2,4, print_msg=True)\n", 402 | "\n", 403 | "#gradient_check_test(gradient_check)" 404 | ] 405 | }, 406 | { 407 | "cell_type": "markdown", 408 | "metadata": {}, 409 | "source": [ 410 | "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()`. \n", 411 | "\n", 412 | "Now, in the more general case, your cost function $J$ has more than a single 1D input. When you are training a neural network, $\\theta$ 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!" 413 | ] 414 | }, 415 | { 416 | "cell_type": "markdown", 417 | "metadata": {}, 418 | "source": [ 419 | "\n", 420 | "## 5 - N-Dimensional Gradient Checking" 421 | ] 422 | }, 423 | { 424 | "cell_type": "markdown", 425 | "metadata": { 426 | "collapsed": true 427 | }, 428 | "source": [ 429 | "The following figure describes the forward and backward propagation of your fraud detection model.\n", 430 | "\n", 431 | "\n", 432 | "
Figure 2: Deep neural network. LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID
\n", 433 | "\n", 434 | "Let's look at your implementations for forward propagation and backward propagation. " 435 | ] 436 | }, 437 | { 438 | "cell_type": "code", 439 | "execution_count": 8, 440 | "metadata": {}, 441 | "outputs": [], 442 | "source": [ 443 | "def forward_propagation_n(X, Y, parameters):\n", 444 | " \"\"\"\n", 445 | " Implements the forward propagation (and computes the cost) presented in Figure 3.\n", 446 | " \n", 447 | " Arguments:\n", 448 | " X -- training set for m examples\n", 449 | " Y -- labels for m examples \n", 450 | " parameters -- python dictionary containing your parameters \"W1\", \"b1\", \"W2\", \"b2\", \"W3\", \"b3\":\n", 451 | " W1 -- weight matrix of shape (5, 4)\n", 452 | " b1 -- bias vector of shape (5, 1)\n", 453 | " W2 -- weight matrix of shape (3, 5)\n", 454 | " b2 -- bias vector of shape (3, 1)\n", 455 | " W3 -- weight matrix of shape (1, 3)\n", 456 | " b3 -- bias vector of shape (1, 1)\n", 457 | " \n", 458 | " Returns:\n", 459 | " cost -- the cost function (logistic cost for one example)\n", 460 | " cache -- a tuple with the intermediate values (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3)\n", 461 | "\n", 462 | " \"\"\"\n", 463 | " \n", 464 | " # retrieve parameters\n", 465 | " m = X.shape[1]\n", 466 | " W1 = parameters[\"W1\"]\n", 467 | " b1 = parameters[\"b1\"]\n", 468 | " W2 = parameters[\"W2\"]\n", 469 | " b2 = parameters[\"b2\"]\n", 470 | " W3 = parameters[\"W3\"]\n", 471 | " b3 = parameters[\"b3\"]\n", 472 | "\n", 473 | " # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID\n", 474 | " Z1 = np.dot(W1, X) + b1\n", 475 | " A1 = relu(Z1)\n", 476 | " Z2 = np.dot(W2, A1) + b2\n", 477 | " A2 = relu(Z2)\n", 478 | " Z3 = np.dot(W3, A2) + b3\n", 479 | " A3 = sigmoid(Z3)\n", 480 | "\n", 481 | " # Cost\n", 482 | " log_probs = np.multiply(-np.log(A3),Y) + np.multiply(-np.log(1 - A3), 1 - Y)\n", 483 | " cost = 1. / m * np.sum(log_probs)\n", 484 | " \n", 485 | " cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3)\n", 486 | " \n", 487 | " return cost, cache" 488 | ] 489 | }, 490 | { 491 | "cell_type": "markdown", 492 | "metadata": {}, 493 | "source": [ 494 | "Now, run backward propagation." 495 | ] 496 | }, 497 | { 498 | "cell_type": "code", 499 | "execution_count": 9, 500 | "metadata": {}, 501 | "outputs": [], 502 | "source": [ 503 | "def backward_propagation_n(X, Y, cache):\n", 504 | " \"\"\"\n", 505 | " Implement the backward propagation presented in figure 2.\n", 506 | " \n", 507 | " Arguments:\n", 508 | " X -- input datapoint, of shape (input size, 1)\n", 509 | " Y -- true \"label\"\n", 510 | " cache -- cache output from forward_propagation_n()\n", 511 | " \n", 512 | " Returns:\n", 513 | " gradients -- A dictionary with the gradients of the cost with respect to each parameter, activation and pre-activation variables.\n", 514 | " \"\"\"\n", 515 | " \n", 516 | " m = X.shape[1]\n", 517 | " (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache\n", 518 | " \n", 519 | " dZ3 = A3 - Y\n", 520 | " dW3 = 1. / m * np.dot(dZ3, A2.T)\n", 521 | " db3 = 1. / m * np.sum(dZ3, axis=1, keepdims=True)\n", 522 | " \n", 523 | " dA2 = np.dot(W3.T, dZ3)\n", 524 | " dZ2 = np.multiply(dA2, np.int64(A2 > 0))\n", 525 | " dW2 = 1. / m * np.dot(dZ2, A1.T) * 2\n", 526 | " db2 = 1. / m * np.sum(dZ2, axis=1, keepdims=True)\n", 527 | " \n", 528 | " dA1 = np.dot(W2.T, dZ2)\n", 529 | " dZ1 = np.multiply(dA1, np.int64(A1 > 0))\n", 530 | " dW1 = 1. / m * np.dot(dZ1, X.T)\n", 531 | " db1 = 4. / m * np.sum(dZ1, axis=1, keepdims=True)\n", 532 | " \n", 533 | " gradients = {\"dZ3\": dZ3, \"dW3\": dW3, \"db3\": db3,\n", 534 | " \"dA2\": dA2, \"dZ2\": dZ2, \"dW2\": dW2, \"db2\": db2,\n", 535 | " \"dA1\": dA1, \"dZ1\": dZ1, \"dW1\": dW1, \"db1\": db1}\n", 536 | " \n", 537 | " return gradients" 538 | ] 539 | }, 540 | { 541 | "cell_type": "markdown", 542 | "metadata": { 543 | "collapsed": true 544 | }, 545 | "source": [ 546 | "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." 547 | ] 548 | }, 549 | { 550 | "cell_type": "markdown", 551 | "metadata": {}, 552 | "source": [ 553 | "**How does gradient checking work?**.\n", 554 | "\n", 555 | "As in Section 3 and 4, you want to compare \"gradapprox\" to the gradient computed by backpropagation. The formula is still:\n", 556 | "\n", 557 | "$$ \\frac{\\partial J}{\\partial \\theta} = \\lim_{\\varepsilon \\to 0} \\frac{J(\\theta + \\varepsilon) - J(\\theta - \\varepsilon)}{2 \\varepsilon} \\tag{1}$$\n", 558 | "\n", 559 | "However, $\\theta$ 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.\n", 560 | "\n", 561 | "The inverse function is \"`vector_to_dictionary`\" which outputs back the \"parameters\" dictionary.\n", 562 | "\n", 563 | "\n", 564 | "
Figure 2: dictionary_to_vector() and vector_to_dictionary(). You will need these functions in gradient_check_n()
\n", 565 | "\n", 566 | "The \"gradients\" dictionary has also been converted into a vector \"grad\" using gradients_to_vector(), so you don't need to worry about that.\n", 567 | "\n", 568 | "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. \n", 569 | "\n", 570 | "Note that `grad` is calculated using the function `gradients_to_vector`, which uses the gradients outputs of the `backward_propagation_n` function.\n", 571 | "\n", 572 | "\n", 573 | "### Exercise 4 - gradient_check_n\n", 574 | "\n", 575 | "Implement the function below.\n", 576 | "\n", 577 | "**Instructions**: Here is pseudo-code that will help you implement the gradient check.\n", 578 | "\n", 579 | "For each i in num_parameters:\n", 580 | "- To compute `J_plus[i]`:\n", 581 | " 1. Set $\\theta^{+}$ to `np.copy(parameters_values)`\n", 582 | " 2. Set $\\theta^{+}_i$ to $\\theta^{+}_i + \\varepsilon$\n", 583 | " 3. Calculate $J^{+}_i$ using to `forward_propagation_n(x, y, vector_to_dictionary(`$\\theta^{+}$ `))`. \n", 584 | "- To compute `J_minus[i]`: do the same thing with $\\theta^{-}$\n", 585 | "- Compute $gradapprox[i] = \\frac{J^{+}_i - J^{-}_i}{2 \\varepsilon}$\n", 586 | "\n", 587 | "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: \n", 588 | "$$ difference = \\frac {\\| grad - gradapprox \\|_2}{\\| grad \\|_2 + \\| gradapprox \\|_2 } \\tag{3}$$\n", 589 | "\n", 590 | "**Note**: Use `np.linalg.norm` to get the norms" 591 | ] 592 | }, 593 | { 594 | "cell_type": "code", 595 | "execution_count": 12, 596 | "metadata": { 597 | "deletable": false, 598 | "nbgrader": { 599 | "cell_type": "code", 600 | "checksum": "e202e41c23c49198f7bf3abb69ed7e1a", 601 | "grade": false, 602 | "grade_id": "cell-1e5a768bc4e28e66", 603 | "locked": false, 604 | "schema_version": 3, 605 | "solution": true, 606 | "task": false 607 | } 608 | }, 609 | "outputs": [], 610 | "source": [ 611 | "# GRADED FUNCTION: gradient_check_n\n", 612 | "\n", 613 | "def gradient_check_n(parameters, gradients, X, Y, epsilon=1e-7, print_msg=False):\n", 614 | " \"\"\"\n", 615 | " Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n\n", 616 | " \n", 617 | " Arguments:\n", 618 | " parameters -- python dictionary containing your parameters \"W1\", \"b1\", \"W2\", \"b2\", \"W3\", \"b3\":\n", 619 | " grad -- output of backward_propagation_n, contains gradients of the cost with respect to the parameters. \n", 620 | " x -- input datapoint, of shape (input size, 1)\n", 621 | " y -- true \"label\"\n", 622 | " epsilon -- tiny shift to the input to compute approximated gradient with formula(1)\n", 623 | " \n", 624 | " Returns:\n", 625 | " difference -- difference (2) between the approximated gradient and the backward propagation gradient\n", 626 | " \"\"\"\n", 627 | " \n", 628 | " # Set-up variables\n", 629 | " parameters_values, _ = dictionary_to_vector(parameters)\n", 630 | " \n", 631 | " grad = gradients_to_vector(gradients)\n", 632 | " num_parameters = parameters_values.shape[0]\n", 633 | " J_plus = np.zeros((num_parameters, 1))\n", 634 | " J_minus = np.zeros((num_parameters, 1))\n", 635 | " gradapprox = np.zeros((num_parameters, 1))\n", 636 | " \n", 637 | " # Compute gradapprox\n", 638 | " for i in range(num_parameters):\n", 639 | " \n", 640 | " # Compute J_plus[i]. Inputs: \"parameters_values, epsilon\". Output = \"J_plus[i]\".\n", 641 | " # \"_\" is used because the function you have to outputs two parameters but we only care about the first one\n", 642 | " #(approx. 3 lines)\n", 643 | " theta_plus = np.copy(parameters_values) # Step 1\n", 644 | " theta_plus[i][0] = theta_plus[i][0] + epsilon # Step 2\n", 645 | " J_plus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(theta_plus)) \n", 646 | " \n", 647 | " # Step 3\n", 648 | " # YOUR CODE STARTS HERE\n", 649 | " \n", 650 | " \n", 651 | " # YOUR CODE ENDS HERE\n", 652 | " \n", 653 | " # Compute J_minus[i]. Inputs: \"parameters_values, epsilon\". Output = \"J_minus[i]\".\n", 654 | " #(approx. 3 lines)\n", 655 | " theta_minus = np.copy(parameters_values) # Step 1\n", 656 | " theta_minus[i][0] = theta_minus[i][0] - epsilon # Step 2 \n", 657 | " J_minus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(theta_minus)) # Step 3\n", 658 | " # YOUR CODE STARTS HERE\n", 659 | " \n", 660 | " \n", 661 | " # YOUR CODE ENDS HERE\n", 662 | " \n", 663 | " # Compute gradapprox[i]\n", 664 | " # (approx. 1 line)\n", 665 | " gradapprox[i] = (J_plus[i] - J_minus[i])/(2*epsilon)\n", 666 | " # YOUR CODE STARTS HERE\n", 667 | " \n", 668 | " \n", 669 | " # YOUR CODE ENDS HERE\n", 670 | " \n", 671 | " # Compare gradapprox to backward propagation gradients by computing difference.\n", 672 | " # (approx. 1 line)\n", 673 | " numerator = np.linalg.norm(grad - gradapprox) # Step 1'\n", 674 | " denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) # Step 2'\n", 675 | " difference = numerator/denominator # Step 3'\n", 676 | " # YOUR CODE STARTS HERE\n", 677 | " \n", 678 | " \n", 679 | " # YOUR CODE ENDS HERE\n", 680 | " if print_msg:\n", 681 | " if difference > 2e-7:\n", 682 | " print (\"\\033[93m\" + \"There is a mistake in the backward propagation! difference = \" + str(difference) + \"\\033[0m\")\n", 683 | " else:\n", 684 | " print (\"\\033[92m\" + \"Your backward propagation works perfectly fine! difference = \" + str(difference) + \"\\033[0m\")\n", 685 | "\n", 686 | " return difference" 687 | ] 688 | }, 689 | { 690 | "cell_type": "code", 691 | "execution_count": 13, 692 | "metadata": { 693 | "deletable": false, 694 | "editable": false, 695 | "nbgrader": { 696 | "cell_type": "code", 697 | "checksum": "e119ddabcb075e6e3391464b48e11234", 698 | "grade": true, 699 | "grade_id": "cell-0d7896ce7c954fc9", 700 | "locked": true, 701 | "points": 20, 702 | "schema_version": 3, 703 | "solution": false, 704 | "task": false 705 | } 706 | }, 707 | "outputs": [ 708 | { 709 | "name": "stdout", 710 | "output_type": "stream", 711 | "text": [ 712 | "\u001b[93mThere is a mistake in the backward propagation! difference = 0.2850931567761623\u001b[0m\n" 713 | ] 714 | } 715 | ], 716 | "source": [ 717 | "X, Y, parameters = gradient_check_n_test_case()\n", 718 | "\n", 719 | "cost, cache = forward_propagation_n(X, Y, parameters)\n", 720 | "gradients = backward_propagation_n(X, Y, cache)\n", 721 | "difference = gradient_check_n(parameters, gradients, X, Y, 1e-7, True)\n", 722 | "expected_values = [0.2850931567761623, 1.1890913024229996e-07]\n", 723 | "assert not(type(difference) == np.ndarray), \"You are not using np.linalg.norm for numerator or denominator\"\n", 724 | "assert np.any(np.isclose(difference, expected_values)), \"Wrong value. It is not one of the expected values\"\n" 725 | ] 726 | }, 727 | { 728 | "cell_type": "markdown", 729 | "metadata": {}, 730 | "source": [ 731 | "**Expected output**:\n", 732 | "\n", 733 | "\n", 734 | " \n", 735 | " \n", 736 | " \n", 737 | " \n", 738 | "
There is a mistake in the backward propagation! difference = 0.2850931567761623
" 739 | ] 740 | }, 741 | { 742 | "cell_type": "markdown", 743 | "metadata": {}, 744 | "source": [ 745 | "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. \n", 746 | "\n", 747 | "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. \n", 748 | "\n", 749 | "**Notes** \n", 750 | "- Gradient Checking is slow! Approximating the gradient with $\\frac{\\partial J}{\\partial \\theta} \\approx \\frac{J(\\theta + \\varepsilon) - J(\\theta - \\varepsilon)}{2 \\varepsilon}$ 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. \n", 751 | "- 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. \n", 752 | "\n", 753 | "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. :) \n", 754 | "
\n", 755 | "\n", 756 | " \n", 757 | "**What you should remember from this notebook**:\n", 758 | "- Gradient checking verifies closeness between the gradients from backpropagation and the numerical approximation of the gradient (computed using forward propagation).\n", 759 | "- 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. " 760 | ] 761 | } 762 | ], 763 | "metadata": { 764 | "coursera": { 765 | "course_slug": "deep-neural-network", 766 | "graded_item_id": "n6NBD", 767 | "launcher_item_id": "yfOsE" 768 | }, 769 | "kernelspec": { 770 | "display_name": "Python 3", 771 | "language": "python", 772 | "name": "python3" 773 | }, 774 | "language_info": { 775 | "codemirror_mode": { 776 | "name": "ipython", 777 | "version": 3 778 | }, 779 | "file_extension": ".py", 780 | "mimetype": "text/x-python", 781 | "name": "python", 782 | "nbconvert_exporter": "python", 783 | "pygments_lexer": "ipython3", 784 | "version": "3.7.6" 785 | } 786 | }, 787 | "nbformat": 4, 788 | "nbformat_minor": 1 789 | } 790 | -------------------------------------------------------------------------------- /week-1/Quiz-1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jialincheoh/coursera-improving-deep-neural-networks/9f73fba63edcf59f1e0d013c42211ee1eba578e1/week-1/Quiz-1.pdf -------------------------------------------------------------------------------- /week-2/Quiz-2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jialincheoh/coursera-improving-deep-neural-networks/9f73fba63edcf59f1e0d013c42211ee1eba578e1/week-2/Quiz-2.pdf -------------------------------------------------------------------------------- /week-3/Quiz3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jialincheoh/coursera-improving-deep-neural-networks/9f73fba63edcf59f1e0d013c42211ee1eba578e1/week-3/Quiz3.pdf --------------------------------------------------------------------------------