├── Building_your_Deep_Neural_Network_Step_by_Step_v8a.ipynb ├── Convolution_model_Application.ipynb ├── Convolution_model_Step_by_Step_v1.ipynb ├── Deep+Neural+Network+-+Application+v8.ipynb ├── Gradient+Checking+v1.ipynb ├── Initialization.ipynb ├── Logistic_Regression_with_a_Neural_Network_mindset_v6a.ipynb ├── My Notes ├── .ipynb_checkpoints │ ├── Convolutional Neural Networks-checkpoint.ipynb │ └── Vectorization-checkpoint.ipynb ├── Convolutional Neural Networks.ipynb └── Vectorization.ipynb ├── Neural_Networks_with_Tensorflow.ipynb ├── Notations.pdf ├── Notes.pdf ├── Optimization_methods_v1b.ipynb ├── Planar_data_classification_with_onehidden_layer_v6c.ipynb ├── README.md ├── Regularization_v2a.ipynb ├── Residual_Networks.ipynb ├── TensorFlow_Tutorial_v3b.ipynb ├── Transfer_learning_with_MobileNet_v1.ipynb ├── datasets ├── test_catvnoncat.h5 └── train_catvnoncat.h5 └── requirements.txt /Building_your_Deep_Neural_Network_Step_by_Step_v8a.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Building your Deep Neural Network: Step by Step\n", 8 | "\n", 9 | "Welcome to your week 4 assignment (part 1 of 2)! You have previously trained a 2-layer Neural Network (with a single hidden layer). This week, you will build a deep neural network, with as many layers as you want!\n", 10 | "\n", 11 | "- In this notebook, you will implement all the functions required to build a deep neural network.\n", 12 | "- In the next assignment, you will use these functions to build a deep neural network for image classification.\n", 13 | "\n", 14 | "**After this assignment you will be able to:**\n", 15 | "- Use non-linear units like ReLU to improve your model\n", 16 | "- Build a deeper neural network (with more than 1 hidden layer)\n", 17 | "- Implement an easy-to-use neural network class\n", 18 | "\n", 19 | "**Notation**:\n", 20 | "- Superscript $[l]$ denotes a quantity associated with the $l^{th}$ layer. \n", 21 | " - Example: $a^{[L]}$ is the $L^{th}$ layer activation. $W^{[L]}$ and $b^{[L]}$ are the $L^{th}$ layer parameters.\n", 22 | "- Superscript $(i)$ denotes a quantity associated with the $i^{th}$ example. \n", 23 | " - Example: $x^{(i)}$ is the $i^{th}$ training example.\n", 24 | "- Lowerscript $i$ denotes the $i^{th}$ entry of a vector.\n", 25 | " - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the $l^{th}$ layer's activations).\n", 26 | "\n", 27 | "Let's get started!" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "### Updates to Assignment \n", 35 | "\n", 36 | "#### If you were working on a previous version\n", 37 | "* The current notebook filename is version \"4a\". \n", 38 | "* You can find your work in the file directory as version \"4\".\n", 39 | "* To see the file directory, click on the Coursera logo at the top left of the notebook.\n", 40 | "\n", 41 | "#### List of Updates\n", 42 | "* compute_cost unit test now includes tests for Y = 0 as well as Y = 1. This catches a possible bug before students get graded.\n", 43 | "* linear_backward unit test now has a more complete unit test that catches a possible bug before students get graded.\n" 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": {}, 49 | "source": [ 50 | "## 1 - Packages\n", 51 | "\n", 52 | "Let's first import all the packages that you will need during this assignment. \n", 53 | "- [numpy](www.numpy.org) is the main package for scientific computing with Python.\n", 54 | "- [matplotlib](http://matplotlib.org) is a library to plot graphs in Python.\n", 55 | "- dnn_utils provides some necessary functions for this notebook.\n", 56 | "- testCases provides some test cases to assess the correctness of your functions\n", 57 | "- np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work. Please don't change the seed. " 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 2, 63 | "metadata": {}, 64 | "outputs": [ 65 | { 66 | "name": "stdout", 67 | "output_type": "stream", 68 | "text": [ 69 | "The autoreload extension is already loaded. To reload it, use:\n", 70 | " %reload_ext autoreload\n" 71 | ] 72 | } 73 | ], 74 | "source": [ 75 | "import numpy as np\n", 76 | "import h5py\n", 77 | "import matplotlib.pyplot as plt\n", 78 | "from testCases_v4a import *\n", 79 | "from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward\n", 80 | "\n", 81 | "%matplotlib inline\n", 82 | "plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots\n", 83 | "plt.rcParams['image.interpolation'] = 'nearest'\n", 84 | "plt.rcParams['image.cmap'] = 'gray'\n", 85 | "\n", 86 | "%load_ext autoreload\n", 87 | "%autoreload 2\n", 88 | "\n", 89 | "np.random.seed(1)" 90 | ] 91 | }, 92 | { 93 | "cell_type": "markdown", 94 | "metadata": {}, 95 | "source": [ 96 | "## 2 - Outline of the Assignment\n", 97 | "\n", 98 | "To build your neural network, you will be implementing several \"helper functions\". These helper functions will be used in the next assignment to build a two-layer neural network and an L-layer neural network. Each small helper function you will implement will have detailed instructions that will walk you through the necessary steps. Here is an outline of this assignment, you will:\n", 99 | "\n", 100 | "- Initialize the parameters for a two-layer network and for an $L$-layer neural network.\n", 101 | "- Implement the forward propagation module (shown in purple in the figure below).\n", 102 | " - Complete the LINEAR part of a layer's forward propagation step (resulting in $Z^{[l]}$).\n", 103 | " - We give you the ACTIVATION function (relu/sigmoid).\n", 104 | " - Combine the previous two steps into a new [LINEAR->ACTIVATION] forward function.\n", 105 | " - Stack the [LINEAR->RELU] forward function L-1 time (for layers 1 through L-1) and add a [LINEAR->SIGMOID] at the end (for the final layer $L$). This gives you a new L_model_forward function.\n", 106 | "- Compute the loss.\n", 107 | "- Implement the backward propagation module (denoted in red in the figure below).\n", 108 | " - Complete the LINEAR part of a layer's backward propagation step.\n", 109 | " - We give you the gradient of the ACTIVATE function (relu_backward/sigmoid_backward) \n", 110 | " - Combine the previous two steps into a new [LINEAR->ACTIVATION] backward function.\n", 111 | " - Stack [LINEAR->RELU] backward L-1 times and add [LINEAR->SIGMOID] backward in a new L_model_backward function\n", 112 | "- Finally update the parameters.\n", 113 | "\n", 114 | "\n", 115 | "
**Figure 1**

\n", 116 | "\n", 117 | "\n", 118 | "**Note** that for every forward function, there is a corresponding backward function. That is why at every step of your forward module you will be storing some values in a cache. The cached values are useful for computing gradients. In the backpropagation module you will then use the cache to calculate the gradients. This assignment will show you exactly how to carry out each of these steps. " 119 | ] 120 | }, 121 | { 122 | "cell_type": "markdown", 123 | "metadata": {}, 124 | "source": [ 125 | "## 3 - Initialization\n", 126 | "\n", 127 | "You will write two helper functions that will initialize the parameters for your model. The first function will be used to initialize parameters for a two layer model. The second one will generalize this initialization process to $L$ layers.\n", 128 | "\n", 129 | "### 3.1 - 2-layer Neural Network\n", 130 | "\n", 131 | "**Exercise**: Create and initialize the parameters of the 2-layer neural network.\n", 132 | "\n", 133 | "**Instructions**:\n", 134 | "- The model's structure is: *LINEAR -> RELU -> LINEAR -> SIGMOID*. \n", 135 | "- Use random initialization for the weight matrices. Use `np.random.randn(shape)*0.01` with the correct shape.\n", 136 | "- Use zero initialization for the biases. Use `np.zeros(shape)`." 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": 3, 142 | "metadata": { 143 | "collapsed": true 144 | }, 145 | "outputs": [], 146 | "source": [ 147 | "# GRADED FUNCTION: initialize_parameters\n", 148 | "\n", 149 | "def initialize_parameters(n_x, n_h, n_y):\n", 150 | " \"\"\"\n", 151 | " Argument:\n", 152 | " n_x -- size of the input layer\n", 153 | " n_h -- size of the hidden layer\n", 154 | " n_y -- size of the output layer\n", 155 | " \n", 156 | " Returns:\n", 157 | " parameters -- python dictionary containing your parameters:\n", 158 | " W1 -- weight matrix of shape (n_h, n_x)\n", 159 | " b1 -- bias vector of shape (n_h, 1)\n", 160 | " W2 -- weight matrix of shape (n_y, n_h)\n", 161 | " b2 -- bias vector of shape (n_y, 1)\n", 162 | " \"\"\"\n", 163 | " \n", 164 | " np.random.seed(1)\n", 165 | " \n", 166 | " ### START CODE HERE ### (≈ 4 lines of code)\n", 167 | " W1 = np.random.randn(n_h,n_x)*0.01\n", 168 | " b1 = np.zeros((n_h,1))\n", 169 | " W2 = np.random.randn(n_y,n_h)*0.01\n", 170 | " b2 = np.zeros((n_y,1))\n", 171 | " ### END CODE HERE ###\n", 172 | " \n", 173 | " assert(W1.shape == (n_h, n_x))\n", 174 | " assert(b1.shape == (n_h, 1))\n", 175 | " assert(W2.shape == (n_y, n_h))\n", 176 | " assert(b2.shape == (n_y, 1))\n", 177 | " \n", 178 | " parameters = {\"W1\": W1,\n", 179 | " \"b1\": b1,\n", 180 | " \"W2\": W2,\n", 181 | " \"b2\": b2}\n", 182 | " \n", 183 | " return parameters " 184 | ] 185 | }, 186 | { 187 | "cell_type": "code", 188 | "execution_count": 4, 189 | "metadata": { 190 | "scrolled": true 191 | }, 192 | "outputs": [ 193 | { 194 | "name": "stdout", 195 | "output_type": "stream", 196 | "text": [ 197 | "W1 = [[ 0.01624345 -0.00611756 -0.00528172]\n", 198 | " [-0.01072969 0.00865408 -0.02301539]]\n", 199 | "b1 = [[ 0.]\n", 200 | " [ 0.]]\n", 201 | "W2 = [[ 0.01744812 -0.00761207]]\n", 202 | "b2 = [[ 0.]]\n" 203 | ] 204 | } 205 | ], 206 | "source": [ 207 | "parameters = initialize_parameters(3,2,1)\n", 208 | "print(\"W1 = \" + str(parameters[\"W1\"]))\n", 209 | "print(\"b1 = \" + str(parameters[\"b1\"]))\n", 210 | "print(\"W2 = \" + str(parameters[\"W2\"]))\n", 211 | "print(\"b2 = \" + str(parameters[\"b2\"]))" 212 | ] 213 | }, 214 | { 215 | "cell_type": "markdown", 216 | "metadata": {}, 217 | "source": [ 218 | "**Expected output**:\n", 219 | " \n", 220 | "\n", 221 | " \n", 222 | " \n", 223 | " \n", 225 | " \n", 226 | "\n", 227 | " \n", 228 | " \n", 229 | " \n", 231 | " \n", 232 | " \n", 233 | " \n", 234 | " \n", 235 | " \n", 236 | " \n", 237 | " \n", 238 | " \n", 239 | " \n", 240 | " \n", 241 | " \n", 242 | " \n", 243 | "
**W1** [[ 0.01624345 -0.00611756 -0.00528172]\n", 224 | " [-0.01072969 0.00865408 -0.02301539]]
**b1**[[ 0.]\n", 230 | " [ 0.]]
**W2** [[ 0.01744812 -0.00761207]]
**b2** [[ 0.]]
" 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "metadata": {}, 249 | "source": [ 250 | "### 3.2 - L-layer Neural Network\n", 251 | "\n", 252 | "The initialization for a deeper L-layer neural network is more complicated because there are many more weight matrices and bias vectors. When completing the `initialize_parameters_deep`, you should make sure that your dimensions match between each layer. Recall that $n^{[l]}$ is the number of units in layer $l$. Thus for example if the size of our input $X$ is $(12288, 209)$ (with $m=209$ examples) then:\n", 253 | "\n", 254 | "\n", 255 | "\n", 256 | "\n", 257 | " \n", 258 | " \n", 259 | " \n", 260 | " \n", 261 | " \n", 262 | " \n", 263 | " \n", 264 | " \n", 265 | " \n", 266 | " \n", 267 | " \n", 268 | " \n", 269 | " \n", 270 | " \n", 271 | " \n", 272 | " \n", 273 | " \n", 274 | " \n", 275 | " \n", 276 | " \n", 277 | " \n", 278 | " \n", 279 | " \n", 280 | " \n", 281 | " \n", 282 | " \n", 283 | " \n", 284 | " \n", 285 | " \n", 286 | " \n", 287 | " \n", 288 | " \n", 289 | " \n", 290 | " \n", 291 | " \n", 292 | " \n", 293 | " \n", 294 | " \n", 295 | " \n", 296 | " \n", 297 | " \n", 298 | " \n", 299 | " \n", 300 | " \n", 301 | " \n", 302 | " \n", 303 | " \n", 304 | " \n", 305 | " \n", 306 | "\n", 307 | "
**Shape of W** **Shape of b** **Activation** **Shape of Activation**
**Layer 1** $(n^{[1]},12288)$ $(n^{[1]},1)$ $Z^{[1]} = W^{[1]} X + b^{[1]} $ $(n^{[1]},209)$
**Layer 2** $(n^{[2]}, n^{[1]})$ $(n^{[2]},1)$ $Z^{[2]} = W^{[2]} A^{[1]} + b^{[2]}$ $(n^{[2]}, 209)$
$\\vdots$ $\\vdots$ $\\vdots$ $\\vdots$ $\\vdots$
**Layer L-1** $(n^{[L-1]}, n^{[L-2]})$ $(n^{[L-1]}, 1)$ $Z^{[L-1]} = W^{[L-1]} A^{[L-2]} + b^{[L-1]}$ $(n^{[L-1]}, 209)$
**Layer L** $(n^{[L]}, n^{[L-1]})$ $(n^{[L]}, 1)$ $Z^{[L]} = W^{[L]} A^{[L-1]} + b^{[L]}$ $(n^{[L]}, 209)$
\n", 308 | "\n", 309 | "Remember that when we compute $W X + b$ in python, it carries out broadcasting. For example, if: \n", 310 | "\n", 311 | "$$ W = \\begin{bmatrix}\n", 312 | " j & k & l\\\\\n", 313 | " m & n & o \\\\\n", 314 | " p & q & r \n", 315 | "\\end{bmatrix}\\;\\;\\; X = \\begin{bmatrix}\n", 316 | " a & b & c\\\\\n", 317 | " d & e & f \\\\\n", 318 | " g & h & i \n", 319 | "\\end{bmatrix} \\;\\;\\; b =\\begin{bmatrix}\n", 320 | " s \\\\\n", 321 | " t \\\\\n", 322 | " u\n", 323 | "\\end{bmatrix}\\tag{2}$$\n", 324 | "\n", 325 | "Then $WX + b$ will be:\n", 326 | "\n", 327 | "$$ WX + b = \\begin{bmatrix}\n", 328 | " (ja + kd + lg) + s & (jb + ke + lh) + s & (jc + kf + li)+ s\\\\\n", 329 | " (ma + nd + og) + t & (mb + ne + oh) + t & (mc + nf + oi) + t\\\\\n", 330 | " (pa + qd + rg) + u & (pb + qe + rh) + u & (pc + qf + ri)+ u\n", 331 | "\\end{bmatrix}\\tag{3} $$" 332 | ] 333 | }, 334 | { 335 | "cell_type": "markdown", 336 | "metadata": {}, 337 | "source": [ 338 | "**Exercise**: Implement initialization for an L-layer Neural Network. \n", 339 | "\n", 340 | "**Instructions**:\n", 341 | "- The model's structure is *[LINEAR -> RELU] $ \\times$ (L-1) -> LINEAR -> SIGMOID*. I.e., it has $L-1$ layers using a ReLU activation function followed by an output layer with a sigmoid activation function.\n", 342 | "- Use random initialization for the weight matrices. Use `np.random.randn(shape) * 0.01`.\n", 343 | "- Use zeros initialization for the biases. Use `np.zeros(shape)`.\n", 344 | "- We will store $n^{[l]}$, the number of units in different layers, in a variable `layer_dims`. For example, the `layer_dims` for the \"Planar Data classification model\" from last week would have been [2,4,1]: There were two inputs, one hidden layer with 4 hidden units, and an output layer with 1 output unit. This means `W1`'s shape was (4,2), `b1` was (4,1), `W2` was (1,4) and `b2` was (1,1). Now you will generalize this to $L$ layers! \n", 345 | "- Here is the implementation for $L=1$ (one layer neural network). It should inspire you to implement the general case (L-layer neural network).\n", 346 | "```python\n", 347 | " if L == 1:\n", 348 | " parameters[\"W\" + str(L)] = np.random.randn(layer_dims[1], layer_dims[0]) * 0.01\n", 349 | " parameters[\"b\" + str(L)] = np.zeros((layer_dims[1], 1))\n", 350 | "```" 351 | ] 352 | }, 353 | { 354 | "cell_type": "code", 355 | "execution_count": 7, 356 | "metadata": { 357 | "collapsed": true 358 | }, 359 | "outputs": [], 360 | "source": [ 361 | "# GRADED FUNCTION: initialize_parameters_deep\n", 362 | "\n", 363 | "def initialize_parameters_deep(layer_dims):\n", 364 | " \"\"\"\n", 365 | " Arguments:\n", 366 | " layer_dims -- python array (list) containing the dimensions of each layer in our network\n", 367 | " \n", 368 | " Returns:\n", 369 | " parameters -- python dictionary containing your parameters \"W1\", \"b1\", ..., \"WL\", \"bL\":\n", 370 | " Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1])\n", 371 | " bl -- bias vector of shape (layer_dims[l], 1)\n", 372 | " \"\"\"\n", 373 | " \n", 374 | " np.random.seed(3)\n", 375 | " parameters = {}\n", 376 | " L = len(layer_dims) # number of layers in the network\n", 377 | "\n", 378 | " for l in range(1, L):\n", 379 | " ### START CODE HERE ### (≈ 2 lines of code)\n", 380 | " parameters[\"W\" + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) * 0.01\n", 381 | " parameters[\"b\" + str(l)] = np.zeros((layer_dims[l], 1))\n", 382 | " ### END CODE HERE ###\n", 383 | " \n", 384 | " assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1]))\n", 385 | " assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))\n", 386 | "\n", 387 | " \n", 388 | " return parameters" 389 | ] 390 | }, 391 | { 392 | "cell_type": "code", 393 | "execution_count": 8, 394 | "metadata": {}, 395 | "outputs": [ 396 | { 397 | "name": "stdout", 398 | "output_type": "stream", 399 | "text": [ 400 | "W1 = [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]\n", 401 | " [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]\n", 402 | " [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]\n", 403 | " [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]\n", 404 | "b1 = [[ 0.]\n", 405 | " [ 0.]\n", 406 | " [ 0.]\n", 407 | " [ 0.]]\n", 408 | "W2 = [[-0.01185047 -0.0020565 0.01486148 0.00236716]\n", 409 | " [-0.01023785 -0.00712993 0.00625245 -0.00160513]\n", 410 | " [-0.00768836 -0.00230031 0.00745056 0.01976111]]\n", 411 | "b2 = [[ 0.]\n", 412 | " [ 0.]\n", 413 | " [ 0.]]\n" 414 | ] 415 | } 416 | ], 417 | "source": [ 418 | "parameters = initialize_parameters_deep([5,4,3])\n", 419 | "print(\"W1 = \" + str(parameters[\"W1\"]))\n", 420 | "print(\"b1 = \" + str(parameters[\"b1\"]))\n", 421 | "print(\"W2 = \" + str(parameters[\"W2\"]))\n", 422 | "print(\"b2 = \" + str(parameters[\"b2\"]))" 423 | ] 424 | }, 425 | { 426 | "cell_type": "markdown", 427 | "metadata": {}, 428 | "source": [ 429 | "**Expected output**:\n", 430 | " \n", 431 | "\n", 432 | " \n", 433 | " \n", 434 | " \n", 438 | " \n", 439 | " \n", 440 | " \n", 441 | " \n", 442 | " \n", 446 | " \n", 447 | " \n", 448 | " \n", 449 | " \n", 450 | " \n", 453 | " \n", 454 | " \n", 455 | " \n", 456 | " \n", 457 | " \n", 460 | " \n", 461 | " \n", 462 | "
**W1** [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]\n", 435 | " [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]\n", 436 | " [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]\n", 437 | " [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]
**b1** [[ 0.]\n", 443 | " [ 0.]\n", 444 | " [ 0.]\n", 445 | " [ 0.]]
**W2** [[-0.01185047 -0.0020565 0.01486148 0.00236716]\n", 451 | " [-0.01023785 -0.00712993 0.00625245 -0.00160513]\n", 452 | " [-0.00768836 -0.00230031 0.00745056 0.01976111]]
**b2** [[ 0.]\n", 458 | " [ 0.]\n", 459 | " [ 0.]]
" 463 | ] 464 | }, 465 | { 466 | "cell_type": "markdown", 467 | "metadata": {}, 468 | "source": [ 469 | "## 4 - Forward propagation module\n", 470 | "\n", 471 | "### 4.1 - Linear Forward \n", 472 | "Now that you have initialized your parameters, you will do the forward propagation module. You will start by implementing some basic functions that you will use later when implementing the model. You will complete three functions in this order:\n", 473 | "\n", 474 | "- LINEAR\n", 475 | "- LINEAR -> ACTIVATION where ACTIVATION will be either ReLU or Sigmoid. \n", 476 | "- [LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID (whole model)\n", 477 | "\n", 478 | "The linear forward module (vectorized over all the examples) computes the following equations:\n", 479 | "\n", 480 | "$$Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}\\tag{4}$$\n", 481 | "\n", 482 | "where $A^{[0]} = X$. \n", 483 | "\n", 484 | "**Exercise**: Build the linear part of forward propagation.\n", 485 | "\n", 486 | "**Reminder**:\n", 487 | "The mathematical representation of this unit is $Z^{[l]} = W^{[l]}A^{[l-1]} +b^{[l]}$. You may also find `np.dot()` useful. If your dimensions don't match, printing `W.shape` may help." 488 | ] 489 | }, 490 | { 491 | "cell_type": "code", 492 | "execution_count": 9, 493 | "metadata": { 494 | "collapsed": true 495 | }, 496 | "outputs": [], 497 | "source": [ 498 | "# GRADED FUNCTION: linear_forward\n", 499 | "\n", 500 | "def linear_forward(A, W, b):\n", 501 | " \"\"\"\n", 502 | " Implement the linear part of a layer's forward propagation.\n", 503 | "\n", 504 | " Arguments:\n", 505 | " A -- activations from previous layer (or input data): (size of previous layer, number of examples)\n", 506 | " W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)\n", 507 | " b -- bias vector, numpy array of shape (size of the current layer, 1)\n", 508 | "\n", 509 | " Returns:\n", 510 | " Z -- the input of the activation function, also called pre-activation parameter \n", 511 | " cache -- a python tuple containing \"A\", \"W\" and \"b\" ; stored for computing the backward pass efficiently\n", 512 | " \"\"\"\n", 513 | " \n", 514 | " ### START CODE HERE ### (≈ 1 line of code)\n", 515 | " Z = np.dot(W,A)+b\n", 516 | " ### END CODE HERE ###\n", 517 | " \n", 518 | " assert(Z.shape == (W.shape[0], A.shape[1]))\n", 519 | " cache = (A, W, b)\n", 520 | " \n", 521 | " return Z, cache" 522 | ] 523 | }, 524 | { 525 | "cell_type": "code", 526 | "execution_count": 10, 527 | "metadata": {}, 528 | "outputs": [ 529 | { 530 | "name": "stdout", 531 | "output_type": "stream", 532 | "text": [ 533 | "Z = [[ 3.26295337 -1.23429987]]\n" 534 | ] 535 | } 536 | ], 537 | "source": [ 538 | "A, W, b = linear_forward_test_case()\n", 539 | "\n", 540 | "Z, linear_cache = linear_forward(A, W, b)\n", 541 | "print(\"Z = \" + str(Z))" 542 | ] 543 | }, 544 | { 545 | "cell_type": "markdown", 546 | "metadata": {}, 547 | "source": [ 548 | "**Expected output**:\n", 549 | "\n", 550 | "\n", 551 | " \n", 552 | " \n", 553 | " \n", 554 | " \n", 555 | " \n", 556 | " \n", 557 | "
**Z** [[ 3.26295337 -1.23429987]]
" 558 | ] 559 | }, 560 | { 561 | "cell_type": "markdown", 562 | "metadata": {}, 563 | "source": [ 564 | "### 4.2 - Linear-Activation Forward\n", 565 | "\n", 566 | "In this notebook, you will use two activation functions:\n", 567 | "\n", 568 | "- **Sigmoid**: $\\sigma(Z) = \\sigma(W A + b) = \\frac{1}{ 1 + e^{-(W A + b)}}$. We have provided you with the `sigmoid` function. This function returns **two** items: the activation value \"`a`\" and a \"`cache`\" that contains \"`Z`\" (it's what we will feed in to the corresponding backward function). To use it you could just call: \n", 569 | "``` python\n", 570 | "A, activation_cache = sigmoid(Z)\n", 571 | "```\n", 572 | "\n", 573 | "- **ReLU**: The mathematical formula for ReLu is $A = RELU(Z) = max(0, Z)$. We have provided you with the `relu` function. This function returns **two** items: the activation value \"`A`\" and a \"`cache`\" that contains \"`Z`\" (it's what we will feed in to the corresponding backward function). To use it you could just call:\n", 574 | "``` python\n", 575 | "A, activation_cache = relu(Z)\n", 576 | "```" 577 | ] 578 | }, 579 | { 580 | "cell_type": "markdown", 581 | "metadata": {}, 582 | "source": [ 583 | "For more convenience, you are going to group two functions (Linear and Activation) into one function (LINEAR->ACTIVATION). Hence, you will implement a function that does the LINEAR forward step followed by an ACTIVATION forward step.\n", 584 | "\n", 585 | "**Exercise**: Implement the forward propagation of the *LINEAR->ACTIVATION* layer. Mathematical relation is: $A^{[l]} = g(Z^{[l]}) = g(W^{[l]}A^{[l-1]} +b^{[l]})$ where the activation \"g\" can be sigmoid() or relu(). Use linear_forward() and the correct activation function." 586 | ] 587 | }, 588 | { 589 | "cell_type": "code", 590 | "execution_count": 13, 591 | "metadata": { 592 | "collapsed": true 593 | }, 594 | "outputs": [], 595 | "source": [ 596 | "# GRADED FUNCTION: linear_activation_forward\n", 597 | "\n", 598 | "def linear_activation_forward(A_prev, W, b, activation):\n", 599 | " \"\"\"\n", 600 | " Implement the forward propagation for the LINEAR->ACTIVATION layer\n", 601 | "\n", 602 | " Arguments:\n", 603 | " A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)\n", 604 | " W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)\n", 605 | " b -- bias vector, numpy array of shape (size of the current layer, 1)\n", 606 | " activation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n", 607 | "\n", 608 | " Returns:\n", 609 | " A -- the output of the activation function, also called the post-activation value \n", 610 | " cache -- a python tuple containing \"linear_cache\" and \"activation_cache\";\n", 611 | " stored for computing the backward pass efficiently\n", 612 | " \"\"\"\n", 613 | " \n", 614 | " if activation == \"sigmoid\":\n", 615 | " # Inputs: \"A_prev, W, b\". Outputs: \"A, activation_cache\".\n", 616 | " ### START CODE HERE ### (≈ 2 lines of code)\n", 617 | " Z, linear_cache = linear_forward(A_prev,W,b)\n", 618 | " A, activation_cache = sigmoid(Z)\n", 619 | " ### END CODE HERE ###\n", 620 | " \n", 621 | " elif activation == \"relu\":\n", 622 | " # Inputs: \"A_prev, W, b\". Outputs: \"A, activation_cache\".\n", 623 | " ### START CODE HERE ### (≈ 2 lines of code)\n", 624 | " Z, linear_cache = linear_forward(A_prev,W,b)\n", 625 | " A, activation_cache = relu(Z)\n", 626 | " ### END CODE HERE ###\n", 627 | " \n", 628 | " assert (A.shape == (W.shape[0], A_prev.shape[1]))\n", 629 | " cache = (linear_cache, activation_cache)\n", 630 | "\n", 631 | " return A, cache" 632 | ] 633 | }, 634 | { 635 | "cell_type": "code", 636 | "execution_count": 14, 637 | "metadata": {}, 638 | "outputs": [ 639 | { 640 | "name": "stdout", 641 | "output_type": "stream", 642 | "text": [ 643 | "With sigmoid: A = [[ 0.96890023 0.11013289]]\n", 644 | "With ReLU: A = [[ 3.43896131 0. ]]\n" 645 | ] 646 | } 647 | ], 648 | "source": [ 649 | "A_prev, W, b = linear_activation_forward_test_case()\n", 650 | "\n", 651 | "A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = \"sigmoid\")\n", 652 | "print(\"With sigmoid: A = \" + str(A))\n", 653 | "\n", 654 | "A, linear_activation_cache = linear_activation_forward(A_prev, W, b, activation = \"relu\")\n", 655 | "print(\"With ReLU: A = \" + str(A))" 656 | ] 657 | }, 658 | { 659 | "cell_type": "markdown", 660 | "metadata": {}, 661 | "source": [ 662 | "**Expected output**:\n", 663 | " \n", 664 | "\n", 665 | " \n", 666 | " \n", 667 | " \n", 668 | " \n", 669 | " \n", 670 | " \n", 671 | " \n", 672 | " \n", 673 | "
**With sigmoid: A ** [[ 0.96890023 0.11013289]]
**With ReLU: A ** [[ 3.43896131 0. ]]
\n" 674 | ] 675 | }, 676 | { 677 | "cell_type": "markdown", 678 | "metadata": {}, 679 | "source": [ 680 | "**Note**: In deep learning, the \"[LINEAR->ACTIVATION]\" computation is counted as a single layer in the neural network, not two layers. " 681 | ] 682 | }, 683 | { 684 | "cell_type": "markdown", 685 | "metadata": {}, 686 | "source": [ 687 | "### d) L-Layer Model \n", 688 | "\n", 689 | "For even more convenience when implementing the $L$-layer Neural Net, you will need a function that replicates the previous one (`linear_activation_forward` with RELU) $L-1$ times, then follows that with one `linear_activation_forward` with SIGMOID.\n", 690 | "\n", 691 | "\n", 692 | "
**Figure 2** : *[LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID* model

\n", 693 | "\n", 694 | "**Exercise**: Implement the forward propagation of the above model.\n", 695 | "\n", 696 | "**Instruction**: In the code below, the variable `AL` will denote $A^{[L]} = \\sigma(Z^{[L]}) = \\sigma(W^{[L]} A^{[L-1]} + b^{[L]})$. (This is sometimes also called `Yhat`, i.e., this is $\\hat{Y}$.) \n", 697 | "\n", 698 | "**Tips**:\n", 699 | "- Use the functions you had previously written \n", 700 | "- Use a for loop to replicate [LINEAR->RELU] (L-1) times\n", 701 | "- Don't forget to keep track of the caches in the \"caches\" list. To add a new value `c` to a `list`, you can use `list.append(c)`." 702 | ] 703 | }, 704 | { 705 | "cell_type": "code", 706 | "execution_count": 28, 707 | "metadata": {}, 708 | "outputs": [ 709 | { 710 | "data": { 711 | "text/plain": [ 712 | "3" 713 | ] 714 | }, 715 | "execution_count": 28, 716 | "metadata": {}, 717 | "output_type": "execute_result" 718 | } 719 | ], 720 | "source": [ 721 | "len(parameters) //2" 722 | ] 723 | }, 724 | { 725 | "cell_type": "code", 726 | "execution_count": 51, 727 | "metadata": { 728 | "collapsed": true 729 | }, 730 | "outputs": [], 731 | "source": [ 732 | "# GRADED FUNCTION: L_model_forward\n", 733 | "\n", 734 | "def L_model_forward(X, parameters):\n", 735 | " \"\"\"\n", 736 | " Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation\n", 737 | " \n", 738 | " Arguments:\n", 739 | " X -- data, numpy array of shape (input size, number of examples)\n", 740 | " parameters -- output of initialize_parameters_deep()\n", 741 | " \n", 742 | " Returns:\n", 743 | " AL -- last post-activation value\n", 744 | " caches -- list of caches containing:\n", 745 | " every cache of linear_activation_forward() (there are L-1 of them, indexed from 0 to L-1)\n", 746 | " \"\"\"\n", 747 | "\n", 748 | " caches = []\n", 749 | " A = X\n", 750 | " L = len(parameters) // 2 # number of layers in the neural network\n", 751 | " \n", 752 | " # Implement [LINEAR -> RELU]*(L-1). Add \"cache\" to the \"caches\" list.\n", 753 | " for l in range(1, L):\n", 754 | " A_prev = A \n", 755 | " ### START CODE HERE ### (≈ 2 lines of code)\n", 756 | " A, cache = linear_activation_forward(A_prev, parameters[\"W\"+str(l)], parameters[\"b\"+str(l)], activation = \"relu\")\n", 757 | " caches.append(cache)\n", 758 | " ### END CODE HERE ###\n", 759 | " \n", 760 | " # Implement LINEAR -> SIGMOID. Add \"cache\" to the \"caches\" list.\n", 761 | " ### START CODE HERE ### (≈ 2 lines of code)\n", 762 | " AL, cache = linear_activation_forward(A,parameters[\"W3\"], parameters[\"b3\"], activation = \"sigmoid\")\n", 763 | " caches.append(cache)\n", 764 | " ### END CODE HERE ###\n", 765 | " \n", 766 | " assert(AL.shape == (1,X.shape[1]))\n", 767 | " \n", 768 | " return AL, caches" 769 | ] 770 | }, 771 | { 772 | "cell_type": "code", 773 | "execution_count": 52, 774 | "metadata": {}, 775 | "outputs": [ 776 | { 777 | "name": "stdout", 778 | "output_type": "stream", 779 | "text": [ 780 | "AL = [[ 0.03921668 0.70498921 0.19734387 0.04728177]]\n", 781 | "Length of caches list = 3\n" 782 | ] 783 | } 784 | ], 785 | "source": [ 786 | "X, parameters = L_model_forward_test_case_2hidden()\n", 787 | "AL, caches = L_model_forward(X, parameters)\n", 788 | "print(\"AL = \" + str(AL))\n", 789 | "print(\"Length of caches list = \" + str(len(caches)))" 790 | ] 791 | }, 792 | { 793 | "cell_type": "markdown", 794 | "metadata": {}, 795 | "source": [ 796 | "\n", 797 | " \n", 798 | " \n", 799 | " \n", 800 | " \n", 801 | " \n", 802 | " \n", 803 | " \n", 804 | " \n", 805 | "
**AL** [[ 0.03921668 0.70498921 0.19734387 0.04728177]]
**Length of caches list ** 3
" 806 | ] 807 | }, 808 | { 809 | "cell_type": "markdown", 810 | "metadata": {}, 811 | "source": [ 812 | "Great! Now you have a full forward propagation that takes the input X and outputs a row vector $A^{[L]}$ containing your predictions. It also records all intermediate values in \"caches\". Using $A^{[L]}$, you can compute the cost of your predictions." 813 | ] 814 | }, 815 | { 816 | "cell_type": "markdown", 817 | "metadata": {}, 818 | "source": [ 819 | "## 5 - Cost function\n", 820 | "\n", 821 | "Now you will implement forward and backward propagation. You need to compute the cost, because you want to check if your model is actually learning.\n", 822 | "\n", 823 | "**Exercise**: Compute the cross-entropy cost $J$, using the following formula: $$-\\frac{1}{m} \\sum\\limits_{i = 1}^{m} (y^{(i)}\\log\\left(a^{[L] (i)}\\right) + (1-y^{(i)})\\log\\left(1- a^{[L](i)}\\right)) \\tag{7}$$\n" 824 | ] 825 | }, 826 | { 827 | "cell_type": "code", 828 | "execution_count": 59, 829 | "metadata": { 830 | "collapsed": true 831 | }, 832 | "outputs": [], 833 | "source": [ 834 | "# GRADED FUNCTION: compute_cost\n", 835 | "\n", 836 | "def compute_cost(AL, Y):\n", 837 | " \"\"\"\n", 838 | " Implement the cost function defined by equation (7).\n", 839 | "\n", 840 | " Arguments:\n", 841 | " AL -- probability vector corresponding to your label predictions, shape (1, number of examples)\n", 842 | " Y -- true \"label\" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)\n", 843 | "\n", 844 | " Returns:\n", 845 | " cost -- cross-entropy cost\n", 846 | " \"\"\"\n", 847 | " \n", 848 | " m = Y.shape[1]\n", 849 | "\n", 850 | " # Compute loss from aL and y.\n", 851 | " ### START CODE HERE ### (≈ 1 lines of code)\n", 852 | " cost = (-1/m)*(np.sum(np.multiply(np.log(AL),Y)+np.multiply((1-Y),np.log(1-AL))))\n", 853 | " ### END CODE HERE ###\n", 854 | " \n", 855 | " cost = np.squeeze(cost) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).\n", 856 | " assert(cost.shape == ())\n", 857 | " \n", 858 | " return cost" 859 | ] 860 | }, 861 | { 862 | "cell_type": "code", 863 | "execution_count": 60, 864 | "metadata": {}, 865 | "outputs": [ 866 | { 867 | "name": "stdout", 868 | "output_type": "stream", 869 | "text": [ 870 | "cost = 0.279776563579\n" 871 | ] 872 | } 873 | ], 874 | "source": [ 875 | "Y, AL = compute_cost_test_case()\n", 876 | "\n", 877 | "print(\"cost = \" + str(compute_cost(AL, Y)))" 878 | ] 879 | }, 880 | { 881 | "cell_type": "markdown", 882 | "metadata": {}, 883 | "source": [ 884 | "**Expected Output**:\n", 885 | "\n", 886 | "\n", 887 | "\n", 888 | " \n", 889 | " \n", 890 | " \n", 891 | " \n", 892 | "
**cost** 0.2797765635793422
" 893 | ] 894 | }, 895 | { 896 | "cell_type": "markdown", 897 | "metadata": {}, 898 | "source": [ 899 | "## 6 - Backward propagation module\n", 900 | "\n", 901 | "Just like with forward propagation, you will implement helper functions for backpropagation. Remember that back propagation is used to calculate the gradient of the loss function with respect to the parameters. \n", 902 | "\n", 903 | "**Reminder**: \n", 904 | "\n", 905 | "
**Figure 3** : Forward and Backward propagation for *LINEAR->RELU->LINEAR->SIGMOID*
*The purple blocks represent the forward propagation, and the red blocks represent the backward propagation.*
\n", 906 | "\n", 907 | "\n", 918 | "\n", 919 | "Now, similar to forward propagation, you are going to build the backward propagation in three steps:\n", 920 | "- LINEAR backward\n", 921 | "- LINEAR -> ACTIVATION backward where ACTIVATION computes the derivative of either the ReLU or sigmoid activation\n", 922 | "- [LINEAR -> RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID backward (whole model)" 923 | ] 924 | }, 925 | { 926 | "cell_type": "markdown", 927 | "metadata": {}, 928 | "source": [ 929 | "### 6.1 - Linear backward\n", 930 | "\n", 931 | "For layer $l$, the linear part is: $Z^{[l]} = W^{[l]} A^{[l-1]} + b^{[l]}$ (followed by an activation).\n", 932 | "\n", 933 | "Suppose you have already calculated the derivative $dZ^{[l]} = \\frac{\\partial \\mathcal{L} }{\\partial Z^{[l]}}$. You want to get $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$.\n", 934 | "\n", 935 | "\n", 936 | "
**Figure 4**
\n", 937 | "\n", 938 | "The three outputs $(dW^{[l]}, db^{[l]}, dA^{[l-1]})$ are computed using the input $dZ^{[l]}$.Here are the formulas you need:\n", 939 | "$$ dW^{[l]} = \\frac{\\partial \\mathcal{J} }{\\partial W^{[l]}} = \\frac{1}{m} dZ^{[l]} A^{[l-1] T} \\tag{8}$$\n", 940 | "$$ db^{[l]} = \\frac{\\partial \\mathcal{J} }{\\partial b^{[l]}} = \\frac{1}{m} \\sum_{i = 1}^{m} dZ^{[l](i)}\\tag{9}$$\n", 941 | "$$ dA^{[l-1]} = \\frac{\\partial \\mathcal{L} }{\\partial A^{[l-1]}} = W^{[l] T} dZ^{[l]} \\tag{10}$$\n" 942 | ] 943 | }, 944 | { 945 | "cell_type": "markdown", 946 | "metadata": {}, 947 | "source": [ 948 | "**Exercise**: Use the 3 formulas above to implement linear_backward()." 949 | ] 950 | }, 951 | { 952 | "cell_type": "code", 953 | "execution_count": 101, 954 | "metadata": { 955 | "collapsed": true 956 | }, 957 | "outputs": [], 958 | "source": [ 959 | "# GRADED FUNCTION: linear_backward\n", 960 | "\n", 961 | "def linear_backward(dZ, cache):\n", 962 | " \"\"\"\n", 963 | " Implement the linear portion of backward propagation for a single layer (layer l)\n", 964 | "\n", 965 | " Arguments:\n", 966 | " dZ -- Gradient of the cost with respect to the linear output (of current layer l)\n", 967 | " cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer\n", 968 | "\n", 969 | " Returns:\n", 970 | " dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n", 971 | " dW -- Gradient of the cost with respect to W (current layer l), same shape as W\n", 972 | " db -- Gradient of the cost with respect to b (current layer l), same shape as b\n", 973 | " \"\"\"\n", 974 | " A_prev, W, b = cache\n", 975 | " m = A_prev.shape[1]\n", 976 | "\n", 977 | " ### START CODE HERE ### (≈ 3 lines of code)\n", 978 | " dW = (1/m)* (np.dot(dZ,A_prev.T))\n", 979 | " db = (1/m)* np.sum(dZ,axis=1,keepdims=True)\n", 980 | " dA_prev = np.dot(W.T,dZ)\n", 981 | " ### END CODE HERE ###\n", 982 | " \n", 983 | " assert (dA_prev.shape == A_prev.shape)\n", 984 | " assert (dW.shape == W.shape)\n", 985 | " assert (db.shape == b.shape)\n", 986 | " \n", 987 | " return dA_prev, dW, db" 988 | ] 989 | }, 990 | { 991 | "cell_type": "code", 992 | "execution_count": 102, 993 | "metadata": {}, 994 | "outputs": [ 995 | { 996 | "name": "stdout", 997 | "output_type": "stream", 998 | "text": [ 999 | "dA_prev = [[-1.15171336 0.06718465 -0.3204696 2.09812712]\n", 1000 | " [ 0.60345879 -3.72508701 5.81700741 -3.84326836]\n", 1001 | " [-0.4319552 -1.30987417 1.72354705 0.05070578]\n", 1002 | " [-0.38981415 0.60811244 -1.25938424 1.47191593]\n", 1003 | " [-2.52214926 2.67882552 -0.67947465 1.48119548]]\n", 1004 | "dW = [[ 0.07313866 -0.0976715 -0.87585828 0.73763362 0.00785716]\n", 1005 | " [ 0.85508818 0.37530413 -0.59912655 0.71278189 -0.58931808]\n", 1006 | " [ 0.97913304 -0.24376494 -0.08839671 0.55151192 -0.10290907]]\n", 1007 | "db = [[-0.14713786]\n", 1008 | " [-0.11313155]\n", 1009 | " [-0.13209101]]\n" 1010 | ] 1011 | } 1012 | ], 1013 | "source": [ 1014 | "# Set up some test inputs\n", 1015 | "dZ, linear_cache = linear_backward_test_case()\n", 1016 | "\n", 1017 | "dA_prev, dW, db = linear_backward(dZ, linear_cache)\n", 1018 | "print (\"dA_prev = \"+ str(dA_prev))\n", 1019 | "print (\"dW = \" + str(dW))\n", 1020 | "print (\"db = \" + str(db))" 1021 | ] 1022 | }, 1023 | { 1024 | "cell_type": "markdown", 1025 | "metadata": {}, 1026 | "source": [ 1027 | "** Expected Output**:\n", 1028 | " \n", 1029 | "```\n", 1030 | "dA_prev = \n", 1031 | " [[-1.15171336 0.06718465 -0.3204696 2.09812712]\n", 1032 | " [ 0.60345879 -3.72508701 5.81700741 -3.84326836]\n", 1033 | " [-0.4319552 -1.30987417 1.72354705 0.05070578]\n", 1034 | " [-0.38981415 0.60811244 -1.25938424 1.47191593]\n", 1035 | " [-2.52214926 2.67882552 -0.67947465 1.48119548]]\n", 1036 | "dW = \n", 1037 | " [[ 0.07313866 -0.0976715 -0.87585828 0.73763362 0.00785716]\n", 1038 | " [ 0.85508818 0.37530413 -0.59912655 0.71278189 -0.58931808]\n", 1039 | " [ 0.97913304 -0.24376494 -0.08839671 0.55151192 -0.10290907]]\n", 1040 | "db = \n", 1041 | " [[-0.14713786]\n", 1042 | " [-0.11313155]\n", 1043 | " [-0.13209101]]\n", 1044 | "```" 1045 | ] 1046 | }, 1047 | { 1048 | "cell_type": "markdown", 1049 | "metadata": {}, 1050 | "source": [ 1051 | "### 6.2 - Linear-Activation backward\n", 1052 | "\n", 1053 | "Next, you will create a function that merges the two helper functions: **`linear_backward`** and the backward step for the activation **`linear_activation_backward`**. \n", 1054 | "\n", 1055 | "To help you implement `linear_activation_backward`, we provided two backward functions:\n", 1056 | "- **`sigmoid_backward`**: Implements the backward propagation for SIGMOID unit. You can call it as follows:\n", 1057 | "\n", 1058 | "```python\n", 1059 | "dZ = sigmoid_backward(dA, activation_cache)\n", 1060 | "```\n", 1061 | "\n", 1062 | "- **`relu_backward`**: Implements the backward propagation for RELU unit. You can call it as follows:\n", 1063 | "\n", 1064 | "```python\n", 1065 | "dZ = relu_backward(dA, activation_cache)\n", 1066 | "```\n", 1067 | "\n", 1068 | "If $g(.)$ is the activation function, \n", 1069 | "`sigmoid_backward` and `relu_backward` compute $$dZ^{[l]} = dA^{[l]} * g'(Z^{[l]}) \\tag{11}$$. \n", 1070 | "\n", 1071 | "**Exercise**: Implement the backpropagation for the *LINEAR->ACTIVATION* layer." 1072 | ] 1073 | }, 1074 | { 1075 | "cell_type": "code", 1076 | "execution_count": 103, 1077 | "metadata": { 1078 | "collapsed": true 1079 | }, 1080 | "outputs": [], 1081 | "source": [ 1082 | "# GRADED FUNCTION: linear_activation_backward\n", 1083 | "\n", 1084 | "def linear_activation_backward(dA, cache, activation):\n", 1085 | " \"\"\"\n", 1086 | " Implement the backward propagation for the LINEAR->ACTIVATION layer.\n", 1087 | " \n", 1088 | " Arguments:\n", 1089 | " dA -- post-activation gradient for current layer l \n", 1090 | " cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently\n", 1091 | " activation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n", 1092 | " \n", 1093 | " Returns:\n", 1094 | " dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n", 1095 | " dW -- Gradient of the cost with respect to W (current layer l), same shape as W\n", 1096 | " db -- Gradient of the cost with respect to b (current layer l), same shape as b\n", 1097 | " \"\"\"\n", 1098 | " linear_cache, activation_cache = cache\n", 1099 | " \n", 1100 | " if activation == \"relu\":\n", 1101 | " ### START CODE HERE ### (≈ 2 lines of code)\n", 1102 | " dZ = relu_backward(dA,activation_cache)\n", 1103 | " dA_prev, dW, db = linear_backward(dZ,linear_cache)\n", 1104 | " ### END CODE HERE ###\n", 1105 | " \n", 1106 | " elif activation == \"sigmoid\":\n", 1107 | " ### START CODE HERE ### (≈ 2 lines of code)\n", 1108 | " dZ = sigmoid_backward(dA,activation_cache)\n", 1109 | " dA_prev, dW, db = linear_backward(dZ,linear_cache)\n", 1110 | " ### END CODE HERE ###\n", 1111 | " \n", 1112 | " return dA_prev, dW, db" 1113 | ] 1114 | }, 1115 | { 1116 | "cell_type": "code", 1117 | "execution_count": 104, 1118 | "metadata": {}, 1119 | "outputs": [ 1120 | { 1121 | "name": "stdout", 1122 | "output_type": "stream", 1123 | "text": [ 1124 | "sigmoid:\n", 1125 | "dA_prev = [[ 0.11017994 0.01105339]\n", 1126 | " [ 0.09466817 0.00949723]\n", 1127 | " [-0.05743092 -0.00576154]]\n", 1128 | "dW = [[ 0.10266786 0.09778551 -0.01968084]]\n", 1129 | "db = [[-0.05729622]]\n", 1130 | "\n", 1131 | "relu:\n", 1132 | "dA_prev = [[ 0.44090989 -0. ]\n", 1133 | " [ 0.37883606 -0. ]\n", 1134 | " [-0.2298228 0. ]]\n", 1135 | "dW = [[ 0.44513824 0.37371418 -0.10478989]]\n", 1136 | "db = [[-0.20837892]]\n" 1137 | ] 1138 | } 1139 | ], 1140 | "source": [ 1141 | "dAL, linear_activation_cache = linear_activation_backward_test_case()\n", 1142 | "\n", 1143 | "dA_prev, dW, db = linear_activation_backward(dAL, linear_activation_cache, activation = \"sigmoid\")\n", 1144 | "print (\"sigmoid:\")\n", 1145 | "print (\"dA_prev = \"+ str(dA_prev))\n", 1146 | "print (\"dW = \" + str(dW))\n", 1147 | "print (\"db = \" + str(db) + \"\\n\")\n", 1148 | "\n", 1149 | "dA_prev, dW, db = linear_activation_backward(dAL, linear_activation_cache, activation = \"relu\")\n", 1150 | "print (\"relu:\")\n", 1151 | "print (\"dA_prev = \"+ str(dA_prev))\n", 1152 | "print (\"dW = \" + str(dW))\n", 1153 | "print (\"db = \" + str(db))" 1154 | ] 1155 | }, 1156 | { 1157 | "cell_type": "markdown", 1158 | "metadata": {}, 1159 | "source": [ 1160 | "**Expected output with sigmoid:**\n", 1161 | "\n", 1162 | "\n", 1163 | " \n", 1164 | " \n", 1165 | " \n", 1168 | "\n", 1169 | " \n", 1170 | " \n", 1171 | " \n", 1172 | " \n", 1173 | " \n", 1174 | " \n", 1175 | " \n", 1176 | " \n", 1177 | " \n", 1178 | " \n", 1179 | " \n", 1180 | "
dA_prev [[ 0.11017994 0.01105339]\n", 1166 | " [ 0.09466817 0.00949723]\n", 1167 | " [-0.05743092 -0.00576154]]
dW [[ 0.10266786 0.09778551 -0.01968084]]
db [[-0.05729622]]
\n", 1181 | "\n" 1182 | ] 1183 | }, 1184 | { 1185 | "cell_type": "markdown", 1186 | "metadata": {}, 1187 | "source": [ 1188 | "**Expected output with relu:**\n", 1189 | "\n", 1190 | "\n", 1191 | " \n", 1192 | " \n", 1193 | " \n", 1196 | "\n", 1197 | " \n", 1198 | " \n", 1199 | " \n", 1200 | " \n", 1201 | " \n", 1202 | " \n", 1203 | " \n", 1204 | " \n", 1205 | " \n", 1206 | " \n", 1207 | " \n", 1208 | "
dA_prev [[ 0.44090989 0. ]\n", 1194 | " [ 0.37883606 0. ]\n", 1195 | " [-0.2298228 0. ]]
dW [[ 0.44513824 0.37371418 -0.10478989]]
db [[-0.20837892]]
\n", 1209 | "\n" 1210 | ] 1211 | }, 1212 | { 1213 | "cell_type": "markdown", 1214 | "metadata": {}, 1215 | "source": [ 1216 | "### 6.3 - L-Model Backward \n", 1217 | "\n", 1218 | "Now you will implement the backward function for the whole network. Recall that when you implemented the `L_model_forward` function, at each iteration, you stored a cache which contains (X,W,b, and z). In the back propagation module, you will use those variables to compute the gradients. Therefore, in the `L_model_backward` function, you will iterate through all the hidden layers backward, starting from layer $L$. On each step, you will use the cached values for layer $l$ to backpropagate through layer $l$. Figure 5 below shows the backward pass. \n", 1219 | "\n", 1220 | "\n", 1221 | "\n", 1222 | "
**Figure 5** : Backward pass
\n", 1223 | "\n", 1224 | "** Initializing backpropagation**:\n", 1225 | "To backpropagate through this network, we know that the output is, \n", 1226 | "$A^{[L]} = \\sigma(Z^{[L]})$. Your code thus needs to compute `dAL` $= \\frac{\\partial \\mathcal{L}}{\\partial A^{[L]}}$.\n", 1227 | "To do so, use this formula (derived using calculus which you don't need in-depth knowledge of):\n", 1228 | "```python\n", 1229 | "dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL)) # derivative of cost with respect to AL\n", 1230 | "```\n", 1231 | "\n", 1232 | "You can then use this post-activation gradient `dAL` to keep going backward. As seen in Figure 5, you can now feed in `dAL` into the LINEAR->SIGMOID backward function you implemented (which will use the cached values stored by the L_model_forward function). After that, you will have to use a `for` loop to iterate through all the other layers using the LINEAR->RELU backward function. You should store each dA, dW, and db in the grads dictionary. To do so, use this formula : \n", 1233 | "\n", 1234 | "$$grads[\"dW\" + str(l)] = dW^{[l]}\\tag{15} $$\n", 1235 | "\n", 1236 | "For example, for $l=3$ this would store $dW^{[l]}$ in `grads[\"dW3\"]`.\n", 1237 | "\n", 1238 | "**Exercise**: Implement backpropagation for the *[LINEAR->RELU] $\\times$ (L-1) -> LINEAR -> SIGMOID* model." 1239 | ] 1240 | }, 1241 | { 1242 | "cell_type": "code", 1243 | "execution_count": null, 1244 | "metadata": { 1245 | "collapsed": true 1246 | }, 1247 | "outputs": [], 1248 | "source": [ 1249 | "# GRADED FUNCTION: L_model_backward\n", 1250 | "\n", 1251 | "def L_model_backward(AL, Y, caches):\n", 1252 | " \"\"\"\n", 1253 | " Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group\n", 1254 | " \n", 1255 | " Arguments:\n", 1256 | " AL -- probability vector, output of the forward propagation (L_model_forward())\n", 1257 | " Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat)\n", 1258 | " caches -- list of caches containing:\n", 1259 | " every cache of linear_activation_forward() with \"relu\" (it's caches[l], for l in range(L-1) i.e l = 0...L-2)\n", 1260 | " the cache of linear_activation_forward() with \"sigmoid\" (it's caches[L-1])\n", 1261 | " \n", 1262 | " Returns:\n", 1263 | " grads -- A dictionary with the gradients\n", 1264 | " grads[\"dA\" + str(l)] = ... \n", 1265 | " grads[\"dW\" + str(l)] = ...\n", 1266 | " grads[\"db\" + str(l)] = ... \n", 1267 | " \"\"\"\n", 1268 | " grads = {}\n", 1269 | " L = len(caches) # the number of layers\n", 1270 | " m = AL.shape[1]\n", 1271 | " Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL\n", 1272 | " \n", 1273 | " # Initializing the backpropagation\n", 1274 | " ### START CODE HERE ### (1 line of code)\n", 1275 | " dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))\n", 1276 | " ### END CODE HERE ###\n", 1277 | " \n", 1278 | " # Lth layer (SIGMOID -> LINEAR) gradients. Inputs: \"dAL, current_cache\". Outputs: \"grads[\"dAL-1\"], grads[\"dWL\"], grads[\"dbL\"]\n", 1279 | " ### START CODE HERE ### (approx. 2 lines)\n", 1280 | " current_cache = None\n", 1281 | " grads[\"dA\" + str(L-1)], grads[\"dW\" + str(L)], grads[\"db\" + str(L)] = None\n", 1282 | " ### END CODE HERE ###\n", 1283 | " \n", 1284 | " # Loop from l=L-2 to l=0\n", 1285 | " for l in reversed(range(L-1)):\n", 1286 | " # lth layer: (RELU -> LINEAR) gradients.\n", 1287 | " # Inputs: \"grads[\"dA\" + str(l + 1)], current_cache\". Outputs: \"grads[\"dA\" + str(l)] , grads[\"dW\" + str(l + 1)] , grads[\"db\" + str(l + 1)] \n", 1288 | " ### START CODE HERE ### (approx. 5 lines)\n", 1289 | " current_cache = None\n", 1290 | " dA_prev_temp, dW_temp, db_temp = None\n", 1291 | " grads[\"dA\" + str(l)] = None\n", 1292 | " grads[\"dW\" + str(l + 1)] = None\n", 1293 | " grads[\"db\" + str(l + 1)] = None\n", 1294 | " ### END CODE HERE ###\n", 1295 | "\n", 1296 | " return grads" 1297 | ] 1298 | }, 1299 | { 1300 | "cell_type": "code", 1301 | "execution_count": null, 1302 | "metadata": { 1303 | "collapsed": true 1304 | }, 1305 | "outputs": [], 1306 | "source": [ 1307 | "AL, Y_assess, caches = L_model_backward_test_case()\n", 1308 | "grads = L_model_backward(AL, Y_assess, caches)\n", 1309 | "print_grads(grads)" 1310 | ] 1311 | }, 1312 | { 1313 | "cell_type": "markdown", 1314 | "metadata": {}, 1315 | "source": [ 1316 | "**Expected Output**\n", 1317 | "\n", 1318 | "\n", 1319 | " \n", 1320 | " \n", 1321 | " \n", 1322 | " \n", 1325 | " \n", 1326 | " \n", 1327 | " \n", 1328 | " \n", 1329 | " \n", 1332 | " \n", 1333 | " \n", 1334 | " \n", 1335 | " \n", 1336 | " \n", 1339 | "\n", 1340 | " \n", 1341 | "
dW1 [[ 0.41010002 0.07807203 0.13798444 0.10502167]\n", 1323 | " [ 0. 0. 0. 0. ]\n", 1324 | " [ 0.05283652 0.01005865 0.01777766 0.0135308 ]]
db1 [[-0.22007063]\n", 1330 | " [ 0. ]\n", 1331 | " [-0.02835349]]
dA1 [[ 0.12913162 -0.44014127]\n", 1337 | " [-0.14175655 0.48317296]\n", 1338 | " [ 0.01663708 -0.05670698]]
\n", 1342 | "\n" 1343 | ] 1344 | }, 1345 | { 1346 | "cell_type": "markdown", 1347 | "metadata": {}, 1348 | "source": [ 1349 | "### 6.4 - Update Parameters\n", 1350 | "\n", 1351 | "In this section you will update the parameters of the model, using gradient descent: \n", 1352 | "\n", 1353 | "$$ W^{[l]} = W^{[l]} - \\alpha \\text{ } dW^{[l]} \\tag{16}$$\n", 1354 | "$$ b^{[l]} = b^{[l]} - \\alpha \\text{ } db^{[l]} \\tag{17}$$\n", 1355 | "\n", 1356 | "where $\\alpha$ is the learning rate. After computing the updated parameters, store them in the parameters dictionary. " 1357 | ] 1358 | }, 1359 | { 1360 | "cell_type": "markdown", 1361 | "metadata": {}, 1362 | "source": [ 1363 | "**Exercise**: Implement `update_parameters()` to update your parameters using gradient descent.\n", 1364 | "\n", 1365 | "**Instructions**:\n", 1366 | "Update parameters using gradient descent on every $W^{[l]}$ and $b^{[l]}$ for $l = 1, 2, ..., L$. \n" 1367 | ] 1368 | }, 1369 | { 1370 | "cell_type": "code", 1371 | "execution_count": null, 1372 | "metadata": { 1373 | "collapsed": true 1374 | }, 1375 | "outputs": [], 1376 | "source": [ 1377 | "# GRADED FUNCTION: update_parameters\n", 1378 | "\n", 1379 | "def update_parameters(parameters, grads, learning_rate):\n", 1380 | " \"\"\"\n", 1381 | " Update parameters using gradient descent\n", 1382 | " \n", 1383 | " Arguments:\n", 1384 | " parameters -- python dictionary containing your parameters \n", 1385 | " grads -- python dictionary containing your gradients, output of L_model_backward\n", 1386 | " \n", 1387 | " Returns:\n", 1388 | " parameters -- python dictionary containing your updated parameters \n", 1389 | " parameters[\"W\" + str(l)] = ... \n", 1390 | " parameters[\"b\" + str(l)] = ...\n", 1391 | " \"\"\"\n", 1392 | " \n", 1393 | " L = len(parameters) // 2 # number of layers in the neural network\n", 1394 | "\n", 1395 | " # Update rule for each parameter. Use a for loop.\n", 1396 | " ### START CODE HERE ### (≈ 3 lines of code)\n", 1397 | " for l in range(L):\n", 1398 | " parameters[\"W\" + str(l+1)] = None\n", 1399 | " parameters[\"b\" + str(l+1)] = None\n", 1400 | " ### END CODE HERE ###\n", 1401 | " return parameters" 1402 | ] 1403 | }, 1404 | { 1405 | "cell_type": "code", 1406 | "execution_count": null, 1407 | "metadata": { 1408 | "collapsed": true 1409 | }, 1410 | "outputs": [], 1411 | "source": [ 1412 | "parameters, grads = update_parameters_test_case()\n", 1413 | "parameters = update_parameters(parameters, grads, 0.1)\n", 1414 | "\n", 1415 | "print (\"W1 = \"+ str(parameters[\"W1\"]))\n", 1416 | "print (\"b1 = \"+ str(parameters[\"b1\"]))\n", 1417 | "print (\"W2 = \"+ str(parameters[\"W2\"]))\n", 1418 | "print (\"b2 = \"+ str(parameters[\"b2\"]))" 1419 | ] 1420 | }, 1421 | { 1422 | "cell_type": "markdown", 1423 | "metadata": {}, 1424 | "source": [ 1425 | "**Expected Output**:\n", 1426 | "\n", 1427 | " \n", 1428 | " \n", 1429 | " \n", 1430 | " \n", 1433 | " \n", 1434 | " \n", 1435 | " \n", 1436 | " \n", 1437 | " \n", 1440 | " \n", 1441 | " \n", 1442 | " \n", 1443 | " \n", 1444 | " \n", 1445 | " \n", 1446 | " \n", 1447 | " \n", 1448 | " \n", 1449 | " \n", 1450 | "
W1 [[-0.59562069 -0.09991781 -2.14584584 1.82662008]\n", 1431 | " [-1.76569676 -0.80627147 0.51115557 -1.18258802]\n", 1432 | " [-1.0535704 -0.86128581 0.68284052 2.20374577]]
b1 [[-0.04659241]\n", 1438 | " [-1.28888275]\n", 1439 | " [ 0.53405496]]
W2 [[-0.55569196 0.0354055 1.32964895]]
b2 [[-0.84610769]]
\n" 1451 | ] 1452 | }, 1453 | { 1454 | "cell_type": "markdown", 1455 | "metadata": {}, 1456 | "source": [ 1457 | "\n", 1458 | "## 7 - Conclusion\n", 1459 | "\n", 1460 | "Congrats on implementing all the functions required for building a deep neural network! \n", 1461 | "\n", 1462 | "We know it was a long assignment but going forward it will only get better. The next part of the assignment is easier. \n", 1463 | "\n", 1464 | "In the next assignment you will put all these together to build two models:\n", 1465 | "- A two-layer neural network\n", 1466 | "- An L-layer neural network\n", 1467 | "\n", 1468 | "You will in fact use these models to classify cat vs non-cat images!" 1469 | ] 1470 | } 1471 | ], 1472 | "metadata": { 1473 | "coursera": { 1474 | "course_slug": "neural-networks-deep-learning", 1475 | "graded_item_id": "c4HO0", 1476 | "launcher_item_id": "lSYZM" 1477 | }, 1478 | "kernelspec": { 1479 | "display_name": "Python 3", 1480 | "language": "python", 1481 | "name": "python3" 1482 | }, 1483 | "language_info": { 1484 | "codemirror_mode": { 1485 | "name": "ipython", 1486 | "version": 3 1487 | }, 1488 | "file_extension": ".py", 1489 | "mimetype": "text/x-python", 1490 | "name": "python", 1491 | "nbconvert_exporter": "python", 1492 | "pygments_lexer": "ipython3", 1493 | "version": "3.7.3" 1494 | } 1495 | }, 1496 | "nbformat": 4, 1497 | "nbformat_minor": 2 1498 | } 1499 | -------------------------------------------------------------------------------- /Gradient+Checking+v1.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 will learn to implement and use gradient checking. \n", 10 | "\n", 11 | "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", 12 | "\n", 13 | "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\".\n", 14 | "\n", 15 | "Let's do it!" 16 | ] 17 | }, 18 | { 19 | "cell_type": "code", 20 | "execution_count": 1, 21 | "metadata": { 22 | "collapsed": true 23 | }, 24 | "outputs": [], 25 | "source": [ 26 | "# Packages\n", 27 | "import numpy as np\n", 28 | "from testCases import *\n", 29 | "from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector" 30 | ] 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "metadata": {}, 35 | "source": [ 36 | "## 1) How does gradient checking work?\n", 37 | "\n", 38 | "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", 39 | "\n", 40 | "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", 41 | "\n", 42 | "Let's look back at the definition of a derivative (or gradient):\n", 43 | "$$ \\frac{\\partial J}{\\partial \\theta} = \\lim_{\\varepsilon \\to 0} \\frac{J(\\theta + \\varepsilon) - J(\\theta - \\varepsilon)}{2 \\varepsilon} \\tag{1}$$\n", 44 | "\n", 45 | "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", 46 | "\n", 47 | "We know the following:\n", 48 | "\n", 49 | "- $\\frac{\\partial J}{\\partial \\theta}$ is what you want to make sure you're computing correctly. \n", 50 | "- 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", 51 | "\n", 52 | "Lets 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!" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "## 2) 1-dimensional gradient checking\n", 60 | "\n", 61 | "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", 62 | "\n", 63 | "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", 64 | "\n", 65 | "\n", 66 | "
**Figure 1** : **1D linear model**
\n", 67 | "\n", 68 | "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", 69 | "\n", 70 | "**Exercise**: implement \"forward propagation\" and \"backward propagation\" for this simple function. I.e., compute both $J(.)$ (\"forward propagation\") and its derivative with respect to $\\theta$ (\"backward propagation\"), in two separate functions. " 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": 2, 76 | "metadata": { 77 | "collapsed": true 78 | }, 79 | "outputs": [], 80 | "source": [ 81 | "# GRADED FUNCTION: forward_propagation\n", 82 | "\n", 83 | "def forward_propagation(x, theta):\n", 84 | " \"\"\"\n", 85 | " Implement the linear forward propagation (compute J) presented in Figure 1 (J(theta) = theta * x)\n", 86 | " \n", 87 | " Arguments:\n", 88 | " x -- a real-valued input\n", 89 | " theta -- our parameter, a real number as well\n", 90 | " \n", 91 | " Returns:\n", 92 | " J -- the value of function J, computed using the formula J(theta) = theta * x\n", 93 | " \"\"\"\n", 94 | " \n", 95 | " ### START CODE HERE ### (approx. 1 line)\n", 96 | " J = x*theta\n", 97 | " ### END CODE HERE ###\n", 98 | " \n", 99 | " return J" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": 3, 105 | "metadata": {}, 106 | "outputs": [ 107 | { 108 | "name": "stdout", 109 | "output_type": "stream", 110 | "text": [ 111 | "J = 8\n" 112 | ] 113 | } 114 | ], 115 | "source": [ 116 | "x, theta = 2, 4\n", 117 | "J = forward_propagation(x, theta)\n", 118 | "print (\"J = \" + str(J))" 119 | ] 120 | }, 121 | { 122 | "cell_type": "markdown", 123 | "metadata": {}, 124 | "source": [ 125 | "**Expected Output**:\n", 126 | "\n", 127 | "\n", 128 | " \n", 129 | " \n", 130 | " \n", 131 | " \n", 132 | "
** J ** 8
" 133 | ] 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "metadata": {}, 138 | "source": [ 139 | "**Exercise**: 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$." 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": 6, 145 | "metadata": { 146 | "collapsed": true 147 | }, 148 | "outputs": [], 149 | "source": [ 150 | "# GRADED FUNCTION: backward_propagation\n", 151 | "\n", 152 | "def backward_propagation(x, theta):\n", 153 | " \"\"\"\n", 154 | " Computes the derivative of J with respect to theta (see Figure 1).\n", 155 | " \n", 156 | " Arguments:\n", 157 | " x -- a real-valued input\n", 158 | " theta -- our parameter, a real number as well\n", 159 | " \n", 160 | " Returns:\n", 161 | " dtheta -- the gradient of the cost with respect to theta\n", 162 | " \"\"\"\n", 163 | " \n", 164 | " ### START CODE HERE ### (approx. 1 line)\n", 165 | " dtheta = x\n", 166 | " ### END CODE HERE ###\n", 167 | " \n", 168 | " return dtheta" 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": 7, 174 | "metadata": { 175 | "scrolled": true 176 | }, 177 | "outputs": [ 178 | { 179 | "name": "stdout", 180 | "output_type": "stream", 181 | "text": [ 182 | "dtheta = 2\n" 183 | ] 184 | } 185 | ], 186 | "source": [ 187 | "x, theta = 2, 4\n", 188 | "dtheta = backward_propagation(x, theta)\n", 189 | "print (\"dtheta = \" + str(dtheta))" 190 | ] 191 | }, 192 | { 193 | "cell_type": "markdown", 194 | "metadata": {}, 195 | "source": [ 196 | "**Expected Output**:\n", 197 | "\n", 198 | "\n", 199 | " \n", 200 | " \n", 201 | " \n", 202 | " \n", 203 | "
** dtheta ** 2
" 204 | ] 205 | }, 206 | { 207 | "cell_type": "markdown", 208 | "metadata": {}, 209 | "source": [ 210 | "**Exercise**: To show that the `backward_propagation()` function is correctly computing the gradient $\\frac{\\partial J}{\\partial \\theta}$, let's implement gradient checking.\n", 211 | "\n", 212 | "**Instructions**:\n", 213 | "- First compute \"gradapprox\" using the formula above (1) and a small value of $\\varepsilon$. Here are the Steps to follow:\n", 214 | " 1. $\\theta^{+} = \\theta + \\varepsilon$\n", 215 | " 2. $\\theta^{-} = \\theta - \\varepsilon$\n", 216 | " 3. $J^{+} = J(\\theta^{+})$\n", 217 | " 4. $J^{-} = J(\\theta^{-})$\n", 218 | " 5. $gradapprox = \\frac{J^{+} - J^{-}}{2 \\varepsilon}$\n", 219 | "- Then compute the gradient using backward propagation, and store the result in a variable \"grad\"\n", 220 | "- Finally, compute the relative difference between \"gradapprox\" and the \"grad\" using the following formula:\n", 221 | "$$ difference = \\frac {\\mid\\mid grad - gradapprox \\mid\\mid_2}{\\mid\\mid grad \\mid\\mid_2 + \\mid\\mid gradapprox \\mid\\mid_2} \\tag{2}$$\n", 222 | "You will need 3 Steps to compute this formula:\n", 223 | " - 1'. compute the numerator using np.linalg.norm(...)\n", 224 | " - 2'. compute the denominator. You will need to call np.linalg.norm(...) twice.\n", 225 | " - 3'. divide them.\n", 226 | "- 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" 227 | ] 228 | }, 229 | { 230 | "cell_type": "code", 231 | "execution_count": 30, 232 | "metadata": { 233 | "collapsed": true 234 | }, 235 | "outputs": [], 236 | "source": [ 237 | "# GRADED FUNCTION: gradient_check\n", 238 | "\n", 239 | "def gradient_check(x, theta, epsilon = 1e-7):\n", 240 | " \"\"\"\n", 241 | " Implement the backward propagation presented in Figure 1.\n", 242 | " \n", 243 | " Arguments:\n", 244 | " x -- a real-valued input\n", 245 | " theta -- our parameter, a real number as well\n", 246 | " epsilon -- tiny shift to the input to compute approximated gradient with formula(1)\n", 247 | " \n", 248 | " Returns:\n", 249 | " difference -- difference (2) between the approximated gradient and the backward propagation gradient\n", 250 | " \"\"\"\n", 251 | " \n", 252 | " # Compute gradapprox using left side of formula (1). epsilon is small enough, you don't need to worry about the limit.\n", 253 | " ### START CODE HERE ### (approx. 5 lines)\n", 254 | " thetaplus = theta+epsilon # Step 1\n", 255 | " thetaminus = theta-epsilon # Step 2\n", 256 | " J_plus = forward_propagation(x,thetaplus) # Step 3\n", 257 | " J_minus = forward_propagation(x,thetaminus) # Step 4\n", 258 | " gradapprox = (J_plus-J_minus)/(2*epsilon) # Step 5\n", 259 | " ### END CODE HERE ###\n", 260 | " \n", 261 | " # Check if gradapprox is close enough to the output of backward_propagation()\n", 262 | " ### START CODE HERE ### (approx. 1 line)\n", 263 | " grad = backward_propagation(x,theta)\n", 264 | " ### END CODE HERE ###\n", 265 | " \n", 266 | " ### START CODE HERE ### (approx. 1 line)\n", 267 | " numerator = np.linalg.norm(grad-gradapprox) # Step 1'\n", 268 | " denominator = np.linalg.norm(grad)+np.linalg.norm(gradapprox) # Step 2'\n", 269 | " difference = numerator/denominator # Step 3'\n", 270 | " ### END CODE HERE ###\n", 271 | " \n", 272 | " if difference < 1e-7:\n", 273 | " print (\"The gradient is correct!\")\n", 274 | " else:\n", 275 | " print (\"The gradient is wrong!\")\n", 276 | " \n", 277 | " return difference" 278 | ] 279 | }, 280 | { 281 | "cell_type": "code", 282 | "execution_count": 31, 283 | "metadata": { 284 | "scrolled": true 285 | }, 286 | "outputs": [ 287 | { 288 | "name": "stdout", 289 | "output_type": "stream", 290 | "text": [ 291 | "The gradient is correct!\n", 292 | "difference = 2.91933588329e-10\n" 293 | ] 294 | } 295 | ], 296 | "source": [ 297 | "x, theta = 2, 4\n", 298 | "difference = gradient_check(x, theta)\n", 299 | "print(\"difference = \" + str(difference))" 300 | ] 301 | }, 302 | { 303 | "cell_type": "markdown", 304 | "metadata": {}, 305 | "source": [ 306 | "**Expected Output**:\n", 307 | "The gradient is correct!\n", 308 | "\n", 309 | " \n", 310 | " \n", 311 | " \n", 312 | " \n", 313 | "
** difference ** 2.9193358103083e-10
" 314 | ] 315 | }, 316 | { 317 | "cell_type": "markdown", 318 | "metadata": {}, 319 | "source": [ 320 | "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", 321 | "\n", 322 | "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!" 323 | ] 324 | }, 325 | { 326 | "cell_type": "markdown", 327 | "metadata": {}, 328 | "source": [ 329 | "## 3) N-dimensional gradient checking" 330 | ] 331 | }, 332 | { 333 | "cell_type": "markdown", 334 | "metadata": { 335 | "collapsed": true 336 | }, 337 | "source": [ 338 | "The following figure describes the forward and backward propagation of your fraud detection model.\n", 339 | "\n", 340 | "\n", 341 | "
**Figure 2** : **deep neural network**
*LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID*
\n", 342 | "\n", 343 | "Let's look at your implementations for forward propagation and backward propagation. " 344 | ] 345 | }, 346 | { 347 | "cell_type": "code", 348 | "execution_count": 32, 349 | "metadata": { 350 | "collapsed": true 351 | }, 352 | "outputs": [], 353 | "source": [ 354 | "def forward_propagation_n(X, Y, parameters):\n", 355 | " \"\"\"\n", 356 | " Implements the forward propagation (and computes the cost) presented in Figure 3.\n", 357 | " \n", 358 | " Arguments:\n", 359 | " X -- training set for m examples\n", 360 | " Y -- labels for m examples \n", 361 | " parameters -- python dictionary containing your parameters \"W1\", \"b1\", \"W2\", \"b2\", \"W3\", \"b3\":\n", 362 | " W1 -- weight matrix of shape (5, 4)\n", 363 | " b1 -- bias vector of shape (5, 1)\n", 364 | " W2 -- weight matrix of shape (3, 5)\n", 365 | " b2 -- bias vector of shape (3, 1)\n", 366 | " W3 -- weight matrix of shape (1, 3)\n", 367 | " b3 -- bias vector of shape (1, 1)\n", 368 | " \n", 369 | " Returns:\n", 370 | " cost -- the cost function (logistic cost for one example)\n", 371 | " \"\"\"\n", 372 | " \n", 373 | " # retrieve parameters\n", 374 | " m = X.shape[1]\n", 375 | " W1 = parameters[\"W1\"]\n", 376 | " b1 = parameters[\"b1\"]\n", 377 | " W2 = parameters[\"W2\"]\n", 378 | " b2 = parameters[\"b2\"]\n", 379 | " W3 = parameters[\"W3\"]\n", 380 | " b3 = parameters[\"b3\"]\n", 381 | "\n", 382 | " # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID\n", 383 | " Z1 = np.dot(W1, X) + b1\n", 384 | " A1 = relu(Z1)\n", 385 | " Z2 = np.dot(W2, A1) + b2\n", 386 | " A2 = relu(Z2)\n", 387 | " Z3 = np.dot(W3, A2) + b3\n", 388 | " A3 = sigmoid(Z3)\n", 389 | "\n", 390 | " # Cost\n", 391 | " logprobs = np.multiply(-np.log(A3),Y) + np.multiply(-np.log(1 - A3), 1 - Y)\n", 392 | " cost = 1./m * np.sum(logprobs)\n", 393 | " \n", 394 | " cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3)\n", 395 | " \n", 396 | " return cost, cache" 397 | ] 398 | }, 399 | { 400 | "cell_type": "markdown", 401 | "metadata": {}, 402 | "source": [ 403 | "Now, run backward propagation." 404 | ] 405 | }, 406 | { 407 | "cell_type": "code", 408 | "execution_count": 33, 409 | "metadata": { 410 | "collapsed": true 411 | }, 412 | "outputs": [], 413 | "source": [ 414 | "def backward_propagation_n(X, Y, cache):\n", 415 | " \"\"\"\n", 416 | " Implement the backward propagation presented in figure 2.\n", 417 | " \n", 418 | " Arguments:\n", 419 | " X -- input datapoint, of shape (input size, 1)\n", 420 | " Y -- true \"label\"\n", 421 | " cache -- cache output from forward_propagation_n()\n", 422 | " \n", 423 | " Returns:\n", 424 | " gradients -- A dictionary with the gradients of the cost with respect to each parameter, activation and pre-activation variables.\n", 425 | " \"\"\"\n", 426 | " \n", 427 | " m = X.shape[1]\n", 428 | " (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache\n", 429 | " \n", 430 | " dZ3 = A3 - Y\n", 431 | " dW3 = 1./m * np.dot(dZ3, A2.T)\n", 432 | " db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)\n", 433 | " \n", 434 | " dA2 = np.dot(W3.T, dZ3)\n", 435 | " dZ2 = np.multiply(dA2, np.int64(A2 > 0))\n", 436 | " dW2 = 1./m * np.dot(dZ2, A1.T) * 2\n", 437 | " db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)\n", 438 | " \n", 439 | " dA1 = np.dot(W2.T, dZ2)\n", 440 | " dZ1 = np.multiply(dA1, np.int64(A1 > 0))\n", 441 | " dW1 = 1./m * np.dot(dZ1, X.T)\n", 442 | " db1 = 4./m * np.sum(dZ1, axis=1, keepdims = True)\n", 443 | " \n", 444 | " gradients = {\"dZ3\": dZ3, \"dW3\": dW3, \"db3\": db3,\n", 445 | " \"dA2\": dA2, \"dZ2\": dZ2, \"dW2\": dW2, \"db2\": db2,\n", 446 | " \"dA1\": dA1, \"dZ1\": dZ1, \"dW1\": dW1, \"db1\": db1}\n", 447 | " \n", 448 | " return gradients" 449 | ] 450 | }, 451 | { 452 | "cell_type": "markdown", 453 | "metadata": { 454 | "collapsed": true 455 | }, 456 | "source": [ 457 | "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." 458 | ] 459 | }, 460 | { 461 | "cell_type": "markdown", 462 | "metadata": {}, 463 | "source": [ 464 | "**How does gradient checking work?**.\n", 465 | "\n", 466 | "As in 1) and 2), you want to compare \"gradapprox\" to the gradient computed by backpropagation. The formula is still:\n", 467 | "\n", 468 | "$$ \\frac{\\partial J}{\\partial \\theta} = \\lim_{\\varepsilon \\to 0} \\frac{J(\\theta + \\varepsilon) - J(\\theta - \\varepsilon)}{2 \\varepsilon} \\tag{1}$$\n", 469 | "\n", 470 | "However, $\\theta$ 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.\n", 471 | "\n", 472 | "The inverse function is \"`vector_to_dictionary`\" which outputs back the \"parameters\" dictionary.\n", 473 | "\n", 474 | "\n", 475 | "
**Figure 2** : **dictionary_to_vector() and vector_to_dictionary()**
You will need these functions in gradient_check_n()
\n", 476 | "\n", 477 | "We have also converted the \"gradients\" dictionary into a vector \"grad\" using gradients_to_vector(). You don't need to worry about that.\n", 478 | "\n", 479 | "**Exercise**: Implement gradient_check_n().\n", 480 | "\n", 481 | "**Instructions**: Here is pseudo-code that will help you implement the gradient check.\n", 482 | "\n", 483 | "For each i in num_parameters:\n", 484 | "- To compute `J_plus[i]`:\n", 485 | " 1. Set $\\theta^{+}$ to `np.copy(parameters_values)`\n", 486 | " 2. Set $\\theta^{+}_i$ to $\\theta^{+}_i + \\varepsilon$\n", 487 | " 3. Calculate $J^{+}_i$ using to `forward_propagation_n(x, y, vector_to_dictionary(`$\\theta^{+}$ `))`. \n", 488 | "- To compute `J_minus[i]`: do the same thing with $\\theta^{-}$\n", 489 | "- Compute $gradapprox[i] = \\frac{J^{+}_i - J^{-}_i}{2 \\varepsilon}$\n", 490 | "\n", 491 | "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", 492 | "$$ difference = \\frac {\\| grad - gradapprox \\|_2}{\\| grad \\|_2 + \\| gradapprox \\|_2 } \\tag{3}$$" 493 | ] 494 | }, 495 | { 496 | "cell_type": "code", 497 | "execution_count": 60, 498 | "metadata": { 499 | "collapsed": true 500 | }, 501 | "outputs": [], 502 | "source": [ 503 | "# GRADED FUNCTION: gradient_check_n\n", 504 | "\n", 505 | "def gradient_check_n(parameters, gradients, X, Y, epsilon = 1e-7):\n", 506 | " \"\"\"\n", 507 | " Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n\n", 508 | " \n", 509 | " Arguments:\n", 510 | " parameters -- python dictionary containing your parameters \"W1\", \"b1\", \"W2\", \"b2\", \"W3\", \"b3\":\n", 511 | " grad -- output of backward_propagation_n, contains gradients of the cost with respect to the parameters. \n", 512 | " x -- input datapoint, of shape (input size, 1)\n", 513 | " y -- true \"label\"\n", 514 | " epsilon -- tiny shift to the input to compute approximated gradient with formula(1)\n", 515 | " \n", 516 | " Returns:\n", 517 | " difference -- difference (2) between the approximated gradient and the backward propagation gradient\n", 518 | " \"\"\"\n", 519 | " \n", 520 | " # Set-up variables\n", 521 | " parameters_values, _ = dictionary_to_vector(parameters)\n", 522 | " grad = gradients_to_vector(gradients)\n", 523 | " num_parameters = parameters_values.shape[0]\n", 524 | " J_plus = np.zeros((num_parameters, 1))\n", 525 | " J_minus = np.zeros((num_parameters, 1))\n", 526 | " gradapprox = np.zeros((num_parameters, 1))\n", 527 | " \n", 528 | " # Compute gradapprox\n", 529 | " for i in range(num_parameters):\n", 530 | " \n", 531 | " # Compute J_plus[i]. Inputs: \"parameters_values, epsilon\". Output = \"J_plus[i]\".\n", 532 | " # \"_\" is used because the function you have to outputs two parameters but we only care about the first one\n", 533 | " ### START CODE HERE ### (approx. 3 lines)\n", 534 | " thetaplus = np.copy(parameters_values) # Step 1\n", 535 | " thetaplus[i][0] = thetaplus[i][0]+epsilon # Step 2\n", 536 | " J_plus[i], _ = forward_propagation_n(X,Y,vector_to_dictionary(thetaplus)) # Step 3\n", 537 | " ### END CODE HERE ###\n", 538 | " \n", 539 | " # Compute J_minus[i]. Inputs: \"parameters_values, epsilon\". Output = \"J_minus[i]\".\n", 540 | " ### START CODE HERE ### (approx. 3 lines)\n", 541 | " thetaminus = np.copy(parameters_values) # Step 1\n", 542 | " thetaminus[i][0] = thetaminus[i][0]-epsilon # Step 2 \n", 543 | " J_minus[i], _ = forward_propagation_n(X,Y,vector_to_dictionary(thetaminus)) # Step 3\n", 544 | " ### END CODE HERE ###\n", 545 | " \n", 546 | " # Compute gradapprox[i]\n", 547 | " ### START CODE HERE ### (approx. 1 line)\n", 548 | " gradapprox[i] = ((J_plus[i]-J_minus[i])/(2*epsilon))\n", 549 | " ### END CODE HERE ###\n", 550 | " \n", 551 | " # Compare gradapprox to backward propagation gradients by computing difference.\n", 552 | " ### START CODE HERE ### (approx. 1 line)\n", 553 | " numerator = np.linalg.norm(grad-gradapprox) # Step 1'\n", 554 | " denominator = np.linalg.norm(grad)+np.linalg.norm(gradapprox) # Step 2'\n", 555 | " difference = numerator/denominator # Step 3'\n", 556 | " ### END CODE HERE ###\n", 557 | "\n", 558 | " if difference > 2e-7:\n", 559 | " print (\"\\033[93m\" + \"There is a mistake in the backward propagation! difference = \" + str(difference) + \"\\033[0m\")\n", 560 | " else:\n", 561 | " print (\"\\033[92m\" + \"Your backward propagation works perfectly fine! difference = \" + str(difference) + \"\\033[0m\")\n", 562 | " \n", 563 | " return difference" 564 | ] 565 | }, 566 | { 567 | "cell_type": "code", 568 | "execution_count": 61, 569 | "metadata": { 570 | "scrolled": false 571 | }, 572 | "outputs": [ 573 | { 574 | "name": "stdout", 575 | "output_type": "stream", 576 | "text": [ 577 | "\u001b[93mThere is a mistake in the backward propagation! difference = 0.285093156654\u001b[0m\n" 578 | ] 579 | } 580 | ], 581 | "source": [ 582 | "X, Y, parameters = gradient_check_n_test_case()\n", 583 | "\n", 584 | "cost, cache = forward_propagation_n(X, Y, parameters)\n", 585 | "gradients = backward_propagation_n(X, Y, cache)\n", 586 | "difference = gradient_check_n(parameters, gradients, X, Y)" 587 | ] 588 | }, 589 | { 590 | "cell_type": "markdown", 591 | "metadata": {}, 592 | "source": [ 593 | "**Expected output**:\n", 594 | "\n", 595 | "\n", 596 | " \n", 597 | " \n", 598 | " \n", 599 | " \n", 600 | "
** There is a mistake in the backward propagation!** difference = 0.285093156781
" 601 | ] 602 | }, 603 | { 604 | "cell_type": "markdown", 605 | "metadata": {}, 606 | "source": [ 607 | "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. \n", 608 | "\n", 609 | "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. \n", 610 | "\n", 611 | "**Note** \n", 612 | "- 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", 613 | "- 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", 614 | "\n", 615 | "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. :) \n", 616 | "\n", 617 | "\n", 618 | "**What you should remember from this notebook**:\n", 619 | "- Gradient checking verifies closeness between the gradients from backpropagation and the numerical approximation of the gradient (computed using forward propagation).\n", 620 | "- 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. " 621 | ] 622 | }, 623 | { 624 | "cell_type": "code", 625 | "execution_count": null, 626 | "metadata": { 627 | "collapsed": true 628 | }, 629 | "outputs": [], 630 | "source": [] 631 | } 632 | ], 633 | "metadata": { 634 | "coursera": { 635 | "course_slug": "deep-neural-network", 636 | "graded_item_id": "n6NBD", 637 | "launcher_item_id": "yfOsE" 638 | }, 639 | "kernelspec": { 640 | "display_name": "Python 3", 641 | "language": "python", 642 | "name": "python3" 643 | }, 644 | "language_info": { 645 | "codemirror_mode": { 646 | "name": "ipython", 647 | "version": 3 648 | }, 649 | "file_extension": ".py", 650 | "mimetype": "text/x-python", 651 | "name": "python", 652 | "nbconvert_exporter": "python", 653 | "pygments_lexer": "ipython3", 654 | "version": "3.6.0" 655 | } 656 | }, 657 | "nbformat": 4, 658 | "nbformat_minor": 1 659 | } 660 | -------------------------------------------------------------------------------- /My Notes/.ipynb_checkpoints/Vectorization-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "[1 2 3 4]\n" 13 | ] 14 | } 15 | ], 16 | "source": [ 17 | "import numpy as np\n", 18 | "\n", 19 | "a= np.array([1,2,3,4])\n", 20 | "\n", 21 | "print(a)" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": 2, 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "import time\n", 31 | "\n", 32 | "weights = np.random.random(1000000)\n", 33 | "\n", 34 | "inputs = np.random.random(1000000)" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 3, 40 | "metadata": {}, 41 | "outputs": [ 42 | { 43 | "name": "stdout", 44 | "output_type": "stream", 45 | "text": [ 46 | "(1000000,)\n", 47 | "(1000000,)\n" 48 | ] 49 | } 50 | ], 51 | "source": [ 52 | "print(weights.shape)\n", 53 | "print(inputs.shape)" 54 | ] 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "metadata": {}, 59 | "source": [ 60 | "## Vectorized Version" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 4, 66 | "metadata": {}, 67 | "outputs": [ 68 | { 69 | "name": "stdout", 70 | "output_type": "stream", 71 | "text": [ 72 | "Vectorized Version: 1.6379356384277344ms\n", 73 | "Z= 250243.98856325095\n" 74 | ] 75 | } 76 | ], 77 | "source": [ 78 | "tic = time.time()\n", 79 | "\n", 80 | "z= np.dot(weights,inputs)\n", 81 | "\n", 82 | "toc= time.time()\n", 83 | "\n", 84 | "print(\"Vectorized Version: \"+ str(1000*(toc-tic))+\"ms\")\n", 85 | "\n", 86 | "print(\"Z= \"+str(z))" 87 | ] 88 | }, 89 | { 90 | "cell_type": "markdown", 91 | "metadata": {}, 92 | "source": [ 93 | "## Non-Vectorized Version" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": 5, 99 | "metadata": {}, 100 | "outputs": [ 101 | { 102 | "name": "stdout", 103 | "output_type": "stream", 104 | "text": [ 105 | "Non-Vectorized Version: 893.733024597168ms\n", 106 | "Z= 250243.98856324542\n" 107 | ] 108 | } 109 | ], 110 | "source": [ 111 | "z=0\n", 112 | "\n", 113 | "tic = time.time()\n", 114 | "\n", 115 | "for i in range(len(inputs)):\n", 116 | " z += weights[i]*inputs[i]\n", 117 | "\n", 118 | "toc= time.time()\n", 119 | "\n", 120 | "print(\"Non-Vectorized Version: \"+ str(1000*(toc-tic))+\"ms\")\n", 121 | "\n", 122 | "print(\"Z= \"+str(z))" 123 | ] 124 | }, 125 | { 126 | "cell_type": "markdown", 127 | "metadata": {}, 128 | "source": [ 129 | "# Example" 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": 6, 135 | "metadata": {}, 136 | "outputs": [ 137 | { 138 | "data": { 139 | "text/plain": [ 140 | "(6,)" 141 | ] 142 | }, 143 | "execution_count": 6, 144 | "metadata": {}, 145 | "output_type": "execute_result" 146 | } 147 | ], 148 | "source": [ 149 | "v = np.array([2,4,6,8,9,10])\n", 150 | "v.shape" 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": {}, 156 | "source": [ 157 | "We want u = e^v" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": 7, 163 | "metadata": {}, 164 | "outputs": [ 165 | { 166 | "data": { 167 | "text/plain": [ 168 | "6" 169 | ] 170 | }, 171 | "execution_count": 7, 172 | "metadata": {}, 173 | "output_type": "execute_result" 174 | } 175 | ], 176 | "source": [ 177 | "len(v)" 178 | ] 179 | }, 180 | { 181 | "cell_type": "markdown", 182 | "metadata": {}, 183 | "source": [ 184 | "## Non-vectorized" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": 8, 190 | "metadata": {}, 191 | "outputs": [ 192 | { 193 | "name": "stdout", 194 | "output_type": "stream", 195 | "text": [ 196 | "Non-Vectorized Version: 0.1430511474609375 ms\n", 197 | "[[7.38905610e+00]\n", 198 | " [5.45981500e+01]\n", 199 | " [4.03428793e+02]\n", 200 | " [2.98095799e+03]\n", 201 | " [8.10308393e+03]\n", 202 | " [2.20264658e+04]]\n" 203 | ] 204 | } 205 | ], 206 | "source": [ 207 | "import math \n", 208 | "\n", 209 | "tic = time.time()\n", 210 | "\n", 211 | "u = np.zeros((len(v),1))\n", 212 | "\n", 213 | "for i in range(len(v)):\n", 214 | " u[i] = math.exp(v[i])\n", 215 | " \n", 216 | "toc = time.time()\n", 217 | "\n", 218 | "print(\"Non-Vectorized Version: \"+ str(1000*(toc-tic))+\" ms\")\n", 219 | "\n", 220 | "print(u)" 221 | ] 222 | }, 223 | { 224 | "cell_type": "markdown", 225 | "metadata": {}, 226 | "source": [ 227 | "## Vectorized" 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": 9, 233 | "metadata": {}, 234 | "outputs": [ 235 | { 236 | "name": "stdout", 237 | "output_type": "stream", 238 | "text": [ 239 | "Vectorized Version: 0.09298324584960938 ms\n", 240 | "[7.38905610e+00 5.45981500e+01 4.03428793e+02 2.98095799e+03\n", 241 | " 8.10308393e+03 2.20264658e+04]\n" 242 | ] 243 | } 244 | ], 245 | "source": [ 246 | "import math \n", 247 | "\n", 248 | "tic = time.time()\n", 249 | "\n", 250 | "u = np.exp(v)\n", 251 | " \n", 252 | "toc = time.time()\n", 253 | "\n", 254 | "print(\"Vectorized Version: \"+ str(1000*(toc-tic))+\" ms\")\n", 255 | "\n", 256 | "print(u)" 257 | ] 258 | }, 259 | { 260 | "cell_type": "markdown", 261 | "metadata": {}, 262 | "source": [ 263 | "# Vectorizing Logistic Regression" 264 | ] 265 | }, 266 | { 267 | "cell_type": "code", 268 | "execution_count": 10, 269 | "metadata": {}, 270 | "outputs": [], 271 | "source": [ 272 | "inputs = np.array([[2,43,34,1,24]]) #Normal X values - Training examples\n", 273 | "\n", 274 | "weights = np.array([[0.2,0.3,0.4,0.91,0.54]])\n", 275 | "\n", 276 | "bias = np.array([2,4,6,12,43])" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": 11, 282 | "metadata": {}, 283 | "outputs": [ 284 | { 285 | "data": { 286 | "text/plain": [ 287 | "(1, 5)" 288 | ] 289 | }, 290 | "execution_count": 11, 291 | "metadata": {}, 292 | "output_type": "execute_result" 293 | } 294 | ], 295 | "source": [ 296 | "inputs.shape" 297 | ] 298 | }, 299 | { 300 | "cell_type": "code", 301 | "execution_count": 12, 302 | "metadata": {}, 303 | "outputs": [ 304 | { 305 | "data": { 306 | "text/plain": [ 307 | "1" 308 | ] 309 | }, 310 | "execution_count": 12, 311 | "metadata": {}, 312 | "output_type": "execute_result" 313 | } 314 | ], 315 | "source": [ 316 | "len(inputs)" 317 | ] 318 | }, 319 | { 320 | "cell_type": "code", 321 | "execution_count": 13, 322 | "metadata": {}, 323 | "outputs": [ 324 | { 325 | "data": { 326 | "text/plain": [ 327 | "(1, 5)" 328 | ] 329 | }, 330 | "execution_count": 13, 331 | "metadata": {}, 332 | "output_type": "execute_result" 333 | } 334 | ], 335 | "source": [ 336 | "weights.shape" 337 | ] 338 | }, 339 | { 340 | "cell_type": "code", 341 | "execution_count": 14, 342 | "metadata": {}, 343 | "outputs": [ 344 | { 345 | "data": { 346 | "text/plain": [ 347 | "1" 348 | ] 349 | }, 350 | "execution_count": 14, 351 | "metadata": {}, 352 | "output_type": "execute_result" 353 | } 354 | ], 355 | "source": [ 356 | "len(weights)" 357 | ] 358 | }, 359 | { 360 | "cell_type": "markdown", 361 | "metadata": {}, 362 | "source": [ 363 | "## Non-Vectorized" 364 | ] 365 | }, 366 | { 367 | "cell_type": "code", 368 | "execution_count": 15, 369 | "metadata": {}, 370 | "outputs": [ 371 | { 372 | "name": "stdout", 373 | "output_type": "stream", 374 | "text": [ 375 | "Non-Vectorized Version: 0.33092498779296875 ms\n", 376 | "[[ 2.4 12.6 12.8 12.2 47.8 ]\n", 377 | " [ 2.6 16.9 16.2 12.3 50.2 ]\n", 378 | " [ 2.8 21.2 19.6 12.4 52.6 ]\n", 379 | " [ 3.82 43.13 36.94 12.91 64.84]\n", 380 | " [ 3.08 27.22 24.36 12.54 55.96]]\n" 381 | ] 382 | } 383 | ], 384 | "source": [ 385 | "Z = np.zeros((5,5))\n", 386 | "\n", 387 | "tic = time.time()\n", 388 | "\n", 389 | "for i in range(len(weights[0])):\n", 390 | " for j in range(len(inputs[0])):\n", 391 | " Z[i][j]= (weights[0][i]*inputs[0][j])+bias[j]\n", 392 | " \n", 393 | "toc = time.time()\n", 394 | "\n", 395 | "print(\"Non-Vectorized Version: \"+ str(1000*(toc-tic))+\" ms\")\n", 396 | "\n", 397 | "\n", 398 | "print(Z)" 399 | ] 400 | }, 401 | { 402 | "cell_type": "code", 403 | "execution_count": 16, 404 | "metadata": {}, 405 | "outputs": [ 406 | { 407 | "data": { 408 | "text/plain": [ 409 | "(5,)" 410 | ] 411 | }, 412 | "execution_count": 16, 413 | "metadata": {}, 414 | "output_type": "execute_result" 415 | } 416 | ], 417 | "source": [ 418 | "Z = np.zeros((len(bias)))\n", 419 | "Z.shape" 420 | ] 421 | }, 422 | { 423 | "cell_type": "code", 424 | "execution_count": 17, 425 | "metadata": {}, 426 | "outputs": [ 427 | { 428 | "data": { 429 | "text/plain": [ 430 | "0.0" 431 | ] 432 | }, 433 | "execution_count": 17, 434 | "metadata": {}, 435 | "output_type": "execute_result" 436 | } 437 | ], 438 | "source": [ 439 | "Z[4]" 440 | ] 441 | }, 442 | { 443 | "cell_type": "markdown", 444 | "metadata": {}, 445 | "source": [ 446 | "## Vectorized" 447 | ] 448 | }, 449 | { 450 | "cell_type": "code", 451 | "execution_count": 18, 452 | "metadata": {}, 453 | "outputs": [ 454 | { 455 | "name": "stdout", 456 | "output_type": "stream", 457 | "text": [ 458 | "Vectorized Version: 0.2498626708984375 ms\n", 459 | "[[ 2.4 12.6 12.8 12.2 47.8 ]\n", 460 | " [ 2.6 16.9 16.2 12.3 50.2 ]\n", 461 | " [ 2.8 21.2 19.6 12.4 52.6 ]\n", 462 | " [ 3.82 43.13 36.94 12.91 64.84]\n", 463 | " [ 3.08 27.22 24.36 12.54 55.96]]\n" 464 | ] 465 | } 466 | ], 467 | "source": [ 468 | "tic = time.time()\n", 469 | "\n", 470 | "Z= (np.dot(weights.T,inputs))+bias #Multiply will multiply all numbers in a array\n", 471 | " \n", 472 | "toc = time.time()\n", 473 | "\n", 474 | "print(\"Vectorized Version: \"+ str(1000*(toc-tic))+\" ms\")\n", 475 | "\n", 476 | "print(Z)" 477 | ] 478 | }, 479 | { 480 | "cell_type": "code", 481 | "execution_count": 19, 482 | "metadata": {}, 483 | "outputs": [ 484 | { 485 | "data": { 486 | "text/plain": [ 487 | "numpy.ndarray" 488 | ] 489 | }, 490 | "execution_count": 19, 491 | "metadata": {}, 492 | "output_type": "execute_result" 493 | } 494 | ], 495 | "source": [ 496 | "type(Z)" 497 | ] 498 | }, 499 | { 500 | "cell_type": "markdown", 501 | "metadata": {}, 502 | "source": [ 503 | "## Example" 504 | ] 505 | }, 506 | { 507 | "cell_type": "code", 508 | "execution_count": 20, 509 | "metadata": {}, 510 | "outputs": [], 511 | "source": [ 512 | "# Number of features\n", 513 | "n = 1000\n", 514 | "# Number of training examples\n", 515 | "m = 10000\n", 516 | "# Initialize X and W\n", 517 | "X = np.random.rand(n,m)\n", 518 | "W = np.random.rand(n,1)" 519 | ] 520 | }, 521 | { 522 | "cell_type": "code", 523 | "execution_count": 21, 524 | "metadata": {}, 525 | "outputs": [ 526 | { 527 | "data": { 528 | "text/plain": [ 529 | "(1000, 10000)" 530 | ] 531 | }, 532 | "execution_count": 21, 533 | "metadata": {}, 534 | "output_type": "execute_result" 535 | } 536 | ], 537 | "source": [ 538 | "X.shape" 539 | ] 540 | }, 541 | { 542 | "cell_type": "code", 543 | "execution_count": 22, 544 | "metadata": {}, 545 | "outputs": [ 546 | { 547 | "data": { 548 | "text/plain": [ 549 | "(1000, 1)" 550 | ] 551 | }, 552 | "execution_count": 22, 553 | "metadata": {}, 554 | "output_type": "execute_result" 555 | } 556 | ], 557 | "source": [ 558 | "W.shape" 559 | ] 560 | }, 561 | { 562 | "cell_type": "markdown", 563 | "metadata": {}, 564 | "source": [ 565 | "## Vectorizing Logistic Regression's Gradient Output" 566 | ] 567 | }, 568 | { 569 | "cell_type": "code", 570 | "execution_count": null, 571 | "metadata": {}, 572 | "outputs": [], 573 | "source": [] 574 | }, 575 | { 576 | "cell_type": "code", 577 | "execution_count": null, 578 | "metadata": {}, 579 | "outputs": [], 580 | "source": [] 581 | }, 582 | { 583 | "cell_type": "code", 584 | "execution_count": null, 585 | "metadata": {}, 586 | "outputs": [], 587 | "source": [] 588 | }, 589 | { 590 | "cell_type": "code", 591 | "execution_count": null, 592 | "metadata": {}, 593 | "outputs": [], 594 | "source": [] 595 | }, 596 | { 597 | "cell_type": "code", 598 | "execution_count": null, 599 | "metadata": {}, 600 | "outputs": [], 601 | "source": [] 602 | }, 603 | { 604 | "cell_type": "code", 605 | "execution_count": null, 606 | "metadata": {}, 607 | "outputs": [], 608 | "source": [] 609 | }, 610 | { 611 | "cell_type": "code", 612 | "execution_count": null, 613 | "metadata": {}, 614 | "outputs": [], 615 | "source": [] 616 | }, 617 | { 618 | "cell_type": "code", 619 | "execution_count": null, 620 | "metadata": {}, 621 | "outputs": [], 622 | "source": [] 623 | }, 624 | { 625 | "cell_type": "code", 626 | "execution_count": null, 627 | "metadata": {}, 628 | "outputs": [], 629 | "source": [] 630 | }, 631 | { 632 | "cell_type": "code", 633 | "execution_count": null, 634 | "metadata": {}, 635 | "outputs": [], 636 | "source": [] 637 | }, 638 | { 639 | "cell_type": "code", 640 | "execution_count": null, 641 | "metadata": {}, 642 | "outputs": [], 643 | "source": [] 644 | }, 645 | { 646 | "cell_type": "code", 647 | "execution_count": null, 648 | "metadata": {}, 649 | "outputs": [], 650 | "source": [] 651 | } 652 | ], 653 | "metadata": { 654 | "kernelspec": { 655 | "display_name": "Python 3", 656 | "language": "python", 657 | "name": "python3" 658 | }, 659 | "language_info": { 660 | "codemirror_mode": { 661 | "name": "ipython", 662 | "version": 3 663 | }, 664 | "file_extension": ".py", 665 | "mimetype": "text/x-python", 666 | "name": "python", 667 | "nbconvert_exporter": "python", 668 | "pygments_lexer": "ipython3", 669 | "version": "3.7.3" 670 | } 671 | }, 672 | "nbformat": 4, 673 | "nbformat_minor": 4 674 | } 675 | -------------------------------------------------------------------------------- /My Notes/Vectorization.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 195, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "[1 2 3 4]\n" 13 | ] 14 | } 15 | ], 16 | "source": [ 17 | "import numpy as np\n", 18 | "\n", 19 | "a= np.array([1,2,3,4])\n", 20 | "\n", 21 | "print(a)" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": 196, 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "import time\n", 31 | "\n", 32 | "weights = np.random.random(1000000)\n", 33 | "\n", 34 | "inputs = np.random.random(1000000)" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 197, 40 | "metadata": {}, 41 | "outputs": [ 42 | { 43 | "name": "stdout", 44 | "output_type": "stream", 45 | "text": [ 46 | "(1000000,)\n", 47 | "(1000000,)\n" 48 | ] 49 | } 50 | ], 51 | "source": [ 52 | "print(weights.shape)\n", 53 | "print(inputs.shape)" 54 | ] 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "metadata": {}, 59 | "source": [ 60 | "## Vectorized Version" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 198, 66 | "metadata": {}, 67 | "outputs": [ 68 | { 69 | "name": "stdout", 70 | "output_type": "stream", 71 | "text": [ 72 | "Vectorized Version: 11.04593276977539ms\n", 73 | "Z= 249920.585897757\n" 74 | ] 75 | } 76 | ], 77 | "source": [ 78 | "tic = time.time()\n", 79 | "\n", 80 | "z= np.dot(weights,inputs)\n", 81 | "\n", 82 | "toc= time.time()\n", 83 | "\n", 84 | "print(\"Vectorized Version: \"+ str(1000*(toc-tic))+\"ms\")\n", 85 | "\n", 86 | "print(\"Z= \"+str(z))" 87 | ] 88 | }, 89 | { 90 | "cell_type": "markdown", 91 | "metadata": {}, 92 | "source": [ 93 | "## Non-Vectorized Version" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": 199, 99 | "metadata": {}, 100 | "outputs": [ 101 | { 102 | "name": "stdout", 103 | "output_type": "stream", 104 | "text": [ 105 | "Non-Vectorized Version: 930.0210475921631ms\n", 106 | "Z= 249920.58589777275\n" 107 | ] 108 | } 109 | ], 110 | "source": [ 111 | "z=0\n", 112 | "\n", 113 | "tic = time.time()\n", 114 | "\n", 115 | "for i in range(len(inputs)):\n", 116 | " z += weights[i]*inputs[i]\n", 117 | "\n", 118 | "toc= time.time()\n", 119 | "\n", 120 | "print(\"Non-Vectorized Version: \"+ str(1000*(toc-tic))+\"ms\")\n", 121 | "\n", 122 | "print(\"Z= \"+str(z))" 123 | ] 124 | }, 125 | { 126 | "cell_type": "markdown", 127 | "metadata": {}, 128 | "source": [ 129 | "# Example" 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": 200, 135 | "metadata": {}, 136 | "outputs": [ 137 | { 138 | "data": { 139 | "text/plain": [ 140 | "(6,)" 141 | ] 142 | }, 143 | "execution_count": 200, 144 | "metadata": {}, 145 | "output_type": "execute_result" 146 | } 147 | ], 148 | "source": [ 149 | "v = np.array([2,4,6,8,9,10])\n", 150 | "v.shape" 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": {}, 156 | "source": [ 157 | "We want u = e^v" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": 201, 163 | "metadata": {}, 164 | "outputs": [ 165 | { 166 | "data": { 167 | "text/plain": [ 168 | "6" 169 | ] 170 | }, 171 | "execution_count": 201, 172 | "metadata": {}, 173 | "output_type": "execute_result" 174 | } 175 | ], 176 | "source": [ 177 | "len(v)" 178 | ] 179 | }, 180 | { 181 | "cell_type": "markdown", 182 | "metadata": {}, 183 | "source": [ 184 | "## Non-vectorized" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": 202, 190 | "metadata": {}, 191 | "outputs": [ 192 | { 193 | "name": "stdout", 194 | "output_type": "stream", 195 | "text": [ 196 | "Non-Vectorized Version: 0.2472400665283203 ms\n", 197 | "[[7.38905610e+00]\n", 198 | " [5.45981500e+01]\n", 199 | " [4.03428793e+02]\n", 200 | " [2.98095799e+03]\n", 201 | " [8.10308393e+03]\n", 202 | " [2.20264658e+04]]\n" 203 | ] 204 | } 205 | ], 206 | "source": [ 207 | "import math \n", 208 | "\n", 209 | "tic = time.time()\n", 210 | "\n", 211 | "u = np.zeros((len(v),1))\n", 212 | "\n", 213 | "for i in range(len(v)):\n", 214 | " u[i] = math.exp(v[i])\n", 215 | " \n", 216 | "toc = time.time()\n", 217 | "\n", 218 | "print(\"Non-Vectorized Version: \"+ str(1000*(toc-tic))+\" ms\")\n", 219 | "\n", 220 | "print(u)" 221 | ] 222 | }, 223 | { 224 | "cell_type": "markdown", 225 | "metadata": {}, 226 | "source": [ 227 | "## Vectorized" 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": 203, 233 | "metadata": {}, 234 | "outputs": [ 235 | { 236 | "name": "stdout", 237 | "output_type": "stream", 238 | "text": [ 239 | "Vectorized Version: 0.15687942504882812 ms\n", 240 | "[7.38905610e+00 5.45981500e+01 4.03428793e+02 2.98095799e+03\n", 241 | " 8.10308393e+03 2.20264658e+04]\n" 242 | ] 243 | } 244 | ], 245 | "source": [ 246 | "import math \n", 247 | "\n", 248 | "tic = time.time()\n", 249 | "\n", 250 | "u = np.exp(v)\n", 251 | " \n", 252 | "toc = time.time()\n", 253 | "\n", 254 | "print(\"Vectorized Version: \"+ str(1000*(toc-tic))+\" ms\")\n", 255 | "\n", 256 | "print(u)" 257 | ] 258 | }, 259 | { 260 | "cell_type": "markdown", 261 | "metadata": {}, 262 | "source": [ 263 | "# Vectorizing Logistic Regression" 264 | ] 265 | }, 266 | { 267 | "cell_type": "code", 268 | "execution_count": 204, 269 | "metadata": {}, 270 | "outputs": [], 271 | "source": [ 272 | "inputs = np.array([[2,43,34,1,24]]) #Normal X values - Training examples\n", 273 | "\n", 274 | "weights = np.array([[0.2,0.3,0.4,0.91,0.54]])\n", 275 | "\n", 276 | "bias = np.array([2,4,6,12,43])" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": 205, 282 | "metadata": {}, 283 | "outputs": [ 284 | { 285 | "data": { 286 | "text/plain": [ 287 | "(1, 5)" 288 | ] 289 | }, 290 | "execution_count": 205, 291 | "metadata": {}, 292 | "output_type": "execute_result" 293 | } 294 | ], 295 | "source": [ 296 | "inputs.shape" 297 | ] 298 | }, 299 | { 300 | "cell_type": "code", 301 | "execution_count": 206, 302 | "metadata": {}, 303 | "outputs": [ 304 | { 305 | "data": { 306 | "text/plain": [ 307 | "1" 308 | ] 309 | }, 310 | "execution_count": 206, 311 | "metadata": {}, 312 | "output_type": "execute_result" 313 | } 314 | ], 315 | "source": [ 316 | "len(inputs)" 317 | ] 318 | }, 319 | { 320 | "cell_type": "code", 321 | "execution_count": 207, 322 | "metadata": {}, 323 | "outputs": [ 324 | { 325 | "data": { 326 | "text/plain": [ 327 | "(1, 5)" 328 | ] 329 | }, 330 | "execution_count": 207, 331 | "metadata": {}, 332 | "output_type": "execute_result" 333 | } 334 | ], 335 | "source": [ 336 | "weights.shape" 337 | ] 338 | }, 339 | { 340 | "cell_type": "code", 341 | "execution_count": 208, 342 | "metadata": {}, 343 | "outputs": [ 344 | { 345 | "data": { 346 | "text/plain": [ 347 | "1" 348 | ] 349 | }, 350 | "execution_count": 208, 351 | "metadata": {}, 352 | "output_type": "execute_result" 353 | } 354 | ], 355 | "source": [ 356 | "len(weights)" 357 | ] 358 | }, 359 | { 360 | "cell_type": "markdown", 361 | "metadata": {}, 362 | "source": [ 363 | "## Non-Vectorized" 364 | ] 365 | }, 366 | { 367 | "cell_type": "code", 368 | "execution_count": 217, 369 | "metadata": {}, 370 | "outputs": [ 371 | { 372 | "name": "stdout", 373 | "output_type": "stream", 374 | "text": [ 375 | "Non-Vectorized Version: 2.0148754119873047 ms\n", 376 | "[[ 2.4 12.6 12.8 12.2 47.8 ]\n", 377 | " [ 2.6 16.9 16.2 12.3 50.2 ]\n", 378 | " [ 2.8 21.2 19.6 12.4 52.6 ]\n", 379 | " [ 3.82 43.13 36.94 12.91 64.84]\n", 380 | " [ 3.08 27.22 24.36 12.54 55.96]]\n" 381 | ] 382 | } 383 | ], 384 | "source": [ 385 | "Z = np.zeros((5,5))\n", 386 | "\n", 387 | "tic = time.time()\n", 388 | "\n", 389 | "for i in range(len(weights[0])):\n", 390 | " for j in range(len(inputs[0])):\n", 391 | " Z[i][j]= (weights[0][i]*inputs[0][j])+bias[j]\n", 392 | " \n", 393 | "toc = time.time()\n", 394 | "\n", 395 | "print(\"Non-Vectorized Version: \"+ str(1000*(toc-tic))+\" ms\")\n", 396 | "\n", 397 | "\n", 398 | "print(Z)" 399 | ] 400 | }, 401 | { 402 | "cell_type": "code", 403 | "execution_count": 218, 404 | "metadata": {}, 405 | "outputs": [ 406 | { 407 | "data": { 408 | "text/plain": [ 409 | "(5,)" 410 | ] 411 | }, 412 | "execution_count": 218, 413 | "metadata": {}, 414 | "output_type": "execute_result" 415 | } 416 | ], 417 | "source": [ 418 | "Z = np.zeros((len(bias)))\n", 419 | "Z.shape" 420 | ] 421 | }, 422 | { 423 | "cell_type": "code", 424 | "execution_count": 219, 425 | "metadata": {}, 426 | "outputs": [ 427 | { 428 | "data": { 429 | "text/plain": [ 430 | "0.0" 431 | ] 432 | }, 433 | "execution_count": 219, 434 | "metadata": {}, 435 | "output_type": "execute_result" 436 | } 437 | ], 438 | "source": [ 439 | "Z[4]" 440 | ] 441 | }, 442 | { 443 | "cell_type": "markdown", 444 | "metadata": {}, 445 | "source": [ 446 | "## Vectorized" 447 | ] 448 | }, 449 | { 450 | "cell_type": "code", 451 | "execution_count": 212, 452 | "metadata": {}, 453 | "outputs": [ 454 | { 455 | "name": "stdout", 456 | "output_type": "stream", 457 | "text": [ 458 | "Vectorized Version: 3.7276744842529297 ms\n", 459 | "[[ 2.4 12.6 12.8 12.2 47.8 ]\n", 460 | " [ 2.6 16.9 16.2 12.3 50.2 ]\n", 461 | " [ 2.8 21.2 19.6 12.4 52.6 ]\n", 462 | " [ 3.82 43.13 36.94 12.91 64.84]\n", 463 | " [ 3.08 27.22 24.36 12.54 55.96]]\n" 464 | ] 465 | } 466 | ], 467 | "source": [ 468 | "tic = time.time()\n", 469 | "\n", 470 | "Z= (np.dot(weights.T,inputs))+bias #Multiply will multiply all numbers in a array\n", 471 | " \n", 472 | "toc = time.time()\n", 473 | "\n", 474 | "print(\"Vectorized Version: \"+ str(1000*(toc-tic))+\" ms\")\n", 475 | "\n", 476 | "print(Z)" 477 | ] 478 | }, 479 | { 480 | "cell_type": "code", 481 | "execution_count": 213, 482 | "metadata": {}, 483 | "outputs": [ 484 | { 485 | "data": { 486 | "text/plain": [ 487 | "numpy.ndarray" 488 | ] 489 | }, 490 | "execution_count": 213, 491 | "metadata": {}, 492 | "output_type": "execute_result" 493 | } 494 | ], 495 | "source": [ 496 | "type(Z)" 497 | ] 498 | }, 499 | { 500 | "cell_type": "markdown", 501 | "metadata": {}, 502 | "source": [ 503 | "## Example" 504 | ] 505 | }, 506 | { 507 | "cell_type": "code", 508 | "execution_count": 214, 509 | "metadata": {}, 510 | "outputs": [], 511 | "source": [ 512 | "# Number of features\n", 513 | "n = 1000\n", 514 | "# Number of training examples\n", 515 | "m = 10000\n", 516 | "# Initialize X and W\n", 517 | "X = np.random.rand(n,m)\n", 518 | "W = np.random.rand(n,1)" 519 | ] 520 | }, 521 | { 522 | "cell_type": "code", 523 | "execution_count": 215, 524 | "metadata": {}, 525 | "outputs": [ 526 | { 527 | "data": { 528 | "text/plain": [ 529 | "(1000, 10000)" 530 | ] 531 | }, 532 | "execution_count": 215, 533 | "metadata": {}, 534 | "output_type": "execute_result" 535 | } 536 | ], 537 | "source": [ 538 | "X.shape" 539 | ] 540 | }, 541 | { 542 | "cell_type": "code", 543 | "execution_count": 216, 544 | "metadata": {}, 545 | "outputs": [ 546 | { 547 | "data": { 548 | "text/plain": [ 549 | "(1000, 1)" 550 | ] 551 | }, 552 | "execution_count": 216, 553 | "metadata": {}, 554 | "output_type": "execute_result" 555 | } 556 | ], 557 | "source": [ 558 | "W.shape" 559 | ] 560 | }, 561 | { 562 | "cell_type": "markdown", 563 | "metadata": {}, 564 | "source": [ 565 | "## Vectorizing Logistic Regression's Gradient Output" 566 | ] 567 | }, 568 | { 569 | "cell_type": "code", 570 | "execution_count": null, 571 | "metadata": {}, 572 | "outputs": [], 573 | "source": [] 574 | }, 575 | { 576 | "cell_type": "code", 577 | "execution_count": null, 578 | "metadata": {}, 579 | "outputs": [], 580 | "source": [] 581 | }, 582 | { 583 | "cell_type": "code", 584 | "execution_count": null, 585 | "metadata": {}, 586 | "outputs": [], 587 | "source": [] 588 | }, 589 | { 590 | "cell_type": "code", 591 | "execution_count": null, 592 | "metadata": {}, 593 | "outputs": [], 594 | "source": [] 595 | }, 596 | { 597 | "cell_type": "code", 598 | "execution_count": null, 599 | "metadata": {}, 600 | "outputs": [], 601 | "source": [] 602 | }, 603 | { 604 | "cell_type": "code", 605 | "execution_count": null, 606 | "metadata": {}, 607 | "outputs": [], 608 | "source": [] 609 | }, 610 | { 611 | "cell_type": "code", 612 | "execution_count": null, 613 | "metadata": {}, 614 | "outputs": [], 615 | "source": [] 616 | }, 617 | { 618 | "cell_type": "code", 619 | "execution_count": null, 620 | "metadata": {}, 621 | "outputs": [], 622 | "source": [] 623 | }, 624 | { 625 | "cell_type": "code", 626 | "execution_count": 92, 627 | "metadata": {}, 628 | "outputs": [], 629 | "source": [ 630 | "t=[[1,2],[2,8],[9,14],[15,18]]" 631 | ] 632 | }, 633 | { 634 | "cell_type": "code", 635 | "execution_count": 93, 636 | "metadata": {}, 637 | "outputs": [ 638 | { 639 | "data": { 640 | "text/plain": [ 641 | "[0, 1, 2, 3]" 642 | ] 643 | }, 644 | "execution_count": 93, 645 | "metadata": {}, 646 | "output_type": "execute_result" 647 | } 648 | ], 649 | "source": [ 650 | "list(range(len(t)))" 651 | ] 652 | }, 653 | { 654 | "cell_type": "code", 655 | "execution_count": 94, 656 | "metadata": {}, 657 | "outputs": [ 658 | { 659 | "data": { 660 | "text/plain": [ 661 | "15" 662 | ] 663 | }, 664 | "execution_count": 94, 665 | "metadata": {}, 666 | "output_type": "execute_result" 667 | } 668 | ], 669 | "source": [ 670 | "t[3][0]" 671 | ] 672 | }, 673 | { 674 | "cell_type": "code", 675 | "execution_count": 95, 676 | "metadata": {}, 677 | "outputs": [ 678 | { 679 | "data": { 680 | "text/plain": [ 681 | "4" 682 | ] 683 | }, 684 | "execution_count": 95, 685 | "metadata": {}, 686 | "output_type": "execute_result" 687 | } 688 | ], 689 | "source": [ 690 | "len(t)" 691 | ] 692 | }, 693 | { 694 | "cell_type": "code", 695 | "execution_count": 96, 696 | "metadata": {}, 697 | "outputs": [], 698 | "source": [ 699 | "c=[]\n", 700 | "for i in list(range(len(t))):\n", 701 | " if t[i][0] <= t[i][1]:\n", 702 | " if i!=len(t)-1:\n", 703 | " if t[i][1]==t[i+1][0] or t[i+1][0]" 117 | ] 118 | }, 119 | "metadata": { 120 | "tags": [] 121 | }, 122 | "execution_count": 4 123 | } 124 | ] 125 | }, 126 | { 127 | "cell_type": "markdown", 128 | "metadata": { 129 | "id": "PpNM6pqK01vy" 130 | }, 131 | "source": [ 132 | "### Defining a Variable" 133 | ] 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "metadata": { 138 | "id": "GhEWWH_YkbKm" 139 | }, 140 | "source": [ 141 | "Remember to initialize your variables, create a session and run the operations inside the session." 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "metadata": { 147 | "colab": { 148 | "base_uri": "https://localhost:8080/" 149 | }, 150 | "id": "RtIn73Pajp-G", 151 | "outputId": "008719a0-83a3-4c77-cb05-cffd93a1fa3b" 152 | }, 153 | "source": [ 154 | "a = tf.constant(4)\n", 155 | "b = tf.constant(21)\n", 156 | "c = tf.multiply(a,b)\n", 157 | "print(c) # It wont giive us 88, To do that, we need to run a session" 158 | ], 159 | "execution_count": 5, 160 | "outputs": [ 161 | { 162 | "output_type": "stream", 163 | "text": [ 164 | "Tensor(\"Mul:0\", shape=(), dtype=int32)\n" 165 | ], 166 | "name": "stdout" 167 | } 168 | ] 169 | }, 170 | { 171 | "cell_type": "code", 172 | "metadata": { 173 | "colab": { 174 | "base_uri": "https://localhost:8080/" 175 | }, 176 | "id": "askuHpHbjrBZ", 177 | "outputId": "2806d1ec-33f9-40f8-dbac-82280c12a2de" 178 | }, 179 | "source": [ 180 | "sess=tf.Session()\n", 181 | "print(sess.run(c))" 182 | ], 183 | "execution_count": 6, 184 | "outputs": [ 185 | { 186 | "output_type": "stream", 187 | "text": [ 188 | "84\n" 189 | ], 190 | "name": "stdout" 191 | } 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "metadata": { 197 | "id": "v-cPNgrIk-WQ" 198 | }, 199 | "source": [ 200 | "A placeholder is an object whose value you can specify only later. To specify values for a placeholder, you can pass in values by using a \"feed dictionary\" (feed_dict variable). " 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "metadata": { 206 | "colab": { 207 | "base_uri": "https://localhost:8080/" 208 | }, 209 | "id": "M59mewEqjq86", 210 | "outputId": "386a30f1-29f5-4254-bf28-e4733a68d313" 211 | }, 212 | "source": [ 213 | "x = tf.placeholder(tf.int64, name = 'x')\n", 214 | "print(sess.run(2 * x, feed_dict = {x: 43}))\n", 215 | "sess.close()" 216 | ], 217 | "execution_count": 7, 218 | "outputs": [ 219 | { 220 | "output_type": "stream", 221 | "text": [ 222 | "86\n" 223 | ], 224 | "name": "stdout" 225 | } 226 | ] 227 | }, 228 | { 229 | "cell_type": "markdown", 230 | "metadata": { 231 | "id": "XCzMzy8cluji" 232 | }, 233 | "source": [ 234 | "When you first defined x you did not have to specify a value for it. A placeholder is simply a variable that you will assign data to only later, when running the session. We say that you feed data to these placeholders when running the session." 235 | ] 236 | }, 237 | { 238 | "cell_type": "markdown", 239 | "metadata": { 240 | "id": "FcrX3avL1V1U" 241 | }, 242 | "source": [ 243 | "### Matrix Multipication" 244 | ] 245 | }, 246 | { 247 | "cell_type": "code", 248 | "metadata": { 249 | "id": "-5Be2Bv7jqyx" 250 | }, 251 | "source": [ 252 | "X = tf.constant(np.random.randn(3,1), name = \"X\")\n", 253 | "W = tf.constant(np.random.randn(4,3), name = \"W\")\n", 254 | "\n", 255 | "result = tf.matmul(W,X)" 256 | ], 257 | "execution_count": 8, 258 | "outputs": [] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "metadata": { 263 | "id": "mwntv-wDjqse" 264 | }, 265 | "source": [ 266 | "session1 = tf.Session()\n", 267 | "result = session1.run(result)\n", 268 | "session1.close()" 269 | ], 270 | "execution_count": 9, 271 | "outputs": [] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "metadata": { 276 | "colab": { 277 | "base_uri": "https://localhost:8080/" 278 | }, 279 | "id": "8Jz5u43fjqj-", 280 | "outputId": "31936d77-bb8f-4480-ba68-2abc3290b94d" 281 | }, 282 | "source": [ 283 | "result" 284 | ], 285 | "execution_count": 10, 286 | "outputs": [ 287 | { 288 | "output_type": "execute_result", 289 | "data": { 290 | "text/plain": [ 291 | "array([[-0.5450509 ],\n", 292 | " [ 0.35624022],\n", 293 | " [ 0.35442552],\n", 294 | " [-1.46158736]])" 295 | ] 296 | }, 297 | "metadata": { 298 | "tags": [] 299 | }, 300 | "execution_count": 10 301 | } 302 | ] 303 | }, 304 | { 305 | "cell_type": "markdown", 306 | "metadata": { 307 | "id": "uZMTk9uqjlLA" 308 | }, 309 | "source": [ 310 | "## Neural Network" 311 | ] 312 | }, 313 | { 314 | "cell_type": "markdown", 315 | "metadata": { 316 | "id": "crPG1X3efyz5" 317 | }, 318 | "source": [ 319 | "Our cost Function is : (w^2-10w+25)" 320 | ] 321 | }, 322 | { 323 | "cell_type": "code", 324 | "metadata": { 325 | "colab": { 326 | "base_uri": "https://localhost:8080/" 327 | }, 328 | "id": "seb4V_9FdK7P", 329 | "outputId": "916d6128-03d4-4865-abd5-995715add8ed" 330 | }, 331 | "source": [ 332 | "w = tf.Variable(0,dtype= tf.float32)\n", 333 | "#cost = tf.add(tf.add(w**2,tf.multiply(-10.,w)),25)\n", 334 | "cost = w**2 -10*w+25\n", 335 | "train = tf.train.GradientDescentOptimizer(0.01).minimize(cost)\n", 336 | "\n", 337 | "init = tf.global_variables_initializer()\n", 338 | "session = tf.Session()\n", 339 | "session.run(init)\n", 340 | "print(session.run(w))" 341 | ], 342 | "execution_count": 11, 343 | "outputs": [ 344 | { 345 | "output_type": "stream", 346 | "text": [ 347 | "0.0\n" 348 | ], 349 | "name": "stdout" 350 | } 351 | ] 352 | }, 353 | { 354 | "cell_type": "code", 355 | "metadata": { 356 | "colab": { 357 | "base_uri": "https://localhost:8080/" 358 | }, 359 | "id": "qapt12XBdLCN", 360 | "outputId": "9ebe84cd-7edf-467f-ca3b-838ad89c1caf" 361 | }, 362 | "source": [ 363 | "session.run(train)\n", 364 | "print(session.run(w))" 365 | ], 366 | "execution_count": 12, 367 | "outputs": [ 368 | { 369 | "output_type": "stream", 370 | "text": [ 371 | "0.099999994\n" 372 | ], 373 | "name": "stdout" 374 | } 375 | ] 376 | }, 377 | { 378 | "cell_type": "code", 379 | "metadata": { 380 | "colab": { 381 | "base_uri": "https://localhost:8080/" 382 | }, 383 | "id": "oG338x-GdLHe", 384 | "outputId": "2a27475b-6319-4f55-937b-454084b1ca8e" 385 | }, 386 | "source": [ 387 | "for i in range(1000):\n", 388 | " session.run(train)\n", 389 | "print(session.run(w))" 390 | ], 391 | "execution_count": 13, 392 | "outputs": [ 393 | { 394 | "output_type": "stream", 395 | "text": [ 396 | "4.999988\n" 397 | ], 398 | "name": "stdout" 399 | } 400 | ] 401 | }, 402 | { 403 | "cell_type": "markdown", 404 | "metadata": { 405 | "id": "ePpnuMeeg72K" 406 | }, 407 | "source": [ 408 | "Adding a Train Data" 409 | ] 410 | }, 411 | { 412 | "cell_type": "code", 413 | "metadata": { 414 | "colab": { 415 | "base_uri": "https://localhost:8080/" 416 | }, 417 | "id": "uIaJllkpdLMm", 418 | "outputId": "ae9868be-0d38-400c-f0e7-de39e9fdf8d5" 419 | }, 420 | "source": [ 421 | "coefficient = np.array([[1.],[-20.],[100.]])\n", 422 | "\n", 423 | "w = tf.Variable(0,dtype= tf.float32)\n", 424 | "x = tf.placeholder(tf.float32,[3,1]) #Train data\n", 425 | "#cost = tf.add(tf.add(w**2,tf.multiply(-10.,w)),25)\n", 426 | "#cost = w**2 -10*w+25\n", 427 | "cost = x[0][0]*w**2 + x[1][0]*w + x[2][0]\n", 428 | "train = tf.train.GradientDescentOptimizer(0.01).minimize(cost)\n", 429 | "\n", 430 | "init = tf.global_variables_initializer()\n", 431 | "session = tf.Session()\n", 432 | "session.run(init)\n", 433 | "print(session.run(w))" 434 | ], 435 | "execution_count": 14, 436 | "outputs": [ 437 | { 438 | "output_type": "stream", 439 | "text": [ 440 | "0.0\n" 441 | ], 442 | "name": "stdout" 443 | } 444 | ] 445 | }, 446 | { 447 | "cell_type": "code", 448 | "metadata": { 449 | "colab": { 450 | "base_uri": "https://localhost:8080/" 451 | }, 452 | "id": "vaxGzCJ0dLQh", 453 | "outputId": "70deac90-8929-4f75-b2b4-4724ea48b903" 454 | }, 455 | "source": [ 456 | "session.run(train, feed_dict={x: coefficient})\n", 457 | "print(session.run(w))" 458 | ], 459 | "execution_count": 15, 460 | "outputs": [ 461 | { 462 | "output_type": "stream", 463 | "text": [ 464 | "0.19999999\n" 465 | ], 466 | "name": "stdout" 467 | } 468 | ] 469 | }, 470 | { 471 | "cell_type": "code", 472 | "metadata": { 473 | "colab": { 474 | "base_uri": "https://localhost:8080/" 475 | }, 476 | "id": "F0co8w3ddLU1", 477 | "outputId": "cb07dc08-2f86-4106-f298-223b465110f2" 478 | }, 479 | "source": [ 480 | "for i in range(1000):\n", 481 | " session.run(train,feed_dict={x: coefficient})\n", 482 | "print(session.run(w))" 483 | ], 484 | "execution_count": 16, 485 | "outputs": [ 486 | { 487 | "output_type": "stream", 488 | "text": [ 489 | "9.999976\n" 490 | ], 491 | "name": "stdout" 492 | } 493 | ] 494 | } 495 | ] 496 | } -------------------------------------------------------------------------------- /Notations.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/berkayalan/neural-networks-and-deep-learning/590b5b40199f358e911da44f99f6c3e00b0c2934/Notations.pdf -------------------------------------------------------------------------------- /Notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/berkayalan/neural-networks-and-deep-learning/590b5b40199f358e911da44f99f6c3e00b0c2934/Notes.pdf -------------------------------------------------------------------------------- /Optimization_methods_v1b.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Optimization Methods\n", 8 | "\n", 9 | "Until now, you've always used Gradient Descent to update the parameters and minimize the cost. In this notebook, you will learn more advanced optimization methods that can speed up learning and perhaps even get you to a better final value for the cost function. Having a good optimization algorithm can be the difference between waiting days vs. just a few hours to get a good result. \n", 10 | "\n", 11 | "Gradient descent goes \"downhill\" on a cost function $J$. Think of it as trying to do this: \n", 12 | "\n", 13 | "
**Figure 1** : **Minimizing the cost is like finding the lowest point in a hilly landscape**
At each step of the training, you update your parameters following a certain direction to try to get to the lowest possible point.
\n", 14 | "\n", 15 | "**Notations**: As usual, $\\frac{\\partial J}{\\partial a } = $ `da` for any variable `a`.\n", 16 | "\n", 17 | "To get started, run the following code to import the libraries you will need." 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "metadata": {}, 23 | "source": [ 24 | "### Updates to Assignment \n", 25 | "\n", 26 | "#### If you were working on a previous version\n", 27 | "* The current notebook filename is version \"Optimization_methods_v1b\". \n", 28 | "* You can find your work in the file directory as version \"Optimization methods'.\n", 29 | "* To see the file directory, click on the Coursera logo at the top left of the notebook.\n", 30 | "\n", 31 | "#### List of Updates\n", 32 | "* op_utils is now opt_utils_v1a. Assertion statement in `initialize_parameters` is fixed.\n", 33 | "* opt_utils_v1a: `compute_cost` function now accumulates total cost of the batch without taking the average (average is taken for entire epoch instead).\n", 34 | "* In `model` function, the total cost per mini-batch is accumulated, and the average of the entire epoch is taken as the average cost. So the plot of the cost function over time is now a smooth downward curve instead of an oscillating curve.\n", 35 | "* Print statements used to check each function are reformatted, and 'expected output` is reformatted to match the format of the print statements (for easier visual comparisons)." 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": 1, 41 | "metadata": { 42 | "collapsed": true 43 | }, 44 | "outputs": [], 45 | "source": [ 46 | "import numpy as np\n", 47 | "import matplotlib.pyplot as plt\n", 48 | "import scipy.io\n", 49 | "import math\n", 50 | "import sklearn\n", 51 | "import sklearn.datasets\n", 52 | "\n", 53 | "from opt_utils_v1a import load_params_and_grads, initialize_parameters, forward_propagation, backward_propagation\n", 54 | "from opt_utils_v1a import compute_cost, predict, predict_dec, plot_decision_boundary, load_dataset\n", 55 | "from testCases import *\n", 56 | "\n", 57 | "%matplotlib inline\n", 58 | "plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots\n", 59 | "plt.rcParams['image.interpolation'] = 'nearest'\n", 60 | "plt.rcParams['image.cmap'] = 'gray'" 61 | ] 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "metadata": {}, 66 | "source": [ 67 | "## 1 - Gradient Descent\n", 68 | "\n", 69 | "A simple optimization method in machine learning is gradient descent (GD). When you take gradient steps with respect to all $m$ examples on each step, it is also called Batch Gradient Descent. \n", 70 | "\n", 71 | "**Warm-up exercise**: Implement the gradient descent update rule. The gradient descent rule is, for $l = 1, ..., L$: \n", 72 | "$$ W^{[l]} = W^{[l]} - \\alpha \\text{ } dW^{[l]} \\tag{1}$$\n", 73 | "$$ b^{[l]} = b^{[l]} - \\alpha \\text{ } db^{[l]} \\tag{2}$$\n", 74 | "\n", 75 | "where L is the number of layers and $\\alpha$ is the learning rate. All parameters should be stored in the `parameters` dictionary. Note that the iterator `l` starts at 0 in the `for` loop while the first parameters are $W^{[1]}$ and $b^{[1]}$. You need to shift `l` to `l+1` when coding." 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": 2, 81 | "metadata": { 82 | "collapsed": true 83 | }, 84 | "outputs": [], 85 | "source": [ 86 | "# GRADED FUNCTION: update_parameters_with_gd\n", 87 | "\n", 88 | "def update_parameters_with_gd(parameters, grads, learning_rate):\n", 89 | " \"\"\"\n", 90 | " Update parameters using one step of gradient descent\n", 91 | " \n", 92 | " Arguments:\n", 93 | " parameters -- python dictionary containing your parameters to be updated:\n", 94 | " parameters['W' + str(l)] = Wl\n", 95 | " parameters['b' + str(l)] = bl\n", 96 | " grads -- python dictionary containing your gradients to update each parameters:\n", 97 | " grads['dW' + str(l)] = dWl\n", 98 | " grads['db' + str(l)] = dbl\n", 99 | " learning_rate -- the learning rate, scalar.\n", 100 | " \n", 101 | " Returns:\n", 102 | " parameters -- python dictionary containing your updated parameters \n", 103 | " \"\"\"\n", 104 | "\n", 105 | " L = len(parameters) // 2 # number of layers in the neural networks\n", 106 | "\n", 107 | " \n", 108 | " # Update rule for each parameter\n", 109 | " for l in range(L):\n", 110 | " ### START CODE HERE ### (approx. 2 lines)\n", 111 | " parameters[\"W\" + str(l+1)] = parameters[\"W\" + str(l+1)] - learning_rate*(grads['dW' + str(l+1)])\n", 112 | " parameters[\"b\" + str(l+1)] = parameters[\"b\" + str(l+1)] - learning_rate*(grads['db' + str(l+1)])\n", 113 | " ### END CODE HERE ###\n", 114 | " \n", 115 | " return parameters" 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": 3, 121 | "metadata": { 122 | "scrolled": true 123 | }, 124 | "outputs": [ 125 | { 126 | "name": "stdout", 127 | "output_type": "stream", 128 | "text": [ 129 | "W1 =\n", 130 | "[[ 1.63535156 -0.62320365 -0.53718766]\n", 131 | " [-1.07799357 0.85639907 -2.29470142]]\n", 132 | "b1 =\n", 133 | "[[ 1.74604067]\n", 134 | " [-0.75184921]]\n", 135 | "W2 =\n", 136 | "[[ 0.32171798 -0.25467393 1.46902454]\n", 137 | " [-2.05617317 -0.31554548 -0.3756023 ]\n", 138 | " [ 1.1404819 -1.09976462 -0.1612551 ]]\n", 139 | "b2 =\n", 140 | "[[-0.88020257]\n", 141 | " [ 0.02561572]\n", 142 | " [ 0.57539477]]\n" 143 | ] 144 | } 145 | ], 146 | "source": [ 147 | "parameters, grads, learning_rate = update_parameters_with_gd_test_case()\n", 148 | "\n", 149 | "parameters = update_parameters_with_gd(parameters, grads, learning_rate)\n", 150 | "print(\"W1 =\\n\" + str(parameters[\"W1\"]))\n", 151 | "print(\"b1 =\\n\" + str(parameters[\"b1\"]))\n", 152 | "print(\"W2 =\\n\" + str(parameters[\"W2\"]))\n", 153 | "print(\"b2 =\\n\" + str(parameters[\"b2\"]))" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": 4, 159 | "metadata": {}, 160 | "outputs": [ 161 | { 162 | "data": { 163 | "text/plain": [ 164 | "{'W1': array([[ 1.63535156, -0.62320365, -0.53718766],\n", 165 | " [-1.07799357, 0.85639907, -2.29470142]]),\n", 166 | " 'W2': array([[ 0.32171798, -0.25467393, 1.46902454],\n", 167 | " [-2.05617317, -0.31554548, -0.3756023 ],\n", 168 | " [ 1.1404819 , -1.09976462, -0.1612551 ]]),\n", 169 | " 'b1': array([[ 1.74604067],\n", 170 | " [-0.75184921]]),\n", 171 | " 'b2': array([[-0.88020257],\n", 172 | " [ 0.02561572],\n", 173 | " [ 0.57539477]])}" 174 | ] 175 | }, 176 | "execution_count": 4, 177 | "metadata": {}, 178 | "output_type": "execute_result" 179 | } 180 | ], 181 | "source": [ 182 | "parameters" 183 | ] 184 | }, 185 | { 186 | "cell_type": "code", 187 | "execution_count": 5, 188 | "metadata": {}, 189 | "outputs": [ 190 | { 191 | "data": { 192 | "text/plain": [ 193 | "{'dW1': array([[-1.10061918, 1.14472371, 0.90159072],\n", 194 | " [ 0.50249434, 0.90085595, -0.68372786]]),\n", 195 | " 'dW2': array([[-0.26788808, 0.53035547, -0.69166075],\n", 196 | " [-0.39675353, -0.6871727 , -0.84520564],\n", 197 | " [-0.67124613, -0.0126646 , -1.11731035]]),\n", 198 | " 'db1': array([[-0.12289023],\n", 199 | " [-0.93576943]]),\n", 200 | " 'db2': array([[ 0.2344157 ],\n", 201 | " [ 1.65980218],\n", 202 | " [ 0.74204416]])}" 203 | ] 204 | }, 205 | "execution_count": 5, 206 | "metadata": {}, 207 | "output_type": "execute_result" 208 | } 209 | ], 210 | "source": [ 211 | "grads" 212 | ] 213 | }, 214 | { 215 | "cell_type": "markdown", 216 | "metadata": {}, 217 | "source": [ 218 | "**Expected Output**:\n", 219 | "\n", 220 | "```\n", 221 | "W1 =\n", 222 | "[[ 1.63535156 -0.62320365 -0.53718766]\n", 223 | " [-1.07799357 0.85639907 -2.29470142]]\n", 224 | "b1 =\n", 225 | "[[ 1.74604067]\n", 226 | " [-0.75184921]]\n", 227 | "W2 =\n", 228 | "[[ 0.32171798 -0.25467393 1.46902454]\n", 229 | " [-2.05617317 -0.31554548 -0.3756023 ]\n", 230 | " [ 1.1404819 -1.09976462 -0.1612551 ]]\n", 231 | "b2 =\n", 232 | "[[-0.88020257]\n", 233 | " [ 0.02561572]\n", 234 | " [ 0.57539477]]\n", 235 | "```" 236 | ] 237 | }, 238 | { 239 | "cell_type": "markdown", 240 | "metadata": {}, 241 | "source": [ 242 | "A variant of this is Stochastic Gradient Descent (SGD), which is equivalent to mini-batch gradient descent where each mini-batch has just 1 example. The update rule that you have just implemented does not change. What changes is that you would be computing gradients on just one training example at a time, rather than on the whole training set. The code examples below illustrate the difference between stochastic gradient descent and (batch) gradient descent. \n", 243 | "\n", 244 | "- **(Batch) Gradient Descent**:\n", 245 | "\n", 246 | "``` python\n", 247 | "X = data_input\n", 248 | "Y = labels\n", 249 | "parameters = initialize_parameters(layers_dims)\n", 250 | "for i in range(0, num_iterations):\n", 251 | " # Forward propagation\n", 252 | " a, caches = forward_propagation(X, parameters)\n", 253 | " # Compute cost.\n", 254 | " cost += compute_cost(a, Y)\n", 255 | " # Backward propagation.\n", 256 | " grads = backward_propagation(a, caches, parameters)\n", 257 | " # Update parameters.\n", 258 | " parameters = update_parameters(parameters, grads)\n", 259 | " \n", 260 | "```\n", 261 | "\n", 262 | "- **Stochastic Gradient Descent**:\n", 263 | "\n", 264 | "```python\n", 265 | "X = data_input\n", 266 | "Y = labels\n", 267 | "parameters = initialize_parameters(layers_dims)\n", 268 | "for i in range(0, num_iterations):\n", 269 | " for j in range(0, m):\n", 270 | " # Forward propagation\n", 271 | " a, caches = forward_propagation(X[:,j], parameters)\n", 272 | " # Compute cost\n", 273 | " cost += compute_cost(a, Y[:,j])\n", 274 | " # Backward propagation\n", 275 | " grads = backward_propagation(a, caches, parameters)\n", 276 | " # Update parameters.\n", 277 | " parameters = update_parameters(parameters, grads)\n", 278 | "```\n" 279 | ] 280 | }, 281 | { 282 | "cell_type": "markdown", 283 | "metadata": {}, 284 | "source": [ 285 | "In Stochastic Gradient Descent, you use only 1 training example before updating the gradients. When the training set is large, SGD can be faster. But the parameters will \"oscillate\" toward the minimum rather than converge smoothly. Here is an illustration of this: \n", 286 | "\n", 287 | "\n", 288 | "
**Figure 1** : **SGD vs GD**
\"+\" denotes a minimum of the cost. SGD leads to many oscillations to reach convergence. But each step is a lot faster to compute for SGD than for GD, as it uses only one training example (vs. the whole batch for GD).
\n", 289 | "\n", 290 | "**Note** also that implementing SGD requires 3 for-loops in total:\n", 291 | "1. Over the number of iterations\n", 292 | "2. Over the $m$ training examples\n", 293 | "3. Over the layers (to update all parameters, from $(W^{[1]},b^{[1]})$ to $(W^{[L]},b^{[L]})$)\n", 294 | "\n", 295 | "In practice, you'll often get faster results if you do not use neither the whole training set, nor only one training example, to perform each update. Mini-batch gradient descent uses an intermediate number of examples for each step. With mini-batch gradient descent, you loop over the mini-batches instead of looping over individual training examples.\n", 296 | "\n", 297 | "\n", 298 | "
**Figure 2** : **SGD vs Mini-Batch GD**
\"+\" denotes a minimum of the cost. Using mini-batches in your optimization algorithm often leads to faster optimization.
\n", 299 | "\n", 300 | "\n", 301 | "**What you should remember**:\n", 302 | "- The difference between gradient descent, mini-batch gradient descent and stochastic gradient descent is the number of examples you use to perform one update step.\n", 303 | "- You have to tune a learning rate hyperparameter $\\alpha$.\n", 304 | "- With a well-turned mini-batch size, usually it outperforms either gradient descent or stochastic gradient descent (particularly when the training set is large)." 305 | ] 306 | }, 307 | { 308 | "cell_type": "markdown", 309 | "metadata": {}, 310 | "source": [ 311 | "## 2 - Mini-Batch Gradient descent\n", 312 | "\n", 313 | "Let's learn how to build mini-batches from the training set (X, Y).\n", 314 | "\n", 315 | "There are two steps:\n", 316 | "- **Shuffle**: Create a shuffled version of the training set (X, Y) as shown below. Each column of X and Y represents a training example. Note that the random shuffling is done synchronously between X and Y. Such that after the shuffling the $i^{th}$ column of X is the example corresponding to the $i^{th}$ label in Y. The shuffling step ensures that examples will be split randomly into different mini-batches. \n", 317 | "\n", 318 | "\n", 319 | "\n", 320 | "- **Partition**: Partition the shuffled (X, Y) into mini-batches of size `mini_batch_size` (here 64). Note that the number of training examples is not always divisible by `mini_batch_size`. The last mini batch might be smaller, but you don't need to worry about this. When the final mini-batch is smaller than the full `mini_batch_size`, it will look like this: \n", 321 | "\n", 322 | "\n", 323 | "\n", 324 | "**Exercise**: Implement `random_mini_batches`. We coded the shuffling part for you. To help you with the partitioning step, we give you the following code that selects the indexes for the $1^{st}$ and $2^{nd}$ mini-batches:\n", 325 | "```python\n", 326 | "first_mini_batch_X = shuffled_X[:, 0 : mini_batch_size]\n", 327 | "second_mini_batch_X = shuffled_X[:, mini_batch_size : 2 * mini_batch_size]\n", 328 | "...\n", 329 | "```\n", 330 | "\n", 331 | "Note that the last mini-batch might end up smaller than `mini_batch_size=64`. Let $\\lfloor s \\rfloor$ represents $s$ rounded down to the nearest integer (this is `math.floor(s)` in Python). If the total number of examples is not a multiple of `mini_batch_size=64` then there will be $\\lfloor \\frac{m}{mini\\_batch\\_size}\\rfloor$ mini-batches with a full 64 examples, and the number of examples in the final mini-batch will be ($m-mini_\\_batch_\\_size \\times \\lfloor \\frac{m}{mini\\_batch\\_size}\\rfloor$). " 332 | ] 333 | }, 334 | { 335 | "cell_type": "code", 336 | "execution_count": 19, 337 | "metadata": { 338 | "collapsed": true 339 | }, 340 | "outputs": [], 341 | "source": [ 342 | "# GRADED FUNCTION: random_mini_batches\n", 343 | "\n", 344 | "def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):\n", 345 | " \"\"\"\n", 346 | " Creates a list of random minibatches from (X, Y)\n", 347 | " \n", 348 | " Arguments:\n", 349 | " X -- input data, of shape (input size, number of examples)\n", 350 | " Y -- true \"label\" vector (1 for blue dot / 0 for red dot), of shape (1, number of examples)\n", 351 | " mini_batch_size -- size of the mini-batches, integer\n", 352 | " \n", 353 | " Returns:\n", 354 | " mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)\n", 355 | " \"\"\"\n", 356 | " \n", 357 | " np.random.seed(seed) # To make your \"random\" minibatches the same as ours\n", 358 | " m = X.shape[1] # number of training examples\n", 359 | " mini_batches = []\n", 360 | " \n", 361 | " # Step 1: Shuffle (X, Y)\n", 362 | " permutation = list(np.random.permutation(m))\n", 363 | " shuffled_X = X[:, permutation]\n", 364 | " shuffled_Y = Y[:, permutation].reshape((1,m))\n", 365 | "\n", 366 | " # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.\n", 367 | " num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning\n", 368 | " for k in range(0, num_complete_minibatches):\n", 369 | " ### START CODE HERE ### (approx. 2 lines)\n", 370 | " mini_batch_X = shuffled_X[:,k * mini_batch_size:(k + 1) * mini_batch_size]\n", 371 | " mini_batch_Y = shuffled_Y[:,k * mini_batch_size:(k + 1) * mini_batch_size]\n", 372 | " ### END CODE HERE ###\n", 373 | " mini_batch = (mini_batch_X, mini_batch_Y)\n", 374 | " mini_batches.append(mini_batch)\n", 375 | " \n", 376 | " # Handling the end case (last mini-batch < mini_batch_size)\n", 377 | " if m % mini_batch_size != 0:\n", 378 | " ### START CODE HERE ### (approx. 2 lines)\n", 379 | " end = m - mini_batch_size * math.floor(m / mini_batch_size)\n", 380 | " mini_batch_X = shuffled_X[:,num_complete_minibatches * mini_batch_size:]\n", 381 | " mini_batch_Y = shuffled_Y[:,num_complete_minibatches * mini_batch_size:]\n", 382 | " ### END CODE HERE ###\n", 383 | " mini_batch = (mini_batch_X, mini_batch_Y)\n", 384 | " mini_batches.append(mini_batch)\n", 385 | " \n", 386 | " return mini_batches" 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": 20, 392 | "metadata": {}, 393 | "outputs": [ 394 | { 395 | "name": "stdout", 396 | "output_type": "stream", 397 | "text": [ 398 | "shape of the 1st mini_batch_X: (12288, 64)\n", 399 | "shape of the 2nd mini_batch_X: (12288, 64)\n", 400 | "shape of the 3rd mini_batch_X: (12288, 20)\n", 401 | "shape of the 1st mini_batch_Y: (1, 64)\n", 402 | "shape of the 2nd mini_batch_Y: (1, 64)\n", 403 | "shape of the 3rd mini_batch_Y: (1, 20)\n", 404 | "mini batch sanity check: [ 0.90085595 -0.7612069 0.2344157 ]\n" 405 | ] 406 | } 407 | ], 408 | "source": [ 409 | "X_assess, Y_assess, mini_batch_size = random_mini_batches_test_case()\n", 410 | "mini_batches = random_mini_batches(X_assess, Y_assess, mini_batch_size)\n", 411 | "\n", 412 | "print (\"shape of the 1st mini_batch_X: \" + str(mini_batches[0][0].shape))\n", 413 | "print (\"shape of the 2nd mini_batch_X: \" + str(mini_batches[1][0].shape))\n", 414 | "print (\"shape of the 3rd mini_batch_X: \" + str(mini_batches[2][0].shape))\n", 415 | "print (\"shape of the 1st mini_batch_Y: \" + str(mini_batches[0][1].shape))\n", 416 | "print (\"shape of the 2nd mini_batch_Y: \" + str(mini_batches[1][1].shape)) \n", 417 | "print (\"shape of the 3rd mini_batch_Y: \" + str(mini_batches[2][1].shape))\n", 418 | "print (\"mini batch sanity check: \" + str(mini_batches[0][0][0][0:3]))" 419 | ] 420 | }, 421 | { 422 | "cell_type": "markdown", 423 | "metadata": {}, 424 | "source": [ 425 | "**Expected Output**:\n", 426 | "\n", 427 | " \n", 428 | " \n", 429 | " \n", 430 | " \n", 431 | " \n", 432 | " \n", 433 | " \n", 434 | " \n", 435 | " \n", 436 | " \n", 437 | " \n", 438 | " \n", 439 | " \n", 440 | " \n", 441 | " \n", 442 | " \n", 443 | " \n", 444 | " \n", 445 | " \n", 446 | " \n", 447 | " \n", 448 | " \n", 449 | " \n", 450 | " \n", 451 | " \n", 452 | " \n", 453 | " \n", 454 | " \n", 455 | " \n", 456 | " \n", 457 | " \n", 458 | " \n", 459 | "
**shape of the 1st mini_batch_X** (12288, 64)
**shape of the 2nd mini_batch_X** (12288, 64)
**shape of the 3rd mini_batch_X** (12288, 20)
**shape of the 1st mini_batch_Y** (1, 64)
**shape of the 2nd mini_batch_Y** (1, 64)
**shape of the 3rd mini_batch_Y** (1, 20)
**mini batch sanity check** [ 0.90085595 -0.7612069 0.2344157 ]
" 460 | ] 461 | }, 462 | { 463 | "cell_type": "markdown", 464 | "metadata": {}, 465 | "source": [ 466 | "\n", 467 | "**What you should remember**:\n", 468 | "- Shuffling and Partitioning are the two steps required to build mini-batches\n", 469 | "- Powers of two are often chosen to be the mini-batch size, e.g., 16, 32, 64, 128." 470 | ] 471 | }, 472 | { 473 | "cell_type": "markdown", 474 | "metadata": {}, 475 | "source": [ 476 | "## 3 - Momentum\n", 477 | "\n", 478 | "Because mini-batch gradient descent makes a parameter update after seeing just a subset of examples, the direction of the update has some variance, and so the path taken by mini-batch gradient descent will \"oscillate\" toward convergence. Using momentum can reduce these oscillations. \n", 479 | "\n", 480 | "Momentum takes into account the past gradients to smooth out the update. We will store the 'direction' of the previous gradients in the variable $v$. Formally, this will be the exponentially weighted average of the gradient on previous steps. You can also think of $v$ as the \"velocity\" of a ball rolling downhill, building up speed (and momentum) according to the direction of the gradient/slope of the hill. \n", 481 | "\n", 482 | "\n", 483 | "
**Figure 3**: The red arrows shows the direction taken by one step of mini-batch gradient descent with momentum. The blue points show the direction of the gradient (with respect to the current mini-batch) on each step. Rather than just following the gradient, we let the gradient influence $v$ and then take a step in the direction of $v$.
\n", 484 | "\n", 485 | "\n", 486 | "**Exercise**: Initialize the velocity. The velocity, $v$, is a python dictionary that needs to be initialized with arrays of zeros. Its keys are the same as those in the `grads` dictionary, that is:\n", 487 | "for $l =1,...,L$:\n", 488 | "```python\n", 489 | "v[\"dW\" + str(l+1)] = ... #(numpy array of zeros with the same shape as parameters[\"W\" + str(l+1)])\n", 490 | "v[\"db\" + str(l+1)] = ... #(numpy array of zeros with the same shape as parameters[\"b\" + str(l+1)])\n", 491 | "```\n", 492 | "**Note** that the iterator l starts at 0 in the for loop while the first parameters are v[\"dW1\"] and v[\"db1\"] (that's a \"one\" on the superscript). This is why we are shifting l to l+1 in the `for` loop." 493 | ] 494 | }, 495 | { 496 | "cell_type": "code", 497 | "execution_count": 27, 498 | "metadata": {}, 499 | "outputs": [ 500 | { 501 | "data": { 502 | "text/plain": [ 503 | "{'W1': array([[ 1.62434536, -0.61175641, -0.52817175],\n", 504 | " [-1.07296862, 0.86540763, -2.3015387 ]]),\n", 505 | " 'W2': array([[ 0.3190391 , -0.24937038, 1.46210794],\n", 506 | " [-2.06014071, -0.3224172 , -0.38405435],\n", 507 | " [ 1.13376944, -1.09989127, -0.17242821]]),\n", 508 | " 'b1': array([[ 1.74481176],\n", 509 | " [-0.7612069 ]]),\n", 510 | " 'b2': array([[-0.87785842],\n", 511 | " [ 0.04221375],\n", 512 | " [ 0.58281521]])}" 513 | ] 514 | }, 515 | "execution_count": 27, 516 | "metadata": {}, 517 | "output_type": "execute_result" 518 | } 519 | ], 520 | "source": [ 521 | "parameters" 522 | ] 523 | }, 524 | { 525 | "cell_type": "code", 526 | "execution_count": 35, 527 | "metadata": {}, 528 | "outputs": [ 529 | { 530 | "data": { 531 | "text/plain": [ 532 | "(2, 3)" 533 | ] 534 | }, 535 | "execution_count": 35, 536 | "metadata": {}, 537 | "output_type": "execute_result" 538 | } 539 | ], 540 | "source": [ 541 | "parameters[\"W1\"].shape" 542 | ] 543 | }, 544 | { 545 | "cell_type": "code", 546 | "execution_count": 38, 547 | "metadata": { 548 | "collapsed": true 549 | }, 550 | "outputs": [], 551 | "source": [ 552 | "# GRADED FUNCTION: initialize_velocity\n", 553 | "\n", 554 | "def initialize_velocity(parameters):\n", 555 | " \"\"\"\n", 556 | " Initializes the velocity as a python dictionary with:\n", 557 | " - keys: \"dW1\", \"db1\", ..., \"dWL\", \"dbL\" \n", 558 | " - values: numpy arrays of zeros of the same shape as the corresponding gradients/parameters.\n", 559 | " Arguments:\n", 560 | " parameters -- python dictionary containing your parameters.\n", 561 | " parameters['W' + str(l)] = Wl\n", 562 | " parameters['b' + str(l)] = bl\n", 563 | " \n", 564 | " Returns:\n", 565 | " v -- python dictionary containing the current velocity.\n", 566 | " v['dW' + str(l)] = velocity of dWl\n", 567 | " v['db' + str(l)] = velocity of dbl\n", 568 | " \"\"\"\n", 569 | " \n", 570 | " L = len(parameters) // 2 # number of layers in the neural networks\n", 571 | " v = {}\n", 572 | " \n", 573 | " # Initialize velocity\n", 574 | " for l in range(L):\n", 575 | " ### START CODE HERE ### (approx. 2 lines)\n", 576 | " v[\"dW\" + str(l+1)] = np.zeros([parameters[\"W\" + str(l+1)].shape[0],parameters[\"W\" + str(l+1)].shape[1]])\n", 577 | " v[\"db\" + str(l+1)] = np.zeros([parameters[\"b\" + str(l+1)].shape[0],parameters[\"b\" + str(l+1)].shape[1]])\n", 578 | " ### END CODE HERE ###\n", 579 | " \n", 580 | " return v" 581 | ] 582 | }, 583 | { 584 | "cell_type": "code", 585 | "execution_count": 39, 586 | "metadata": {}, 587 | "outputs": [ 588 | { 589 | "name": "stdout", 590 | "output_type": "stream", 591 | "text": [ 592 | "v[\"dW1\"] =\n", 593 | "[[ 0. 0. 0.]\n", 594 | " [ 0. 0. 0.]]\n", 595 | "v[\"db1\"] =\n", 596 | "[[ 0.]\n", 597 | " [ 0.]]\n", 598 | "v[\"dW2\"] =\n", 599 | "[[ 0. 0. 0.]\n", 600 | " [ 0. 0. 0.]\n", 601 | " [ 0. 0. 0.]]\n", 602 | "v[\"db2\"] =\n", 603 | "[[ 0.]\n", 604 | " [ 0.]\n", 605 | " [ 0.]]\n" 606 | ] 607 | } 608 | ], 609 | "source": [ 610 | "parameters = initialize_velocity_test_case()\n", 611 | "\n", 612 | "v = initialize_velocity(parameters)\n", 613 | "print(\"v[\\\"dW1\\\"] =\\n\" + str(v[\"dW1\"]))\n", 614 | "print(\"v[\\\"db1\\\"] =\\n\" + str(v[\"db1\"]))\n", 615 | "print(\"v[\\\"dW2\\\"] =\\n\" + str(v[\"dW2\"]))\n", 616 | "print(\"v[\\\"db2\\\"] =\\n\" + str(v[\"db2\"]))" 617 | ] 618 | }, 619 | { 620 | "cell_type": "markdown", 621 | "metadata": {}, 622 | "source": [ 623 | "**Expected Output**:\n", 624 | "\n", 625 | "```\n", 626 | "v[\"dW1\"] =\n", 627 | "[[ 0. 0. 0.]\n", 628 | " [ 0. 0. 0.]]\n", 629 | "v[\"db1\"] =\n", 630 | "[[ 0.]\n", 631 | " [ 0.]]\n", 632 | "v[\"dW2\"] =\n", 633 | "[[ 0. 0. 0.]\n", 634 | " [ 0. 0. 0.]\n", 635 | " [ 0. 0. 0.]]\n", 636 | "v[\"db2\"] =\n", 637 | "[[ 0.]\n", 638 | " [ 0.]\n", 639 | " [ 0.]]\n", 640 | "```" 641 | ] 642 | }, 643 | { 644 | "cell_type": "markdown", 645 | "metadata": {}, 646 | "source": [ 647 | "**Exercise**: Now, implement the parameters update with momentum. The momentum update rule is, for $l = 1, ..., L$: \n", 648 | "\n", 649 | "$$ \\begin{cases}\n", 650 | "v_{dW^{[l]}} = \\beta v_{dW^{[l]}} + (1 - \\beta) dW^{[l]} \\\\\n", 651 | "W^{[l]} = W^{[l]} - \\alpha v_{dW^{[l]}}\n", 652 | "\\end{cases}\\tag{3}$$\n", 653 | "\n", 654 | "$$\\begin{cases}\n", 655 | "v_{db^{[l]}} = \\beta v_{db^{[l]}} + (1 - \\beta) db^{[l]} \\\\\n", 656 | "b^{[l]} = b^{[l]} - \\alpha v_{db^{[l]}} \n", 657 | "\\end{cases}\\tag{4}$$\n", 658 | "\n", 659 | "where L is the number of layers, $\\beta$ is the momentum and $\\alpha$ is the learning rate. All parameters should be stored in the `parameters` dictionary. Note that the iterator `l` starts at 0 in the `for` loop while the first parameters are $W^{[1]}$ and $b^{[1]}$ (that's a \"one\" on the superscript). So you will need to shift `l` to `l+1` when coding." 660 | ] 661 | }, 662 | { 663 | "cell_type": "code", 664 | "execution_count": 40, 665 | "metadata": {}, 666 | "outputs": [ 667 | { 668 | "data": { 669 | "text/plain": [ 670 | "{'W1': array([[ 1.62434536, -0.61175641, -0.52817175],\n", 671 | " [-1.07296862, 0.86540763, -2.3015387 ]]),\n", 672 | " 'W2': array([[ 0.3190391 , -0.24937038, 1.46210794],\n", 673 | " [-2.06014071, -0.3224172 , -0.38405435],\n", 674 | " [ 1.13376944, -1.09989127, -0.17242821]]),\n", 675 | " 'b1': array([[ 1.74481176],\n", 676 | " [-0.7612069 ]]),\n", 677 | " 'b2': array([[-0.87785842],\n", 678 | " [ 0.04221375],\n", 679 | " [ 0.58281521]])}" 680 | ] 681 | }, 682 | "execution_count": 40, 683 | "metadata": {}, 684 | "output_type": "execute_result" 685 | } 686 | ], 687 | "source": [ 688 | "parameters" 689 | ] 690 | }, 691 | { 692 | "cell_type": "code", 693 | "execution_count": 41, 694 | "metadata": {}, 695 | "outputs": [ 696 | { 697 | "data": { 698 | "text/plain": [ 699 | "{'dW1': array([[-1.10061918, 1.14472371, 0.90159072],\n", 700 | " [ 0.50249434, 0.90085595, -0.68372786]]),\n", 701 | " 'dW2': array([[-0.26788808, 0.53035547, -0.69166075],\n", 702 | " [-0.39675353, -0.6871727 , -0.84520564],\n", 703 | " [-0.67124613, -0.0126646 , -1.11731035]]),\n", 704 | " 'db1': array([[-0.12289023],\n", 705 | " [-0.93576943]]),\n", 706 | " 'db2': array([[ 0.2344157 ],\n", 707 | " [ 1.65980218],\n", 708 | " [ 0.74204416]])}" 709 | ] 710 | }, 711 | "execution_count": 41, 712 | "metadata": {}, 713 | "output_type": "execute_result" 714 | } 715 | ], 716 | "source": [ 717 | "grads" 718 | ] 719 | }, 720 | { 721 | "cell_type": "code", 722 | "execution_count": 44, 723 | "metadata": { 724 | "collapsed": true 725 | }, 726 | "outputs": [], 727 | "source": [ 728 | "# GRADED FUNCTION: update_parameters_with_momentum\n", 729 | "\n", 730 | "def update_parameters_with_momentum(parameters, grads, v, beta, learning_rate):\n", 731 | " \"\"\"\n", 732 | " Update parameters using Momentum\n", 733 | " \n", 734 | " Arguments:\n", 735 | " parameters -- python dictionary containing your parameters:\n", 736 | " parameters['W' + str(l)] = Wl\n", 737 | " parameters['b' + str(l)] = bl\n", 738 | " grads -- python dictionary containing your gradients for each parameters:\n", 739 | " grads['dW' + str(l)] = dWl\n", 740 | " grads['db' + str(l)] = dbl\n", 741 | " v -- python dictionary containing the current velocity:\n", 742 | " v['dW' + str(l)] = ...\n", 743 | " v['db' + str(l)] = ...\n", 744 | " beta -- the momentum hyperparameter, scalar\n", 745 | " learning_rate -- the learning rate, scalar\n", 746 | " \n", 747 | " Returns:\n", 748 | " parameters -- python dictionary containing your updated parameters \n", 749 | " v -- python dictionary containing your updated velocities\n", 750 | " \"\"\"\n", 751 | "\n", 752 | " L = len(parameters) // 2 # number of layers in the neural networks\n", 753 | " \n", 754 | " # Momentum update for each parameter\n", 755 | " for l in range(L):\n", 756 | " \n", 757 | " ### START CODE HERE ### (approx. 4 lines)\n", 758 | " # compute velocities\n", 759 | " v[\"dW\" + str(l+1)] = beta * v[\"dW\"+str(l+1)] +(1-beta) * grads[\"dW\"+str(l+1)]\n", 760 | " v[\"db\" + str(l+1)] = beta * v[\"db\"+str(l+1)] +(1-beta) * grads[\"db\"+str(l+1)]\n", 761 | " # update parameters\n", 762 | " parameters[\"W\" + str(l+1)] = parameters[\"W\" + str(l+1)] - learning_rate*(v[\"dW\" + str(l+1)])\n", 763 | " parameters[\"b\" + str(l+1)] = parameters[\"b\" + str(l+1)] - learning_rate*(v[\"db\" + str(l+1)])\n", 764 | " ### END CODE HERE ###\n", 765 | " \n", 766 | " return parameters, v" 767 | ] 768 | }, 769 | { 770 | "cell_type": "code", 771 | "execution_count": 45, 772 | "metadata": {}, 773 | "outputs": [ 774 | { 775 | "name": "stdout", 776 | "output_type": "stream", 777 | "text": [ 778 | "W1 = \n", 779 | "[[ 1.62544598 -0.61290114 -0.52907334]\n", 780 | " [-1.07347112 0.86450677 -2.30085497]]\n", 781 | "b1 = \n", 782 | "[[ 1.74493465]\n", 783 | " [-0.76027113]]\n", 784 | "W2 = \n", 785 | "[[ 0.31930698 -0.24990073 1.4627996 ]\n", 786 | " [-2.05974396 -0.32173003 -0.38320915]\n", 787 | " [ 1.13444069 -1.0998786 -0.1713109 ]]\n", 788 | "b2 = \n", 789 | "[[-0.87809283]\n", 790 | " [ 0.04055394]\n", 791 | " [ 0.58207317]]\n", 792 | "v[\"dW1\"] = \n", 793 | "[[-0.11006192 0.11447237 0.09015907]\n", 794 | " [ 0.05024943 0.09008559 -0.06837279]]\n", 795 | "v[\"db1\"] = \n", 796 | "[[-0.01228902]\n", 797 | " [-0.09357694]]\n", 798 | "v[\"dW2\"] = \n", 799 | "[[-0.02678881 0.05303555 -0.06916608]\n", 800 | " [-0.03967535 -0.06871727 -0.08452056]\n", 801 | " [-0.06712461 -0.00126646 -0.11173103]]\n", 802 | "v[\"db2\"] = v[[ 0.02344157]\n", 803 | " [ 0.16598022]\n", 804 | " [ 0.07420442]]\n" 805 | ] 806 | } 807 | ], 808 | "source": [ 809 | "parameters, grads, v = update_parameters_with_momentum_test_case()\n", 810 | "\n", 811 | "parameters, v = update_parameters_with_momentum(parameters, grads, v, beta = 0.9, learning_rate = 0.01)\n", 812 | "print(\"W1 = \\n\" + str(parameters[\"W1\"]))\n", 813 | "print(\"b1 = \\n\" + str(parameters[\"b1\"]))\n", 814 | "print(\"W2 = \\n\" + str(parameters[\"W2\"]))\n", 815 | "print(\"b2 = \\n\" + str(parameters[\"b2\"]))\n", 816 | "print(\"v[\\\"dW1\\\"] = \\n\" + str(v[\"dW1\"]))\n", 817 | "print(\"v[\\\"db1\\\"] = \\n\" + str(v[\"db1\"]))\n", 818 | "print(\"v[\\\"dW2\\\"] = \\n\" + str(v[\"dW2\"]))\n", 819 | "print(\"v[\\\"db2\\\"] = v\" + str(v[\"db2\"]))" 820 | ] 821 | }, 822 | { 823 | "cell_type": "markdown", 824 | "metadata": {}, 825 | "source": [ 826 | "**Expected Output**:\n", 827 | "\n", 828 | "```\n", 829 | "W1 = \n", 830 | "[[ 1.62544598 -0.61290114 -0.52907334]\n", 831 | " [-1.07347112 0.86450677 -2.30085497]]\n", 832 | "b1 = \n", 833 | "[[ 1.74493465]\n", 834 | " [-0.76027113]]\n", 835 | "W2 = \n", 836 | "[[ 0.31930698 -0.24990073 1.4627996 ]\n", 837 | " [-2.05974396 -0.32173003 -0.38320915]\n", 838 | " [ 1.13444069 -1.0998786 -0.1713109 ]]\n", 839 | "b2 = \n", 840 | "[[-0.87809283]\n", 841 | " [ 0.04055394]\n", 842 | " [ 0.58207317]]\n", 843 | "v[\"dW1\"] = \n", 844 | "[[-0.11006192 0.11447237 0.09015907]\n", 845 | " [ 0.05024943 0.09008559 -0.06837279]]\n", 846 | "v[\"db1\"] = \n", 847 | "[[-0.01228902]\n", 848 | " [-0.09357694]]\n", 849 | "v[\"dW2\"] = \n", 850 | "[[-0.02678881 0.05303555 -0.06916608]\n", 851 | " [-0.03967535 -0.06871727 -0.08452056]\n", 852 | " [-0.06712461 -0.00126646 -0.11173103]]\n", 853 | "v[\"db2\"] = v[[ 0.02344157]\n", 854 | " [ 0.16598022]\n", 855 | " [ 0.07420442]]\n", 856 | "```" 857 | ] 858 | }, 859 | { 860 | "cell_type": "markdown", 861 | "metadata": {}, 862 | "source": [ 863 | "**Note** that:\n", 864 | "- The velocity is initialized with zeros. So the algorithm will take a few iterations to \"build up\" velocity and start to take bigger steps.\n", 865 | "- If $\\beta = 0$, then this just becomes standard gradient descent without momentum. \n", 866 | "\n", 867 | "**How do you choose $\\beta$?**\n", 868 | "\n", 869 | "- The larger the momentum $\\beta$ is, the smoother the update because the more we take the past gradients into account. But if $\\beta$ is too big, it could also smooth out the updates too much. \n", 870 | "- Common values for $\\beta$ range from 0.8 to 0.999. If you don't feel inclined to tune this, $\\beta = 0.9$ is often a reasonable default. \n", 871 | "- Tuning the optimal $\\beta$ for your model might need trying several values to see what works best in term of reducing the value of the cost function $J$. " 872 | ] 873 | }, 874 | { 875 | "cell_type": "markdown", 876 | "metadata": {}, 877 | "source": [ 878 | "\n", 879 | "**What you should remember**:\n", 880 | "- Momentum takes past gradients into account to smooth out the steps of gradient descent. It can be applied with batch gradient descent, mini-batch gradient descent or stochastic gradient descent.\n", 881 | "- You have to tune a momentum hyperparameter $\\beta$ and a learning rate $\\alpha$." 882 | ] 883 | }, 884 | { 885 | "cell_type": "markdown", 886 | "metadata": {}, 887 | "source": [ 888 | "## 4 - Adam\n", 889 | "\n", 890 | "Adam is one of the most effective optimization algorithms for training neural networks. It combines ideas from RMSProp (described in lecture) and Momentum. \n", 891 | "\n", 892 | "**How does Adam work?**\n", 893 | "1. It calculates an exponentially weighted average of past gradients, and stores it in variables $v$ (before bias correction) and $v^{corrected}$ (with bias correction). \n", 894 | "2. It calculates an exponentially weighted average of the squares of the past gradients, and stores it in variables $s$ (before bias correction) and $s^{corrected}$ (with bias correction). \n", 895 | "3. It updates parameters in a direction based on combining information from \"1\" and \"2\".\n", 896 | "\n", 897 | "The update rule is, for $l = 1, ..., L$: \n", 898 | "\n", 899 | "$$\\begin{cases}\n", 900 | "v_{dW^{[l]}} = \\beta_1 v_{dW^{[l]}} + (1 - \\beta_1) \\frac{\\partial \\mathcal{J} }{ \\partial W^{[l]} } \\\\\n", 901 | "v^{corrected}_{dW^{[l]}} = \\frac{v_{dW^{[l]}}}{1 - (\\beta_1)^t} \\\\\n", 902 | "s_{dW^{[l]}} = \\beta_2 s_{dW^{[l]}} + (1 - \\beta_2) (\\frac{\\partial \\mathcal{J} }{\\partial W^{[l]} })^2 \\\\\n", 903 | "s^{corrected}_{dW^{[l]}} = \\frac{s_{dW^{[l]}}}{1 - (\\beta_2)^t} \\\\\n", 904 | "W^{[l]} = W^{[l]} - \\alpha \\frac{v^{corrected}_{dW^{[l]}}}{\\sqrt{s^{corrected}_{dW^{[l]}}} + \\varepsilon}\n", 905 | "\\end{cases}$$\n", 906 | "where:\n", 907 | "- t counts the number of steps taken of Adam \n", 908 | "- L is the number of layers\n", 909 | "- $\\beta_1$ and $\\beta_2$ are hyperparameters that control the two exponentially weighted averages. \n", 910 | "- $\\alpha$ is the learning rate\n", 911 | "- $\\varepsilon$ is a very small number to avoid dividing by zero\n", 912 | "\n", 913 | "As usual, we will store all parameters in the `parameters` dictionary " 914 | ] 915 | }, 916 | { 917 | "cell_type": "markdown", 918 | "metadata": {}, 919 | "source": [ 920 | "**Exercise**: Initialize the Adam variables $v, s$ which keep track of the past information.\n", 921 | "\n", 922 | "**Instruction**: The variables $v, s$ are python dictionaries that need to be initialized with arrays of zeros. Their keys are the same as for `grads`, that is:\n", 923 | "for $l = 1, ..., L$:\n", 924 | "```python\n", 925 | "v[\"dW\" + str(l+1)] = ... #(numpy array of zeros with the same shape as parameters[\"W\" + str(l+1)])\n", 926 | "v[\"db\" + str(l+1)] = ... #(numpy array of zeros with the same shape as parameters[\"b\" + str(l+1)])\n", 927 | "s[\"dW\" + str(l+1)] = ... #(numpy array of zeros with the same shape as parameters[\"W\" + str(l+1)])\n", 928 | "s[\"db\" + str(l+1)] = ... #(numpy array of zeros with the same shape as parameters[\"b\" + str(l+1)])\n", 929 | "\n", 930 | "```" 931 | ] 932 | }, 933 | { 934 | "cell_type": "code", 935 | "execution_count": 46, 936 | "metadata": {}, 937 | "outputs": [ 938 | { 939 | "data": { 940 | "text/plain": [ 941 | "{'W1': array([[ 1.62544598, -0.61290114, -0.52907334],\n", 942 | " [-1.07347112, 0.86450677, -2.30085497]]),\n", 943 | " 'W2': array([[ 0.31930698, -0.24990073, 1.4627996 ],\n", 944 | " [-2.05974396, -0.32173003, -0.38320915],\n", 945 | " [ 1.13444069, -1.0998786 , -0.1713109 ]]),\n", 946 | " 'b1': array([[ 1.74493465],\n", 947 | " [-0.76027113]]),\n", 948 | " 'b2': array([[-0.87809283],\n", 949 | " [ 0.04055394],\n", 950 | " [ 0.58207317]])}" 951 | ] 952 | }, 953 | "execution_count": 46, 954 | "metadata": {}, 955 | "output_type": "execute_result" 956 | } 957 | ], 958 | "source": [ 959 | "parameters" 960 | ] 961 | }, 962 | { 963 | "cell_type": "code", 964 | "execution_count": 51, 965 | "metadata": { 966 | "collapsed": true 967 | }, 968 | "outputs": [], 969 | "source": [ 970 | "# GRADED FUNCTION: initialize_adam\n", 971 | "\n", 972 | "def initialize_adam(parameters) :\n", 973 | " \"\"\"\n", 974 | " Initializes v and s as two python dictionaries with:\n", 975 | " - keys: \"dW1\", \"db1\", ..., \"dWL\", \"dbL\" \n", 976 | " - values: numpy arrays of zeros of the same shape as the corresponding gradients/parameters.\n", 977 | " \n", 978 | " Arguments:\n", 979 | " parameters -- python dictionary containing your parameters.\n", 980 | " parameters[\"W\" + str(l)] = Wl\n", 981 | " parameters[\"b\" + str(l)] = bl\n", 982 | " \n", 983 | " Returns: \n", 984 | " v -- python dictionary that will contain the exponentially weighted average of the gradient.\n", 985 | " v[\"dW\" + str(l)] = ...\n", 986 | " v[\"db\" + str(l)] = ...\n", 987 | " s -- python dictionary that will contain the exponentially weighted average of the squared gradient.\n", 988 | " s[\"dW\" + str(l)] = ...\n", 989 | " s[\"db\" + str(l)] = ...\n", 990 | "\n", 991 | " \"\"\"\n", 992 | " \n", 993 | " L = len(parameters) // 2 # number of layers in the neural networks\n", 994 | " v = {}\n", 995 | " s = {}\n", 996 | " \n", 997 | " # Initialize v, s. Input: \"parameters\". Outputs: \"v, s\".\n", 998 | " for l in range(L):\n", 999 | " ### START CODE HERE ### (approx. 4 lines)\n", 1000 | " v[\"dW\" + str(l+1)] = np.zeros([parameters[\"W\"+str(l+1)].shape[0],parameters[\"W\"+str(l+1)].shape[1]])\n", 1001 | " v[\"db\" + str(l+1)] = np.zeros([parameters[\"b\"+str(l+1)].shape[0],parameters[\"b\"+str(l+1)].shape[1]])\n", 1002 | " s[\"dW\" + str(l+1)] = np.zeros([parameters[\"W\"+str(l+1)].shape[0],parameters[\"W\"+str(l+1)].shape[1]])\n", 1003 | " s[\"db\" + str(l+1)] = np.zeros([parameters[\"b\"+str(l+1)].shape[0],parameters[\"b\"+str(l+1)].shape[1]])\n", 1004 | " ### END CODE HERE ###\n", 1005 | " \n", 1006 | " return v, s" 1007 | ] 1008 | }, 1009 | { 1010 | "cell_type": "code", 1011 | "execution_count": 52, 1012 | "metadata": {}, 1013 | "outputs": [ 1014 | { 1015 | "name": "stdout", 1016 | "output_type": "stream", 1017 | "text": [ 1018 | "v[\"dW1\"] = \n", 1019 | "[[ 0. 0. 0.]\n", 1020 | " [ 0. 0. 0.]]\n", 1021 | "v[\"db1\"] = \n", 1022 | "[[ 0.]\n", 1023 | " [ 0.]]\n", 1024 | "v[\"dW2\"] = \n", 1025 | "[[ 0. 0. 0.]\n", 1026 | " [ 0. 0. 0.]\n", 1027 | " [ 0. 0. 0.]]\n", 1028 | "v[\"db2\"] = \n", 1029 | "[[ 0.]\n", 1030 | " [ 0.]\n", 1031 | " [ 0.]]\n", 1032 | "s[\"dW1\"] = \n", 1033 | "[[ 0. 0. 0.]\n", 1034 | " [ 0. 0. 0.]]\n", 1035 | "s[\"db1\"] = \n", 1036 | "[[ 0.]\n", 1037 | " [ 0.]]\n", 1038 | "s[\"dW2\"] = \n", 1039 | "[[ 0. 0. 0.]\n", 1040 | " [ 0. 0. 0.]\n", 1041 | " [ 0. 0. 0.]]\n", 1042 | "s[\"db2\"] = \n", 1043 | "[[ 0.]\n", 1044 | " [ 0.]\n", 1045 | " [ 0.]]\n" 1046 | ] 1047 | } 1048 | ], 1049 | "source": [ 1050 | "parameters = initialize_adam_test_case()\n", 1051 | "\n", 1052 | "v, s = initialize_adam(parameters)\n", 1053 | "print(\"v[\\\"dW1\\\"] = \\n\" + str(v[\"dW1\"]))\n", 1054 | "print(\"v[\\\"db1\\\"] = \\n\" + str(v[\"db1\"]))\n", 1055 | "print(\"v[\\\"dW2\\\"] = \\n\" + str(v[\"dW2\"]))\n", 1056 | "print(\"v[\\\"db2\\\"] = \\n\" + str(v[\"db2\"]))\n", 1057 | "print(\"s[\\\"dW1\\\"] = \\n\" + str(s[\"dW1\"]))\n", 1058 | "print(\"s[\\\"db1\\\"] = \\n\" + str(s[\"db1\"]))\n", 1059 | "print(\"s[\\\"dW2\\\"] = \\n\" + str(s[\"dW2\"]))\n", 1060 | "print(\"s[\\\"db2\\\"] = \\n\" + str(s[\"db2\"]))" 1061 | ] 1062 | }, 1063 | { 1064 | "cell_type": "markdown", 1065 | "metadata": {}, 1066 | "source": [ 1067 | "**Expected Output**:\n", 1068 | "\n", 1069 | "```\n", 1070 | "v[\"dW1\"] = \n", 1071 | "[[ 0. 0. 0.]\n", 1072 | " [ 0. 0. 0.]]\n", 1073 | "v[\"db1\"] = \n", 1074 | "[[ 0.]\n", 1075 | " [ 0.]]\n", 1076 | "v[\"dW2\"] = \n", 1077 | "[[ 0. 0. 0.]\n", 1078 | " [ 0. 0. 0.]\n", 1079 | " [ 0. 0. 0.]]\n", 1080 | "v[\"db2\"] = \n", 1081 | "[[ 0.]\n", 1082 | " [ 0.]\n", 1083 | " [ 0.]]\n", 1084 | "s[\"dW1\"] = \n", 1085 | "[[ 0. 0. 0.]\n", 1086 | " [ 0. 0. 0.]]\n", 1087 | "s[\"db1\"] = \n", 1088 | "[[ 0.]\n", 1089 | " [ 0.]]\n", 1090 | "s[\"dW2\"] = \n", 1091 | "[[ 0. 0. 0.]\n", 1092 | " [ 0. 0. 0.]\n", 1093 | " [ 0. 0. 0.]]\n", 1094 | "s[\"db2\"] = \n", 1095 | "[[ 0.]\n", 1096 | " [ 0.]\n", 1097 | " [ 0.]]\n", 1098 | "```" 1099 | ] 1100 | }, 1101 | { 1102 | "cell_type": "markdown", 1103 | "metadata": {}, 1104 | "source": [ 1105 | "**Exercise**: Now, implement the parameters update with Adam. Recall the general update rule is, for $l = 1, ..., L$: \n", 1106 | "\n", 1107 | "$$\\begin{cases}\n", 1108 | "v_{W^{[l]}} = \\beta_1 v_{W^{[l]}} + (1 - \\beta_1) \\frac{\\partial J }{ \\partial W^{[l]} } \\\\\n", 1109 | "v^{corrected}_{W^{[l]}} = \\frac{v_{W^{[l]}}}{1 - (\\beta_1)^t} \\\\\n", 1110 | "s_{W^{[l]}} = \\beta_2 s_{W^{[l]}} + (1 - \\beta_2) (\\frac{\\partial J }{\\partial W^{[l]} })^2 \\\\\n", 1111 | "s^{corrected}_{W^{[l]}} = \\frac{s_{W^{[l]}}}{1 - (\\beta_2)^t} \\\\\n", 1112 | "W^{[l]} = W^{[l]} - \\alpha \\frac{v^{corrected}_{W^{[l]}}}{\\sqrt{s^{corrected}_{W^{[l]}}}+\\varepsilon}\n", 1113 | "\\end{cases}$$\n", 1114 | "\n", 1115 | "\n", 1116 | "**Note** that the iterator `l` starts at 0 in the `for` loop while the first parameters are $W^{[1]}$ and $b^{[1]}$. You need to shift `l` to `l+1` when coding." 1117 | ] 1118 | }, 1119 | { 1120 | "cell_type": "code", 1121 | "execution_count": 57, 1122 | "metadata": { 1123 | "collapsed": true 1124 | }, 1125 | "outputs": [], 1126 | "source": [ 1127 | "# GRADED FUNCTION: update_parameters_with_adam\n", 1128 | "\n", 1129 | "def update_parameters_with_adam(parameters, grads, v, s, t, learning_rate=0.01,\n", 1130 | " beta1=0.9, beta2=0.999, epsilon=1e-8):\n", 1131 | " \"\"\"\n", 1132 | " Update parameters using Adam\n", 1133 | " \n", 1134 | " Arguments:\n", 1135 | " parameters -- python dictionary containing your parameters:\n", 1136 | " parameters['W' + str(l)] = Wl\n", 1137 | " parameters['b' + str(l)] = bl\n", 1138 | " grads -- python dictionary containing your gradients for each parameters:\n", 1139 | " grads['dW' + str(l)] = dWl\n", 1140 | " grads['db' + str(l)] = dbl\n", 1141 | " v -- Adam variable, moving average of the first gradient, python dictionary\n", 1142 | " s -- Adam variable, moving average of the squared gradient, python dictionary\n", 1143 | " learning_rate -- the learning rate, scalar.\n", 1144 | " beta1 -- Exponential decay hyperparameter for the first moment estimates \n", 1145 | " beta2 -- Exponential decay hyperparameter for the second moment estimates \n", 1146 | " epsilon -- hyperparameter preventing division by zero in Adam updates\n", 1147 | "\n", 1148 | " Returns:\n", 1149 | " parameters -- python dictionary containing your updated parameters \n", 1150 | " v -- Adam variable, moving average of the first gradient, python dictionary\n", 1151 | " s -- Adam variable, moving average of the squared gradient, python dictionary\n", 1152 | " \"\"\"\n", 1153 | " \n", 1154 | " L = len(parameters) // 2 # number of layers in the neural networks\n", 1155 | " v_corrected = {} # Initializing first moment estimate, python dictionary\n", 1156 | " s_corrected = {} # Initializing second moment estimate, python dictionary\n", 1157 | " \n", 1158 | " # Perform Adam update on all parameters\n", 1159 | " for l in range(L):\n", 1160 | " # Moving average of the gradients. Inputs: \"v, grads, beta1\". Output: \"v\".\n", 1161 | " ### START CODE HERE ### (approx. 2 lines)\n", 1162 | " v[\"dW\" + str(l + 1)] = beta1 * v[\"dW\" + str(l + 1)] + (1 - beta1) * grads['dW' + str(l + 1)]\n", 1163 | " v[\"db\" + str(l + 1)] = beta1 * v[\"db\" + str(l + 1)] + (1 - beta1) * grads['db' + str(l + 1)]\n", 1164 | " ### END CODE HERE ###\n", 1165 | "\n", 1166 | " # Compute bias-corrected first moment estimate. Inputs: \"v, beta1, t\". Output: \"v_corrected\".\n", 1167 | " ### START CODE HERE ### (approx. 2 lines)\n", 1168 | " v_corrected[\"dW\" + str(l + 1)] = v[\"dW\" + str(l + 1)] / (1 - np.power(beta1, t))\n", 1169 | " v_corrected[\"db\" + str(l + 1)] = v[\"db\" + str(l + 1)] / (1 - np.power(beta1, t))\n", 1170 | " ### END CODE HERE ###\n", 1171 | "\n", 1172 | " # Moving average of the squared gradients. Inputs: \"s, grads, beta2\". Output: \"s\".\n", 1173 | " ### START CODE HERE ### (approx. 2 lines)\n", 1174 | " s[\"dW\" + str(l + 1)] = beta2 * s[\"dW\" + str(l + 1)] + (1 - beta2) * np.power(grads['dW' + str(l + 1)], 2)\n", 1175 | " s[\"db\" + str(l + 1)] = beta2 * s[\"db\" + str(l + 1)] + (1 - beta2) * np.power(grads['db' + str(l + 1)], 2)\n", 1176 | " ### END CODE HERE ###\n", 1177 | "\n", 1178 | " # Compute bias-corrected second raw moment estimate. Inputs: \"s, beta2, t\". Output: \"s_corrected\".\n", 1179 | " ### START CODE HERE ### (approx. 2 lines)\n", 1180 | " s_corrected[\"dW\" + str(l + 1)] = s[\"dW\" + str(l + 1)] / (1 - np.power(beta2, t))\n", 1181 | " s_corrected[\"db\" + str(l + 1)] = s[\"db\" + str(l + 1)] / (1 - np.power(beta2, t))\n", 1182 | " ### END CODE HERE ###\n", 1183 | "\n", 1184 | " # Update parameters. Inputs: \"parameters, learning_rate, v_corrected, s_corrected, epsilon\". Output: \"parameters\".\n", 1185 | " ### START CODE HERE ### (approx. 2 lines)\n", 1186 | " parameters[\"W\" + str(l + 1)] = parameters[\"W\" + str(l + 1)] - learning_rate * v_corrected[\"dW\" + str(l + 1)] / np.sqrt(s_corrected[\"dW\" + str(l + 1)] + epsilon)\n", 1187 | " parameters[\"b\" + str(l + 1)] = parameters[\"b\" + str(l + 1)] - learning_rate * v_corrected[\"db\" + str(l + 1)] / np.sqrt(s_corrected[\"db\" + str(l + 1)] + epsilon)\n", 1188 | " ### END CODE HERE ###\n", 1189 | "\n", 1190 | " return parameters, v, s" 1191 | ] 1192 | }, 1193 | { 1194 | "cell_type": "code", 1195 | "execution_count": 58, 1196 | "metadata": { 1197 | "scrolled": false 1198 | }, 1199 | "outputs": [ 1200 | { 1201 | "name": "stdout", 1202 | "output_type": "stream", 1203 | "text": [ 1204 | "W1 = \n", 1205 | "[[ 1.63178673 -0.61919778 -0.53561312]\n", 1206 | " [-1.08040999 0.85796626 -2.29409733]]\n", 1207 | "b1 = \n", 1208 | "[[ 1.75225313]\n", 1209 | " [-0.75376553]]\n", 1210 | "W2 = \n", 1211 | "[[ 0.32648046 -0.25681174 1.46954931]\n", 1212 | " [-2.05269934 -0.31497584 -0.37661299]\n", 1213 | " [ 1.14121081 -1.09245036 -0.16498684]]\n", 1214 | "b2 = \n", 1215 | "[[-0.88529978]\n", 1216 | " [ 0.03477238]\n", 1217 | " [ 0.57537385]]\n", 1218 | "v[\"dW1\"] = \n", 1219 | "[[-0.11006192 0.11447237 0.09015907]\n", 1220 | " [ 0.05024943 0.09008559 -0.06837279]]\n", 1221 | "v[\"db1\"] = \n", 1222 | "[[-0.01228902]\n", 1223 | " [-0.09357694]]\n", 1224 | "v[\"dW2\"] = \n", 1225 | "[[-0.02678881 0.05303555 -0.06916608]\n", 1226 | " [-0.03967535 -0.06871727 -0.08452056]\n", 1227 | " [-0.06712461 -0.00126646 -0.11173103]]\n", 1228 | "v[\"db2\"] = \n", 1229 | "[[ 0.02344157]\n", 1230 | " [ 0.16598022]\n", 1231 | " [ 0.07420442]]\n", 1232 | "s[\"dW1\"] = \n", 1233 | "[[ 0.00121136 0.00131039 0.00081287]\n", 1234 | " [ 0.0002525 0.00081154 0.00046748]]\n", 1235 | "s[\"db1\"] = \n", 1236 | "[[ 1.51020075e-05]\n", 1237 | " [ 8.75664434e-04]]\n", 1238 | "s[\"dW2\"] = \n", 1239 | "[[ 7.17640232e-05 2.81276921e-04 4.78394595e-04]\n", 1240 | " [ 1.57413361e-04 4.72206320e-04 7.14372576e-04]\n", 1241 | " [ 4.50571368e-04 1.60392066e-07 1.24838242e-03]]\n", 1242 | "s[\"db2\"] = \n", 1243 | "[[ 5.49507194e-05]\n", 1244 | " [ 2.75494327e-03]\n", 1245 | " [ 5.50629536e-04]]\n" 1246 | ] 1247 | } 1248 | ], 1249 | "source": [ 1250 | "parameters, grads, v, s = update_parameters_with_adam_test_case()\n", 1251 | "parameters, v, s = update_parameters_with_adam(parameters, grads, v, s, t = 2)\n", 1252 | "\n", 1253 | "print(\"W1 = \\n\" + str(parameters[\"W1\"]))\n", 1254 | "print(\"b1 = \\n\" + str(parameters[\"b1\"]))\n", 1255 | "print(\"W2 = \\n\" + str(parameters[\"W2\"]))\n", 1256 | "print(\"b2 = \\n\" + str(parameters[\"b2\"]))\n", 1257 | "print(\"v[\\\"dW1\\\"] = \\n\" + str(v[\"dW1\"]))\n", 1258 | "print(\"v[\\\"db1\\\"] = \\n\" + str(v[\"db1\"]))\n", 1259 | "print(\"v[\\\"dW2\\\"] = \\n\" + str(v[\"dW2\"]))\n", 1260 | "print(\"v[\\\"db2\\\"] = \\n\" + str(v[\"db2\"]))\n", 1261 | "print(\"s[\\\"dW1\\\"] = \\n\" + str(s[\"dW1\"]))\n", 1262 | "print(\"s[\\\"db1\\\"] = \\n\" + str(s[\"db1\"]))\n", 1263 | "print(\"s[\\\"dW2\\\"] = \\n\" + str(s[\"dW2\"]))\n", 1264 | "print(\"s[\\\"db2\\\"] = \\n\" + str(s[\"db2\"]))" 1265 | ] 1266 | }, 1267 | { 1268 | "cell_type": "markdown", 1269 | "metadata": {}, 1270 | "source": [ 1271 | "**Expected Output**:\n", 1272 | "\n", 1273 | "```\n", 1274 | "W1 = \n", 1275 | "[[ 1.63178673 -0.61919778 -0.53561312]\n", 1276 | " [-1.08040999 0.85796626 -2.29409733]]\n", 1277 | "b1 = \n", 1278 | "[[ 1.75225313]\n", 1279 | " [-0.75376553]]\n", 1280 | "W2 = \n", 1281 | "[[ 0.32648046 -0.25681174 1.46954931]\n", 1282 | " [-2.05269934 -0.31497584 -0.37661299]\n", 1283 | " [ 1.14121081 -1.09245036 -0.16498684]]\n", 1284 | "b2 = \n", 1285 | "[[-0.88529978]\n", 1286 | " [ 0.03477238]\n", 1287 | " [ 0.57537385]]\n", 1288 | "v[\"dW1\"] = \n", 1289 | "[[-0.11006192 0.11447237 0.09015907]\n", 1290 | " [ 0.05024943 0.09008559 -0.06837279]]\n", 1291 | "v[\"db1\"] = \n", 1292 | "[[-0.01228902]\n", 1293 | " [-0.09357694]]\n", 1294 | "v[\"dW2\"] = \n", 1295 | "[[-0.02678881 0.05303555 -0.06916608]\n", 1296 | " [-0.03967535 -0.06871727 -0.08452056]\n", 1297 | " [-0.06712461 -0.00126646 -0.11173103]]\n", 1298 | "v[\"db2\"] = \n", 1299 | "[[ 0.02344157]\n", 1300 | " [ 0.16598022]\n", 1301 | " [ 0.07420442]]\n", 1302 | "s[\"dW1\"] = \n", 1303 | "[[ 0.00121136 0.00131039 0.00081287]\n", 1304 | " [ 0.0002525 0.00081154 0.00046748]]\n", 1305 | "s[\"db1\"] = \n", 1306 | "[[ 1.51020075e-05]\n", 1307 | " [ 8.75664434e-04]]\n", 1308 | "s[\"dW2\"] = \n", 1309 | "[[ 7.17640232e-05 2.81276921e-04 4.78394595e-04]\n", 1310 | " [ 1.57413361e-04 4.72206320e-04 7.14372576e-04]\n", 1311 | " [ 4.50571368e-04 1.60392066e-07 1.24838242e-03]]\n", 1312 | "s[\"db2\"] = \n", 1313 | "[[ 5.49507194e-05]\n", 1314 | " [ 2.75494327e-03]\n", 1315 | " [ 5.50629536e-04]]\n", 1316 | "```" 1317 | ] 1318 | }, 1319 | { 1320 | "cell_type": "markdown", 1321 | "metadata": {}, 1322 | "source": [ 1323 | "You now have three working optimization algorithms (mini-batch gradient descent, Momentum, Adam). Let's implement a model with each of these optimizers and observe the difference." 1324 | ] 1325 | }, 1326 | { 1327 | "cell_type": "markdown", 1328 | "metadata": {}, 1329 | "source": [ 1330 | "## 5 - Model with different optimization algorithms\n", 1331 | "\n", 1332 | "Lets use the following \"moons\" dataset to test the different optimization methods. (The dataset is named \"moons\" because the data from each of the two classes looks a bit like a crescent-shaped moon.) " 1333 | ] 1334 | }, 1335 | { 1336 | "cell_type": "code", 1337 | "execution_count": null, 1338 | "metadata": { 1339 | "collapsed": true 1340 | }, 1341 | "outputs": [], 1342 | "source": [ 1343 | "train_X, train_Y = load_dataset()" 1344 | ] 1345 | }, 1346 | { 1347 | "cell_type": "markdown", 1348 | "metadata": {}, 1349 | "source": [ 1350 | "We have already implemented a 3-layer neural network. You will train it with: \n", 1351 | "- Mini-batch **Gradient Descent**: it will call your function:\n", 1352 | " - `update_parameters_with_gd()`\n", 1353 | "- Mini-batch **Momentum**: it will call your functions:\n", 1354 | " - `initialize_velocity()` and `update_parameters_with_momentum()`\n", 1355 | "- Mini-batch **Adam**: it will call your functions:\n", 1356 | " - `initialize_adam()` and `update_parameters_with_adam()`" 1357 | ] 1358 | }, 1359 | { 1360 | "cell_type": "code", 1361 | "execution_count": null, 1362 | "metadata": { 1363 | "collapsed": true 1364 | }, 1365 | "outputs": [], 1366 | "source": [ 1367 | "def model(X, Y, layers_dims, optimizer, learning_rate = 0.0007, mini_batch_size = 64, beta = 0.9,\n", 1368 | " beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8, num_epochs = 10000, print_cost = True):\n", 1369 | " \"\"\"\n", 1370 | " 3-layer neural network model which can be run in different optimizer modes.\n", 1371 | " \n", 1372 | " Arguments:\n", 1373 | " X -- input data, of shape (2, number of examples)\n", 1374 | " Y -- true \"label\" vector (1 for blue dot / 0 for red dot), of shape (1, number of examples)\n", 1375 | " layers_dims -- python list, containing the size of each layer\n", 1376 | " learning_rate -- the learning rate, scalar.\n", 1377 | " mini_batch_size -- the size of a mini batch\n", 1378 | " beta -- Momentum hyperparameter\n", 1379 | " beta1 -- Exponential decay hyperparameter for the past gradients estimates \n", 1380 | " beta2 -- Exponential decay hyperparameter for the past squared gradients estimates \n", 1381 | " epsilon -- hyperparameter preventing division by zero in Adam updates\n", 1382 | " num_epochs -- number of epochs\n", 1383 | " print_cost -- True to print the cost every 1000 epochs\n", 1384 | "\n", 1385 | " Returns:\n", 1386 | " parameters -- python dictionary containing your updated parameters \n", 1387 | " \"\"\"\n", 1388 | "\n", 1389 | " L = len(layers_dims) # number of layers in the neural networks\n", 1390 | " costs = [] # to keep track of the cost\n", 1391 | " t = 0 # initializing the counter required for Adam update\n", 1392 | " seed = 10 # For grading purposes, so that your \"random\" minibatches are the same as ours\n", 1393 | " m = X.shape[1] # number of training examples\n", 1394 | " \n", 1395 | " # Initialize parameters\n", 1396 | " parameters = initialize_parameters(layers_dims)\n", 1397 | "\n", 1398 | " # Initialize the optimizer\n", 1399 | " if optimizer == \"gd\":\n", 1400 | " pass # no initialization required for gradient descent\n", 1401 | " elif optimizer == \"momentum\":\n", 1402 | " v = initialize_velocity(parameters)\n", 1403 | " elif optimizer == \"adam\":\n", 1404 | " v, s = initialize_adam(parameters)\n", 1405 | " \n", 1406 | " # Optimization loop\n", 1407 | " for i in range(num_epochs):\n", 1408 | " \n", 1409 | " # Define the random minibatches. We increment the seed to reshuffle differently the dataset after each epoch\n", 1410 | " seed = seed + 1\n", 1411 | " minibatches = random_mini_batches(X, Y, mini_batch_size, seed)\n", 1412 | " cost_total = 0\n", 1413 | " \n", 1414 | " for minibatch in minibatches:\n", 1415 | "\n", 1416 | " # Select a minibatch\n", 1417 | " (minibatch_X, minibatch_Y) = minibatch\n", 1418 | "\n", 1419 | " # Forward propagation\n", 1420 | " a3, caches = forward_propagation(minibatch_X, parameters)\n", 1421 | "\n", 1422 | " # Compute cost and add to the cost total\n", 1423 | " cost_total += compute_cost(a3, minibatch_Y)\n", 1424 | "\n", 1425 | " # Backward propagation\n", 1426 | " grads = backward_propagation(minibatch_X, minibatch_Y, caches)\n", 1427 | "\n", 1428 | " # Update parameters\n", 1429 | " if optimizer == \"gd\":\n", 1430 | " parameters = update_parameters_with_gd(parameters, grads, learning_rate)\n", 1431 | " elif optimizer == \"momentum\":\n", 1432 | " parameters, v = update_parameters_with_momentum(parameters, grads, v, beta, learning_rate)\n", 1433 | " elif optimizer == \"adam\":\n", 1434 | " t = t + 1 # Adam counter\n", 1435 | " parameters, v, s = update_parameters_with_adam(parameters, grads, v, s,\n", 1436 | " t, learning_rate, beta1, beta2, epsilon)\n", 1437 | " cost_avg = cost_total / m\n", 1438 | " \n", 1439 | " # Print the cost every 1000 epoch\n", 1440 | " if print_cost and i % 1000 == 0:\n", 1441 | " print (\"Cost after epoch %i: %f\" %(i, cost_avg))\n", 1442 | " if print_cost and i % 100 == 0:\n", 1443 | " costs.append(cost_avg)\n", 1444 | " \n", 1445 | " # plot the cost\n", 1446 | " plt.plot(costs)\n", 1447 | " plt.ylabel('cost')\n", 1448 | " plt.xlabel('epochs (per 100)')\n", 1449 | " plt.title(\"Learning rate = \" + str(learning_rate))\n", 1450 | " plt.show()\n", 1451 | "\n", 1452 | " return parameters" 1453 | ] 1454 | }, 1455 | { 1456 | "cell_type": "markdown", 1457 | "metadata": {}, 1458 | "source": [ 1459 | "You will now run this 3 layer neural network with each of the 3 optimization methods.\n", 1460 | "\n", 1461 | "### 5.1 - Mini-batch Gradient descent\n", 1462 | "\n", 1463 | "Run the following code to see how the model does with mini-batch gradient descent." 1464 | ] 1465 | }, 1466 | { 1467 | "cell_type": "code", 1468 | "execution_count": null, 1469 | "metadata": { 1470 | "collapsed": true, 1471 | "scrolled": false 1472 | }, 1473 | "outputs": [], 1474 | "source": [ 1475 | "# train 3-layer model\n", 1476 | "layers_dims = [train_X.shape[0], 5, 2, 1]\n", 1477 | "parameters = model(train_X, train_Y, layers_dims, optimizer = \"gd\")\n", 1478 | "\n", 1479 | "# Predict\n", 1480 | "predictions = predict(train_X, train_Y, parameters)\n", 1481 | "\n", 1482 | "# Plot decision boundary\n", 1483 | "plt.title(\"Model with Gradient Descent optimization\")\n", 1484 | "axes = plt.gca()\n", 1485 | "axes.set_xlim([-1.5,2.5])\n", 1486 | "axes.set_ylim([-1,1.5])\n", 1487 | "plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)" 1488 | ] 1489 | }, 1490 | { 1491 | "cell_type": "markdown", 1492 | "metadata": {}, 1493 | "source": [ 1494 | "### 5.2 - Mini-batch gradient descent with momentum\n", 1495 | "\n", 1496 | "Run the following code to see how the model does with momentum. Because this example is relatively simple, the gains from using momemtum are small; but for more complex problems you might see bigger gains." 1497 | ] 1498 | }, 1499 | { 1500 | "cell_type": "code", 1501 | "execution_count": null, 1502 | "metadata": { 1503 | "collapsed": true 1504 | }, 1505 | "outputs": [], 1506 | "source": [ 1507 | "# train 3-layer model\n", 1508 | "layers_dims = [train_X.shape[0], 5, 2, 1]\n", 1509 | "parameters = model(train_X, train_Y, layers_dims, beta = 0.9, optimizer = \"momentum\")\n", 1510 | "\n", 1511 | "# Predict\n", 1512 | "predictions = predict(train_X, train_Y, parameters)\n", 1513 | "\n", 1514 | "# Plot decision boundary\n", 1515 | "plt.title(\"Model with Momentum optimization\")\n", 1516 | "axes = plt.gca()\n", 1517 | "axes.set_xlim([-1.5,2.5])\n", 1518 | "axes.set_ylim([-1,1.5])\n", 1519 | "plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)" 1520 | ] 1521 | }, 1522 | { 1523 | "cell_type": "markdown", 1524 | "metadata": {}, 1525 | "source": [ 1526 | "### 5.3 - Mini-batch with Adam mode\n", 1527 | "\n", 1528 | "Run the following code to see how the model does with Adam." 1529 | ] 1530 | }, 1531 | { 1532 | "cell_type": "code", 1533 | "execution_count": null, 1534 | "metadata": { 1535 | "collapsed": true 1536 | }, 1537 | "outputs": [], 1538 | "source": [ 1539 | "# train 3-layer model\n", 1540 | "layers_dims = [train_X.shape[0], 5, 2, 1]\n", 1541 | "parameters = model(train_X, train_Y, layers_dims, optimizer = \"adam\")\n", 1542 | "\n", 1543 | "# Predict\n", 1544 | "predictions = predict(train_X, train_Y, parameters)\n", 1545 | "\n", 1546 | "# Plot decision boundary\n", 1547 | "plt.title(\"Model with Adam optimization\")\n", 1548 | "axes = plt.gca()\n", 1549 | "axes.set_xlim([-1.5,2.5])\n", 1550 | "axes.set_ylim([-1,1.5])\n", 1551 | "plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)" 1552 | ] 1553 | }, 1554 | { 1555 | "cell_type": "markdown", 1556 | "metadata": {}, 1557 | "source": [ 1558 | "### 5.4 - Summary\n", 1559 | "\n", 1560 | " \n", 1561 | " \n", 1562 | " \n", 1565 | " \n", 1568 | " \n", 1571 | "\n", 1572 | " \n", 1573 | " \n", 1576 | " \n", 1579 | " \n", 1582 | " \n", 1583 | " \n", 1586 | " \n", 1589 | " \n", 1592 | " \n", 1593 | " \n", 1594 | " \n", 1597 | " \n", 1600 | " \n", 1603 | " \n", 1604 | "
\n", 1563 | " **optimization method**\n", 1564 | " \n", 1566 | " **accuracy**\n", 1567 | " \n", 1569 | " **cost shape**\n", 1570 | "
\n", 1574 | " Gradient descent\n", 1575 | " \n", 1577 | " 79.7%\n", 1578 | " \n", 1580 | " oscillations\n", 1581 | "
\n", 1584 | " Momentum\n", 1585 | " \n", 1587 | " 79.7%\n", 1588 | " \n", 1590 | " oscillations\n", 1591 | "
\n", 1595 | " Adam\n", 1596 | " \n", 1598 | " 94%\n", 1599 | " \n", 1601 | " smoother\n", 1602 | "
\n", 1605 | "\n", 1606 | "Momentum usually helps, but given the small learning rate and the simplistic dataset, its impact is almost negligeable. Also, the huge oscillations you see in the cost come from the fact that some minibatches are more difficult thans others for the optimization algorithm.\n", 1607 | "\n", 1608 | "Adam on the other hand, clearly outperforms mini-batch gradient descent and Momentum. If you run the model for more epochs on this simple dataset, all three methods will lead to very good results. However, you've seen that Adam converges a lot faster.\n", 1609 | "\n", 1610 | "Some advantages of Adam include:\n", 1611 | "- Relatively low memory requirements (though higher than gradient descent and gradient descent with momentum) \n", 1612 | "- Usually works well even with little tuning of hyperparameters (except $\\alpha$)" 1613 | ] 1614 | }, 1615 | { 1616 | "cell_type": "markdown", 1617 | "metadata": {}, 1618 | "source": [ 1619 | "**References**:\n", 1620 | "\n", 1621 | "- Adam paper: https://arxiv.org/pdf/1412.6980.pdf" 1622 | ] 1623 | } 1624 | ], 1625 | "metadata": { 1626 | "coursera": { 1627 | "course_slug": "deep-neural-network", 1628 | "graded_item_id": "Ckiv2", 1629 | "launcher_item_id": "eNLYh" 1630 | }, 1631 | "kernelspec": { 1632 | "display_name": "Python 3", 1633 | "language": "python", 1634 | "name": "python3" 1635 | }, 1636 | "language_info": { 1637 | "codemirror_mode": { 1638 | "name": "ipython", 1639 | "version": 3 1640 | }, 1641 | "file_extension": ".py", 1642 | "mimetype": "text/x-python", 1643 | "name": "python", 1644 | "nbconvert_exporter": "python", 1645 | "pygments_lexer": "ipython3", 1646 | "version": "3.6.0" 1647 | } 1648 | }, 1649 | "nbformat": 4, 1650 | "nbformat_minor": 2 1651 | } 1652 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deep-Learning 2 | 3 | These are Neural Networks and Deep Learning Course Materials given by deeplearning.ai and Andrew NG. 4 | 5 | ## Learning Objectives 6 | 7 | In this course, you will learn the foundations of deep learning. When you finish this class, you will: 8 | 9 | - Understand the major technology trends driving Deep Learning 10 | - Be able to build, train and apply fully connected deep neural networks 11 | - Know how to implement efficient (vectorized) neural networks 12 | - Understand the key parameters in a neural network's architecture 13 | 14 | This course also teaches you how Deep Learning actually works, rather than presenting only a cursory or surface-level description. So after completing it, you will be able to apply deep learning to a your own applications. If you are looking for a job in AI, after this course you will also be able to answer basic interview questions. 15 | 16 | Programming Assignments: 17 | 18 | - Python Basics with Numpy 19 | - Logistic Regression with a Neural Network mindset 20 | - Planar data classification with one hidden layer 21 | - Building your Deep Neural Network Step by Step 22 | - Deep Neural Network Application 23 | 24 | -------------------------------------------------------------------------------- /datasets/test_catvnoncat.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/berkayalan/neural-networks-and-deep-learning/590b5b40199f358e911da44f99f6c3e00b0c2934/datasets/test_catvnoncat.h5 -------------------------------------------------------------------------------- /datasets/train_catvnoncat.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/berkayalan/neural-networks-and-deep-learning/590b5b40199f358e911da44f99f6c3e00b0c2934/datasets/train_catvnoncat.h5 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy==1.18.5 2 | matplotlib==3.2.2 3 | scipy==1.5.0 4 | h5py==2.10.0 5 | Pillow==8.0.1 6 | --------------------------------------------------------------------------------