├── .gitattributes
├── .gitignore
├── Certificate
├── Convolutional Neural Networks.PNG
├── Convolutional Neural Networks.pdf
├── Improving Deep Neural Networks_Hyperparameter tuning_ Regularization.PNG
├── Improving Deep Neural Networks_Hyperparameter tuning_ Regularization.pdf
├── Neural Networks and Deep Learning.pdf
├── Neural Networks for Machine Learning.png
├── Sequence Models.PNG
├── Sequence Models.pdf
├── Structuring Machine Learning Projects.PNG
└── Structuring Machine Learning Projects.pdf
├── Convolutional Neural Networks
├── Week 1
│ ├── Convolutional Model_Step by Step.ipynb
│ ├── Convolutional model_Application.ipynb
│ └── The basics of ConvNets.pdf
├── Week 2
│ ├── Deep convolutional models.pdf
│ └── Residual Networks.ipynb
├── Week 3
│ ├── Car detection with YOLOv2.ipynb
│ └── Detection algorithms.pdf
└── Week 4
│ ├── 4.pdf
│ └── Face Recognition for the Happy House.ipynb
├── Deep Learning.pdf
├── Improving Deep Neural Networks_Hyperparameter tuning_ Regularization
├── Week 1
│ ├── Gradient Checking.ipynb
│ ├── Gradient Checking.py
│ ├── Initialization.ipynb
│ ├── Initialization.py
│ ├── Practical aspects of deep learning.pdf
│ ├── Regularization.ipynb
│ └── Regularization.py
├── Week 2
│ ├── Optimisation algorithms.pdf
│ ├── Optimization methods.ipynb
│ └── Optimization methods.py
└── Week 3
│ ├── Hyperparameter tuning, Batch Normalization, Programming Frameworks.pdf
│ ├── Tensorflow Tutorial.ipynb
│ └── Tensorflow Tutorial.py
├── Neural Networks and Deep Learning
├── Week 1
│ └── Introduction to Deep Learning.pdf
├── Week 2
│ ├── Logistic Regression as a Neural Network
│ │ ├── Logistic+Regression+with+a+Neural+Network+mindset+v3.html
│ │ ├── Logistic+Regression+with+a+Neural+Network+mindset+v3.ipynb
│ │ ├── datasets
│ │ │ ├── test_catvnoncat.h5
│ │ │ └── train_catvnoncat.h5
│ │ └── images
│ │ │ ├── LogReg_kiank.png
│ │ │ ├── cat_in_iran.jpg
│ │ │ ├── gargouille.jpg
│ │ │ ├── image1.png
│ │ │ ├── image2.png
│ │ │ ├── la_defense.jpg
│ │ │ ├── my_image.jpg
│ │ │ └── my_image2.jpg
│ ├── Neural Network Basics.pdf
│ ├── Python Basics with Numpy
│ │ ├── Python+Basics+With+Numpy+v3.ipynb
│ │ └── images
│ │ │ ├── Sigmoid.png
│ │ │ ├── image2vector.png
│ │ │ └── image2vector_kiank.png
│ ├── Quiz.ipynb
│ └── README.md
├── Week 3
│ ├── Planar data classification with one hidden layer
│ │ ├── Planar+data+classification+with+one+hidden+layer+v3.html
│ │ ├── Planar+data+classification+with+one+hidden+layer+v3.ipynb
│ │ ├── README.md
│ │ ├── images
│ │ │ ├── classification_kiank.png
│ │ │ ├── grad_summary.png
│ │ │ ├── sgd.gif
│ │ │ └── sgd_bad.gif
│ │ ├── planar_utils.py
│ │ └── testCases.py
│ ├── README.md
│ └── Shallow Neural Networks.pdf
└── Week 4
│ ├── Building your Deep Neural Network - Step by Step
│ ├── Building+your+Deep+Neural+Network+-+Step+by+Step+v3.html
│ ├── Building+your+Deep+Neural+Network+-+Step+by+Step+v3.ipynb
│ ├── dnn_utils_v2.py
│ ├── images
│ │ ├── 2layerNN.png
│ │ ├── NlayerNN.png
│ │ ├── backpass.png
│ │ ├── backprop.png
│ │ ├── backprop_kiank.png
│ │ ├── final outline.png
│ │ ├── imvector.png
│ │ ├── linearback_kiank.png
│ │ ├── mn_backward.png
│ │ ├── model_architecture2.png
│ │ ├── model_architecture_kiank.png
│ │ ├── n_model_backward.png
│ │ ├── nm_backward.png
│ │ ├── relu.png
│ │ └── structure.png
│ └── testCases_v2.py
│ ├── Deep Neural Network Application Image Classification
│ ├── Deep+Neural+Network+-+Application+v3.html
│ ├── Deep+Neural+Network+-+Application+v3.ipynb
│ ├── datasets
│ │ ├── test_catvnoncat.h5
│ │ └── train_catvnoncat.h5
│ ├── dnn_app_utils_v2.py
│ └── images
│ │ ├── 2layerNN_kiank.png
│ │ ├── LlayerNN_kiank.png
│ │ ├── imvector.png
│ │ ├── imvectorkiank.png
│ │ └── my_image.jpg
│ ├── Key concepts on Deep Neural Networks.pdf
│ └── README.md
├── README.md
├── Sequence Models
├── Week 1
│ ├── Building a Recurrent Neural Network - Step by Step
│ │ ├── Building a Recurrent Neural Network - Step by Step - v1.ipynb
│ │ └── images
│ │ │ ├── LSTM.png
│ │ │ ├── LSTM_rnn.png
│ │ │ ├── clip.png
│ │ │ ├── initial_state.png
│ │ │ ├── rnn.png
│ │ │ ├── rnn_cell_backprop.png
│ │ │ ├── rnn_step_forward.png
│ │ │ └── sampling.png
│ ├── Dinosaur Island -- Character-level language model
│ │ ├── Dinosaurus Island -- Character level language model final - v3.ipynb
│ │ └── images
│ │ │ ├── clip.png
│ │ │ ├── dino.jpg
│ │ │ ├── dinos3.png
│ │ │ ├── fountain.jpg
│ │ │ ├── mangosaurus.jpeg
│ │ │ ├── rnn.png
│ │ │ └── shakespeare.jpg
│ ├── Jazz improvisation with LSTM
│ │ ├── Jazz improvisation with LSTM - v1.ipynb
│ │ ├── data
│ │ │ ├── 30s_seq.mp3
│ │ │ ├── 30s_trained_model.mp3
│ │ │ └── training_example.mp3
│ │ ├── images
│ │ │ ├── chord_symbols.png
│ │ │ ├── dataset.png
│ │ │ ├── jazz.jpg
│ │ │ ├── model.png
│ │ │ ├── music_gen.png
│ │ │ ├── music_generation.png
│ │ │ └── tones.png
│ │ └── inference_code.py
│ └── Recurrent Neural Networks.pdf
├── Week 2
│ ├── Emojify
│ │ ├── Emojify - v2.ipynb
│ │ └── images
│ │ │ ├── data_set.png
│ │ │ ├── dataset_kiank.png
│ │ │ ├── emb_kiank.png
│ │ │ ├── embedding1.png
│ │ │ ├── emo_model.png
│ │ │ ├── emoji_list.png
│ │ │ ├── emojifier-v2.png
│ │ │ ├── emojifierv1.png
│ │ │ ├── emojify_model.png
│ │ │ ├── emojiss.png
│ │ │ ├── image_1.png
│ │ │ └── woebot.png
│ ├── Natural Language Processing & Word Embeddings.pdf
│ └── Word Vector Representation
│ │ ├── Operations on word vectors - v2.ipynb
│ │ └── images
│ │ ├── 1-hot-vector.png
│ │ ├── cosine_sim.png
│ │ ├── equalize.png
│ │ ├── equalize1.png
│ │ ├── equalize10.png
│ │ ├── equalize7.png
│ │ ├── equalize8.png
│ │ ├── equalize9.png
│ │ ├── equalize_kiank.png
│ │ ├── equalize_kiank1.png
│ │ ├── equalize_kiank2.png
│ │ ├── equalize_kiank3.png
│ │ ├── lookup.png
│ │ ├── neutral.png
│ │ ├── neutralize.png
│ │ ├── neutralize_kiank.png
│ │ ├── skipgram.png
│ │ └── slide_window.mp4
└── Week 3
│ ├── Machine Translation
│ ├── Neural machine translation with attention - v2.ipynb
│ └── images
│ │ ├── attn_mechanism.png
│ │ ├── attn_model.png
│ │ ├── date_attention.png
│ │ ├── date_attention2.png
│ │ ├── poorly_trained_model.png
│ │ └── table.png
│ ├── Sequence models & Attention mechanism.pdf
│ └── Trigger word detection
│ ├── Trigger word detection - v1.ipynb
│ ├── audio_examples
│ ├── chime.wav
│ ├── example_train.wav
│ ├── insert_reference.wav
│ ├── my_audio.wav
│ └── train_reference.wav
│ ├── chime_output.wav
│ ├── images
│ ├── label_diagram.png
│ ├── model.png
│ ├── ones_reference.png
│ ├── sound.png
│ ├── spectrogram.png
│ ├── train_label.png
│ └── train_reference.png
│ ├── insert_test.wav
│ ├── raw_data
│ ├── activates
│ │ ├── 1.wav
│ │ ├── 1_act2.wav
│ │ ├── 1_act3.wav
│ │ ├── 2.wav
│ │ ├── 2_act2.wav
│ │ ├── 2_act3.wav
│ │ ├── 3.wav
│ │ ├── 3_act2.wav
│ │ ├── 3_act3.wav
│ │ └── 4_act2.wav
│ ├── backgrounds
│ │ ├── 1.wav
│ │ └── 2.wav
│ ├── dev
│ │ ├── 1.wav
│ │ └── 2.wav
│ └── negatives
│ │ ├── 1.wav
│ │ ├── 1_0.wav
│ │ ├── 2.wav
│ │ ├── 2_1.wav
│ │ ├── 3.wav
│ │ ├── 3_2.wav
│ │ ├── 4.wav
│ │ ├── 4_0.wav
│ │ ├── 5.wav
│ │ └── 5_1.wav
│ └── train.wav
└── Structuring Machine Learning Projects
├── Autonomous driving (case study).pdf
└── Bird recognition in the city of Peacetopia (case study).pdf
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
4 | # Custom for Visual Studio
5 | *.cs diff=csharp
6 |
7 | # Standard to msysgit
8 | *.doc diff=astextplain
9 | *.DOC diff=astextplain
10 | *.docx diff=astextplain
11 | *.DOCX diff=astextplain
12 | *.dot diff=astextplain
13 | *.DOT diff=astextplain
14 | *.pdf diff=astextplain
15 | *.PDF diff=astextplain
16 | *.rtf diff=astextplain
17 | *.RTF diff=astextplain
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Windows image file caches
2 | Thumbs.db
3 | ehthumbs.db
4 |
5 | # Folder config file
6 | Desktop.ini
7 |
8 | # Recycle Bin used on file shares
9 | $RECYCLE.BIN/
10 |
11 | # Windows Installer files
12 | *.cab
13 | *.msi
14 | *.msm
15 | *.msp
16 |
17 | # Windows shortcuts
18 | *.lnk
19 |
20 | # =========================
21 | # Operating System Files
22 | # =========================
23 |
24 | # OSX
25 | # =========================
26 |
27 | .DS_Store
28 | .AppleDouble
29 | .LSOverride
30 |
31 | # Thumbnails
32 | ._*
33 |
34 | # Files that might appear in the root of a volume
35 | .DocumentRevisions-V100
36 | .fseventsd
37 | .Spotlight-V100
38 | .TemporaryItems
39 | .Trashes
40 | .VolumeIcon.icns
41 |
42 | # Directories potentially created on remote AFP share
43 | .AppleDB
44 | .AppleDesktop
45 | Network Trash Folder
46 | Temporary Items
47 | .apdisk
48 |
--------------------------------------------------------------------------------
/Certificate/Convolutional Neural Networks.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Certificate/Convolutional Neural Networks.PNG
--------------------------------------------------------------------------------
/Certificate/Convolutional Neural Networks.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Certificate/Convolutional Neural Networks.pdf
--------------------------------------------------------------------------------
/Certificate/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Certificate/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization.PNG
--------------------------------------------------------------------------------
/Certificate/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Certificate/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization.pdf
--------------------------------------------------------------------------------
/Certificate/Neural Networks and Deep Learning.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Certificate/Neural Networks and Deep Learning.pdf
--------------------------------------------------------------------------------
/Certificate/Neural Networks for Machine Learning.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Certificate/Neural Networks for Machine Learning.png
--------------------------------------------------------------------------------
/Certificate/Sequence Models.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Certificate/Sequence Models.PNG
--------------------------------------------------------------------------------
/Certificate/Sequence Models.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Certificate/Sequence Models.pdf
--------------------------------------------------------------------------------
/Certificate/Structuring Machine Learning Projects.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Certificate/Structuring Machine Learning Projects.PNG
--------------------------------------------------------------------------------
/Certificate/Structuring Machine Learning Projects.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Certificate/Structuring Machine Learning Projects.pdf
--------------------------------------------------------------------------------
/Convolutional Neural Networks/Week 1/The basics of ConvNets.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Convolutional Neural Networks/Week 1/The basics of ConvNets.pdf
--------------------------------------------------------------------------------
/Convolutional Neural Networks/Week 2/Deep convolutional models.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Convolutional Neural Networks/Week 2/Deep convolutional models.pdf
--------------------------------------------------------------------------------
/Convolutional Neural Networks/Week 3/Detection algorithms.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Convolutional Neural Networks/Week 3/Detection algorithms.pdf
--------------------------------------------------------------------------------
/Convolutional Neural Networks/Week 4/4.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Convolutional Neural Networks/Week 4/4.pdf
--------------------------------------------------------------------------------
/Deep Learning.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Deep Learning.pdf
--------------------------------------------------------------------------------
/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization/Week 1/Gradient Checking.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Gradient Checking\n",
8 | "\n",
9 | "Welcome to the final assignment for this week! In this assignment you 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 = np.dot(theta, x)\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 | " ** J ** | \n",
130 | " 8 | \n",
131 | "
\n",
132 | "
"
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": 4,
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": 5,
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 | " ** dtheta ** | \n",
201 | " 2 | \n",
202 | "
\n",
203 | "
"
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": 6,
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": 7,
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 | " ** difference ** | \n",
311 | " 2.9193358103083e-10 | \n",
312 | "
\n",
313 | "
"
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": 8,
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": 9,
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": 10,
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 > 1e-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": 11,
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.285093156781\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 | " ** There is a mistake in the backward propagation!** | \n",
598 | " difference = 0.285093156781 | \n",
599 | "
\n",
600 | "
"
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 |
--------------------------------------------------------------------------------
/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization/Week 1/Gradient Checking.py:
--------------------------------------------------------------------------------
1 |
2 | # coding: utf-8
3 |
4 | # # Gradient Checking
5 | #
6 | # Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking.
7 | #
8 | # 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.
9 | #
10 | # 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".
11 | #
12 | # Let's do it!
13 |
14 | # In[1]:
15 |
16 | # Packages
17 | import numpy as np
18 | from testCases import *
19 | from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector
20 |
21 |
22 | # ## 1) How does gradient checking work?
23 | #
24 | # 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.
25 | #
26 | # 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}$.
27 | #
28 | # Let's look back at the definition of a derivative (or gradient):
29 | # $$ \frac{\partial J}{\partial \theta} = \lim_{\varepsilon \to 0} \frac{J(\theta + \varepsilon) - J(\theta - \varepsilon)}{2 \varepsilon} \tag{1}$$
30 | #
31 | # 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."
32 | #
33 | # We know the following:
34 | #
35 | # - $\frac{\partial J}{\partial \theta}$ is what you want to make sure you're computing correctly.
36 | # - 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.
37 | #
38 | # 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!
39 |
40 | # ## 2) 1-dimensional gradient checking
41 | #
42 | # Consider a 1D linear function $J(\theta) = \theta x$. The model contains only a single real-valued parameter $\theta$, and takes $x$ as input.
43 | #
44 | # 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.
45 | #
46 | #
47 | # **Figure 1** : **1D linear model**
48 | #
49 | # 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").
50 | #
51 | # **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.
52 |
53 | # In[2]:
54 |
55 | # GRADED FUNCTION: forward_propagation
56 |
57 | def forward_propagation(x, theta):
58 | """
59 | Implement the linear forward propagation (compute J) presented in Figure 1 (J(theta) = theta * x)
60 |
61 | Arguments:
62 | x -- a real-valued input
63 | theta -- our parameter, a real number as well
64 |
65 | Returns:
66 | J -- the value of function J, computed using the formula J(theta) = theta * x
67 | """
68 |
69 | ### START CODE HERE ### (approx. 1 line)
70 | J = np.dot(theta, x)
71 | ### END CODE HERE ###
72 |
73 | return J
74 |
75 |
76 | # In[3]:
77 |
78 | x, theta = 2, 4
79 | J = forward_propagation(x, theta)
80 | print ("J = " + str(J))
81 |
82 |
83 | # **Expected Output**:
84 | #
85 | #
86 | #
87 | # ** J ** |
88 | # 8 |
89 | #
90 | #
91 |
92 | # **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$.
93 |
94 | # In[4]:
95 |
96 | # GRADED FUNCTION: backward_propagation
97 |
98 | def backward_propagation(x, theta):
99 | """
100 | Computes the derivative of J with respect to theta (see Figure 1).
101 |
102 | Arguments:
103 | x -- a real-valued input
104 | theta -- our parameter, a real number as well
105 |
106 | Returns:
107 | dtheta -- the gradient of the cost with respect to theta
108 | """
109 |
110 | ### START CODE HERE ### (approx. 1 line)
111 | dtheta = x
112 | ### END CODE HERE ###
113 |
114 | return dtheta
115 |
116 |
117 | # In[5]:
118 |
119 | x, theta = 2, 4
120 | dtheta = backward_propagation(x, theta)
121 | print ("dtheta = " + str(dtheta))
122 |
123 |
124 | # **Expected Output**:
125 | #
126 | #
127 | #
128 | # ** dtheta ** |
129 | # 2 |
130 | #
131 | #
132 |
133 | # **Exercise**: To show that the `backward_propagation()` function is correctly computing the gradient $\frac{\partial J}{\partial \theta}$, let's implement gradient checking.
134 | #
135 | # **Instructions**:
136 | # - First compute "gradapprox" using the formula above (1) and a small value of $\varepsilon$. Here are the Steps to follow:
137 | # 1. $\theta^{+} = \theta + \varepsilon$
138 | # 2. $\theta^{-} = \theta - \varepsilon$
139 | # 3. $J^{+} = J(\theta^{+})$
140 | # 4. $J^{-} = J(\theta^{-})$
141 | # 5. $gradapprox = \frac{J^{+} - J^{-}}{2 \varepsilon}$
142 | # - Then compute the gradient using backward propagation, and store the result in a variable "grad"
143 | # - Finally, compute the relative difference between "gradapprox" and the "grad" using the following formula:
144 | # $$ difference = \frac {\mid\mid grad - gradapprox \mid\mid_2}{\mid\mid grad \mid\mid_2 + \mid\mid gradapprox \mid\mid_2} \tag{2}$$
145 | # You will need 3 Steps to compute this formula:
146 | # - 1'. compute the numerator using np.linalg.norm(...)
147 | # - 2'. compute the denominator. You will need to call np.linalg.norm(...) twice.
148 | # - 3'. divide them.
149 | # - 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.
150 | #
151 |
152 | # In[6]:
153 |
154 | # GRADED FUNCTION: gradient_check
155 |
156 | def gradient_check(x, theta, epsilon = 1e-7):
157 | """
158 | Implement the backward propagation presented in Figure 1.
159 |
160 | Arguments:
161 | x -- a real-valued input
162 | theta -- our parameter, a real number as well
163 | epsilon -- tiny shift to the input to compute approximated gradient with formula(1)
164 |
165 | Returns:
166 | difference -- difference (2) between the approximated gradient and the backward propagation gradient
167 | """
168 |
169 | # Compute gradapprox using left side of formula (1). epsilon is small enough, you don't need to worry about the limit.
170 | ### START CODE HERE ### (approx. 5 lines)
171 | thetaplus = theta + epsilon # Step 1
172 | thetaminus = theta - epsilon # Step 2
173 | J_plus = forward_propagation(x, thetaplus) # Step 3
174 | J_minus = forward_propagation(x, thetaminus) # Step 4
175 | gradapprox = (J_plus - J_minus) / (2 * epsilon) # Step 5
176 | ### END CODE HERE ###
177 |
178 | # Check if gradapprox is close enough to the output of backward_propagation()
179 | ### START CODE HERE ### (approx. 1 line)
180 | grad = backward_propagation(x, theta)
181 | ### END CODE HERE ###
182 |
183 | ### START CODE HERE ### (approx. 1 line)
184 | numerator = np.linalg.norm(grad - gradapprox) # Step 1'
185 | denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) # Step 2'
186 | difference = numerator / denominator # Step 3'
187 | ### END CODE HERE ###
188 |
189 | if difference < 1e-7:
190 | print ("The gradient is correct!")
191 | else:
192 | print ("The gradient is wrong!")
193 |
194 | return difference
195 |
196 |
197 | # In[7]:
198 |
199 | x, theta = 2, 4
200 | difference = gradient_check(x, theta)
201 | print("difference = " + str(difference))
202 |
203 |
204 | # **Expected Output**:
205 | # The gradient is correct!
206 | #
207 | #
208 | # ** difference ** |
209 | # 2.9193358103083e-10 |
210 | #
211 | #
212 |
213 | # 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()`.
214 | #
215 | # 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!
216 |
217 | # ## 3) N-dimensional gradient checking
218 |
219 | # The following figure describes the forward and backward propagation of your fraud detection model.
220 | #
221 | #
222 | # **Figure 2** : **deep neural network**
*LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID*
223 | #
224 | # Let's look at your implementations for forward propagation and backward propagation.
225 |
226 | # In[8]:
227 |
228 | def forward_propagation_n(X, Y, parameters):
229 | """
230 | Implements the forward propagation (and computes the cost) presented in Figure 3.
231 |
232 | Arguments:
233 | X -- training set for m examples
234 | Y -- labels for m examples
235 | parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":
236 | W1 -- weight matrix of shape (5, 4)
237 | b1 -- bias vector of shape (5, 1)
238 | W2 -- weight matrix of shape (3, 5)
239 | b2 -- bias vector of shape (3, 1)
240 | W3 -- weight matrix of shape (1, 3)
241 | b3 -- bias vector of shape (1, 1)
242 |
243 | Returns:
244 | cost -- the cost function (logistic cost for one example)
245 | """
246 |
247 | # retrieve parameters
248 | m = X.shape[1]
249 | W1 = parameters["W1"]
250 | b1 = parameters["b1"]
251 | W2 = parameters["W2"]
252 | b2 = parameters["b2"]
253 | W3 = parameters["W3"]
254 | b3 = parameters["b3"]
255 |
256 | # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID
257 | Z1 = np.dot(W1, X) + b1
258 | A1 = relu(Z1)
259 | Z2 = np.dot(W2, A1) + b2
260 | A2 = relu(Z2)
261 | Z3 = np.dot(W3, A2) + b3
262 | A3 = sigmoid(Z3)
263 |
264 | # Cost
265 | logprobs = np.multiply(-np.log(A3),Y) + np.multiply(-np.log(1 - A3), 1 - Y)
266 | cost = 1./m * np.sum(logprobs)
267 |
268 | cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3)
269 |
270 | return cost, cache
271 |
272 |
273 | # Now, run backward propagation.
274 |
275 | # In[9]:
276 |
277 | def backward_propagation_n(X, Y, cache):
278 | """
279 | Implement the backward propagation presented in figure 2.
280 |
281 | Arguments:
282 | X -- input datapoint, of shape (input size, 1)
283 | Y -- true "label"
284 | cache -- cache output from forward_propagation_n()
285 |
286 | Returns:
287 | gradients -- A dictionary with the gradients of the cost with respect to each parameter, activation and pre-activation variables.
288 | """
289 |
290 | m = X.shape[1]
291 | (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache
292 |
293 | dZ3 = A3 - Y
294 | dW3 = 1./m * np.dot(dZ3, A2.T)
295 | db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)
296 |
297 | dA2 = np.dot(W3.T, dZ3)
298 | dZ2 = np.multiply(dA2, np.int64(A2 > 0))
299 | dW2 = 1./m * np.dot(dZ2, A1.T) * 2
300 | db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)
301 |
302 | dA1 = np.dot(W2.T, dZ2)
303 | dZ1 = np.multiply(dA1, np.int64(A1 > 0))
304 | dW1 = 1./m * np.dot(dZ1, X.T)
305 | db1 = 4./m * np.sum(dZ1, axis=1, keepdims = True)
306 |
307 | gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,
308 | "dA2": dA2, "dZ2": dZ2, "dW2": dW2, "db2": db2,
309 | "dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1}
310 |
311 | return gradients
312 |
313 |
314 | # 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.
315 |
316 | # **How does gradient checking work?**.
317 | #
318 | # As in 1) and 2), you want to compare "gradapprox" to the gradient computed by backpropagation. The formula is still:
319 | #
320 | # $$ \frac{\partial J}{\partial \theta} = \lim_{\varepsilon \to 0} \frac{J(\theta + \varepsilon) - J(\theta - \varepsilon)}{2 \varepsilon} \tag{1}$$
321 | #
322 | # 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.
323 | #
324 | # The inverse function is "`vector_to_dictionary`" which outputs back the "parameters" dictionary.
325 | #
326 | #
327 | # **Figure 2** : **dictionary_to_vector() and vector_to_dictionary()**
You will need these functions in gradient_check_n()
328 | #
329 | # We have also converted the "gradients" dictionary into a vector "grad" using gradients_to_vector(). You don't need to worry about that.
330 | #
331 | # **Exercise**: Implement gradient_check_n().
332 | #
333 | # **Instructions**: Here is pseudo-code that will help you implement the gradient check.
334 | #
335 | # For each i in num_parameters:
336 | # - To compute `J_plus[i]`:
337 | # 1. Set $\theta^{+}$ to `np.copy(parameters_values)`
338 | # 2. Set $\theta^{+}_i$ to $\theta^{+}_i + \varepsilon$
339 | # 3. Calculate $J^{+}_i$ using to `forward_propagation_n(x, y, vector_to_dictionary(`$\theta^{+}$ `))`.
340 | # - To compute `J_minus[i]`: do the same thing with $\theta^{-}$
341 | # - Compute $gradapprox[i] = \frac{J^{+}_i - J^{-}_i}{2 \varepsilon}$
342 | #
343 | # 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:
344 | # $$ difference = \frac {\| grad - gradapprox \|_2}{\| grad \|_2 + \| gradapprox \|_2 } \tag{3}$$
345 |
346 | # In[10]:
347 |
348 | # GRADED FUNCTION: gradient_check_n
349 |
350 | def gradient_check_n(parameters, gradients, X, Y, epsilon = 1e-7):
351 | """
352 | Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n
353 |
354 | Arguments:
355 | parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":
356 | grad -- output of backward_propagation_n, contains gradients of the cost with respect to the parameters.
357 | x -- input datapoint, of shape (input size, 1)
358 | y -- true "label"
359 | epsilon -- tiny shift to the input to compute approximated gradient with formula(1)
360 |
361 | Returns:
362 | difference -- difference (2) between the approximated gradient and the backward propagation gradient
363 | """
364 |
365 | # Set-up variables
366 | parameters_values, _ = dictionary_to_vector(parameters)
367 | grad = gradients_to_vector(gradients)
368 | num_parameters = parameters_values.shape[0]
369 | J_plus = np.zeros((num_parameters, 1))
370 | J_minus = np.zeros((num_parameters, 1))
371 | gradapprox = np.zeros((num_parameters, 1))
372 |
373 | # Compute gradapprox
374 | for i in range(num_parameters):
375 |
376 | # Compute J_plus[i]. Inputs: "parameters_values, epsilon". Output = "J_plus[i]".
377 | # "_" is used because the function you have to outputs two parameters but we only care about the first one
378 | ### START CODE HERE ### (approx. 3 lines)
379 | thetaplus = np.copy(parameters_values) # Step 1
380 | thetaplus[i][0] = thetaplus[i][0] + epsilon # Step 2
381 | J_plus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaplus)) # Step 3
382 | ### END CODE HERE ###
383 |
384 | # Compute J_minus[i]. Inputs: "parameters_values, epsilon". Output = "J_minus[i]".
385 | ### START CODE HERE ### (approx. 3 lines)
386 | thetaminus = np.copy(parameters_values) # Step 1
387 | thetaminus[i][0] = thetaminus[i][0] - epsilon # Step 2
388 | J_minus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaminus)) # Step 3
389 | ### END CODE HERE ###
390 |
391 | # Compute gradapprox[i]
392 | ### START CODE HERE ### (approx. 1 line)
393 | gradapprox[i] = (J_plus[i] - J_minus[i]) / (2 * epsilon)
394 | ### END CODE HERE ###
395 |
396 | # Compare gradapprox to backward propagation gradients by computing difference.
397 | ### START CODE HERE ### (approx. 1 line)
398 | numerator = np.linalg.norm(grad - gradapprox) # Step 1'
399 | denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) # Step 2'
400 | difference = numerator / denominator # Step 3'
401 | ### END CODE HERE ###
402 |
403 | if difference > 1e-7:
404 | print ("\033[93m" + "There is a mistake in the backward propagation! difference = " + str(difference) + "\033[0m")
405 | else:
406 | print ("\033[92m" + "Your backward propagation works perfectly fine! difference = " + str(difference) + "\033[0m")
407 |
408 | return difference
409 |
410 |
411 | # In[11]:
412 |
413 | X, Y, parameters = gradient_check_n_test_case()
414 |
415 | cost, cache = forward_propagation_n(X, Y, parameters)
416 | gradients = backward_propagation_n(X, Y, cache)
417 | difference = gradient_check_n(parameters, gradients, X, Y)
418 |
419 |
420 | # **Expected output**:
421 | #
422 | #
423 | #
424 | # ** There is a mistake in the backward propagation!** |
425 | # difference = 0.285093156781 |
426 | #
427 | #
428 |
429 | # 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.
430 | #
431 | # 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.
432 | #
433 | # **Note**
434 | # - 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.
435 | # - 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.
436 | #
437 | # 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. :)
438 | #
439 | #
440 | # **What you should remember from this notebook**:
441 | # - Gradient checking verifies closeness between the gradients from backpropagation and the numerical approximation of the gradient (computed using forward propagation).
442 | # - 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.
443 |
444 | # In[ ]:
445 |
446 |
447 |
448 |
--------------------------------------------------------------------------------
/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization/Week 1/Initialization.py:
--------------------------------------------------------------------------------
1 |
2 | # coding: utf-8
3 |
4 | # # Initialization
5 | #
6 | # Welcome to the first assignment of "Improving Deep Neural Networks".
7 | #
8 | # Training your neural network requires specifying an initial value of the weights. A well chosen initialization method will help learning.
9 | #
10 | # If you completed the previous course of this specialization, you probably followed our instructions for weight initialization, and it has worked out so far. But how do you choose the initialization for a new neural network? In this notebook, you will see how different initializations lead to different results.
11 | #
12 | # A well chosen initialization can:
13 | # - Speed up the convergence of gradient descent
14 | # - Increase the odds of gradient descent converging to a lower training (and generalization) error
15 | #
16 | # To get started, run the following cell to load the packages and the planar dataset you will try to classify.
17 |
18 | # In[1]:
19 |
20 | import numpy as np
21 | import matplotlib.pyplot as plt
22 | import sklearn
23 | import sklearn.datasets
24 | from init_utils import sigmoid, relu, compute_loss, forward_propagation, backward_propagation
25 | from init_utils import update_parameters, predict, load_dataset, plot_decision_boundary, predict_dec
26 |
27 | get_ipython().magic('matplotlib inline')
28 | plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
29 | plt.rcParams['image.interpolation'] = 'nearest'
30 | plt.rcParams['image.cmap'] = 'gray'
31 |
32 | # load image dataset: blue/red dots in circles
33 | train_X, train_Y, test_X, test_Y = load_dataset()
34 |
35 |
36 | # You would like a classifier to separate the blue dots from the red dots.
37 |
38 | # ## 1 - Neural Network model
39 |
40 | # You will use a 3-layer neural network (already implemented for you). Here are the initialization methods you will experiment with:
41 | # - *Zeros initialization* -- setting `initialization = "zeros"` in the input argument.
42 | # - *Random initialization* -- setting `initialization = "random"` in the input argument. This initializes the weights to large random values.
43 | # - *He initialization* -- setting `initialization = "he"` in the input argument. This initializes the weights to random values scaled according to a paper by He et al., 2015.
44 | #
45 | # **Instructions**: Please quickly read over the code below, and run it. In the next part you will implement the three initialization methods that this `model()` calls.
46 |
47 | # In[2]:
48 |
49 | def model(X, Y, learning_rate = 0.01, num_iterations = 15000, print_cost = True, initialization = "he"):
50 | """
51 | Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.
52 |
53 | Arguments:
54 | X -- input data, of shape (2, number of examples)
55 | Y -- true "label" vector (containing 0 for red dots; 1 for blue dots), of shape (1, number of examples)
56 | learning_rate -- learning rate for gradient descent
57 | num_iterations -- number of iterations to run gradient descent
58 | print_cost -- if True, print the cost every 1000 iterations
59 | initialization -- flag to choose which initialization to use ("zeros","random" or "he")
60 |
61 | Returns:
62 | parameters -- parameters learnt by the model
63 | """
64 |
65 | grads = {}
66 | costs = [] # to keep track of the loss
67 | m = X.shape[1] # number of examples
68 | layers_dims = [X.shape[0], 10, 5, 1]
69 |
70 | # Initialize parameters dictionary.
71 | if initialization == "zeros":
72 | parameters = initialize_parameters_zeros(layers_dims)
73 | elif initialization == "random":
74 | parameters = initialize_parameters_random(layers_dims)
75 | elif initialization == "he":
76 | parameters = initialize_parameters_he(layers_dims)
77 |
78 | # Loop (gradient descent)
79 |
80 | for i in range(0, num_iterations):
81 |
82 | # Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID.
83 | a3, cache = forward_propagation(X, parameters)
84 |
85 | # Loss
86 | cost = compute_loss(a3, Y)
87 |
88 | # Backward propagation.
89 | grads = backward_propagation(X, Y, cache)
90 |
91 | # Update parameters.
92 | parameters = update_parameters(parameters, grads, learning_rate)
93 |
94 | # Print the loss every 1000 iterations
95 | if print_cost and i % 1000 == 0:
96 | print("Cost after iteration {}: {}".format(i, cost))
97 | costs.append(cost)
98 |
99 | # plot the loss
100 | plt.plot(costs)
101 | plt.ylabel('cost')
102 | plt.xlabel('iterations (per hundreds)')
103 | plt.title("Learning rate =" + str(learning_rate))
104 | plt.show()
105 |
106 | return parameters
107 |
108 |
109 | # ## 2 - Zero initialization
110 | #
111 | # There are two types of parameters to initialize in a neural network:
112 | # - the weight matrices $(W^{[1]}, W^{[2]}, W^{[3]}, ..., W^{[L-1]}, W^{[L]})$
113 | # - the bias vectors $(b^{[1]}, b^{[2]}, b^{[3]}, ..., b^{[L-1]}, b^{[L]})$
114 | #
115 | # **Exercise**: Implement the following function to initialize all parameters to zeros. You'll see later that this does not work well since it fails to "break symmetry", but lets try it anyway and see what happens. Use np.zeros((..,..)) with the correct shapes.
116 |
117 | # In[9]:
118 |
119 | # GRADED FUNCTION: initialize_parameters_zeros
120 |
121 | def initialize_parameters_zeros(layers_dims):
122 | """
123 | Arguments:
124 | layer_dims -- python array (list) containing the size of each layer.
125 |
126 | Returns:
127 | parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
128 | W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
129 | b1 -- bias vector of shape (layers_dims[1], 1)
130 | ...
131 | WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
132 | bL -- bias vector of shape (layers_dims[L], 1)
133 | """
134 |
135 | parameters = {}
136 | L = len(layers_dims) # number of layers in the network
137 |
138 | for l in range(1, L):
139 | ### START CODE HERE ### (≈ 2 lines of code)
140 | parameters['W' + str(l)] = np.zeros((layers_dims[l], layers_dims[l-1]))
141 | parameters['b' + str(l)] = np.zeros((layers_dims[l], 1))
142 | ### END CODE HERE ###
143 | return parameters
144 |
145 |
146 | # In[10]:
147 |
148 | parameters = initialize_parameters_zeros([3,2,1])
149 | print("W1 = " + str(parameters["W1"]))
150 | print("b1 = " + str(parameters["b1"]))
151 | print("W2 = " + str(parameters["W2"]))
152 | print("b2 = " + str(parameters["b2"]))
153 |
154 |
155 | # **Expected Output**:
156 | #
157 | #
158 | #
159 | #
160 | # **W1**
161 | # |
162 | #
163 | # [[ 0. 0. 0.]
164 | # [ 0. 0. 0.]]
165 | # |
166 | #
167 | #
168 | #
169 | # **b1**
170 | # |
171 | #
172 | # [[ 0.]
173 | # [ 0.]]
174 | # |
175 | #
176 | #
177 | #
178 | # **W2**
179 | # |
180 | #
181 | # [[ 0. 0.]]
182 | # |
183 | #
184 | #
185 | #
186 | # **b2**
187 | # |
188 | #
189 | # [[ 0.]]
190 | # |
191 | #
192 | #
193 | #
194 |
195 | # Run the following code to train your model on 15,000 iterations using zeros initialization.
196 |
197 | # In[11]:
198 |
199 | parameters = model(train_X, train_Y, initialization = "zeros")
200 | print ("On the train set:")
201 | predictions_train = predict(train_X, train_Y, parameters)
202 | print ("On the test set:")
203 | predictions_test = predict(test_X, test_Y, parameters)
204 |
205 |
206 | # The performance is really bad, and the cost does not really decrease, and the algorithm performs no better than random guessing. Why? Lets look at the details of the predictions and the decision boundary:
207 |
208 | # In[12]:
209 |
210 | print ("predictions_train = " + str(predictions_train))
211 | print ("predictions_test = " + str(predictions_test))
212 |
213 |
214 | # In[13]:
215 |
216 | plt.title("Model with Zeros initialization")
217 | axes = plt.gca()
218 | axes.set_xlim([-1.5,1.5])
219 | axes.set_ylim([-1.5,1.5])
220 | plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
221 |
222 |
223 | # The model is predicting 0 for every example.
224 | #
225 | # In general, initializing all the weights to zero results in the network failing to break symmetry. This means that every neuron in each layer will learn the same thing, and you might as well be training a neural network with $n^{[l]}=1$ for every layer, and the network is no more powerful than a linear classifier such as logistic regression.
226 |
227 | #
228 | # **What you should remember**:
229 | # - The weights $W^{[l]}$ should be initialized randomly to break symmetry.
230 | # - It is however okay to initialize the biases $b^{[l]}$ to zeros. Symmetry is still broken so long as $W^{[l]}$ is initialized randomly.
231 | #
232 |
233 | # ## 3 - Random initialization
234 | #
235 | # To break symmetry, lets intialize the weights randomly. Following random initialization, each neuron can then proceed to learn a different function of its inputs. In this exercise, you will see what happens if the weights are intialized randomly, but to very large values.
236 | #
237 | # **Exercise**: Implement the following function to initialize your weights to large random values (scaled by \*10) and your biases to zeros. Use `np.random.randn(..,..) * 10` for weights and `np.zeros((.., ..))` for biases. We are using a fixed `np.random.seed(..)` to make sure your "random" weights match ours, so don't worry if running several times your code gives you always the same initial values for the parameters.
238 |
239 | # In[14]:
240 |
241 | # GRADED FUNCTION: initialize_parameters_random
242 |
243 | def initialize_parameters_random(layers_dims):
244 | """
245 | Arguments:
246 | layer_dims -- python array (list) containing the size of each layer.
247 |
248 | Returns:
249 | parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
250 | W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
251 | b1 -- bias vector of shape (layers_dims[1], 1)
252 | ...
253 | WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
254 | bL -- bias vector of shape (layers_dims[L], 1)
255 | """
256 |
257 | np.random.seed(3) # This seed makes sure your "random" numbers will be the as ours
258 | parameters = {}
259 | L = len(layers_dims) # integer representing the number of layers
260 |
261 | for l in range(1, L):
262 | ### START CODE HERE ### (≈ 2 lines of code)
263 | parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l-1]) * 10
264 | parameters['b' + str(l)] = np.zeros((layers_dims[l], 1))
265 | ### END CODE HERE ###
266 |
267 | return parameters
268 |
269 |
270 | # In[15]:
271 |
272 | parameters = initialize_parameters_random([3, 2, 1])
273 | print("W1 = " + str(parameters["W1"]))
274 | print("b1 = " + str(parameters["b1"]))
275 | print("W2 = " + str(parameters["W2"]))
276 | print("b2 = " + str(parameters["b2"]))
277 |
278 |
279 | # **Expected Output**:
280 | #
281 | #
282 | #
283 | #
284 | # **W1**
285 | # |
286 | #
287 | # [[ 17.88628473 4.36509851 0.96497468]
288 | # [-18.63492703 -2.77388203 -3.54758979]]
289 | # |
290 | #
291 | #
292 | #
293 | # **b1**
294 | # |
295 | #
296 | # [[ 0.]
297 | # [ 0.]]
298 | # |
299 | #
300 | #
301 | #
302 | # **W2**
303 | # |
304 | #
305 | # [[-0.82741481 -6.27000677]]
306 | # |
307 | #
308 | #
309 | #
310 | # **b2**
311 | # |
312 | #
313 | # [[ 0.]]
314 | # |
315 | #
316 | #
317 | #
318 |
319 | # Run the following code to train your model on 15,000 iterations using random initialization.
320 |
321 | # In[16]:
322 |
323 | parameters = model(train_X, train_Y, initialization = "random")
324 | print ("On the train set:")
325 | predictions_train = predict(train_X, train_Y, parameters)
326 | print ("On the test set:")
327 | predictions_test = predict(test_X, test_Y, parameters)
328 |
329 |
330 | # If you see "inf" as the cost after the iteration 0, this is because of numerical roundoff; a more numerically sophisticated implementation would fix this. But this isn't worth worrying about for our purposes.
331 | #
332 | # Anyway, it looks like you have broken symmetry, and this gives better results. than before. The model is no longer outputting all 0s.
333 |
334 | # In[17]:
335 |
336 | print (predictions_train)
337 | print (predictions_test)
338 |
339 |
340 | # In[18]:
341 |
342 | plt.title("Model with large random initialization")
343 | axes = plt.gca()
344 | axes.set_xlim([-1.5,1.5])
345 | axes.set_ylim([-1.5,1.5])
346 | plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
347 |
348 |
349 | # **Observations**:
350 | # - The cost starts very high. This is because with large random-valued weights, the last activation (sigmoid) outputs results that are very close to 0 or 1 for some examples, and when it gets that example wrong it incurs a very high loss for that example. Indeed, when $\log(a^{[3]}) = \log(0)$, the loss goes to infinity.
351 | # - Poor initialization can lead to vanishing/exploding gradients, which also slows down the optimization algorithm.
352 | # - If you train this network longer you will see better results, but initializing with overly large random numbers slows down the optimization.
353 | #
354 | #
355 | # **In summary**:
356 | # - Initializing weights to very large random values does not work well.
357 | # - Hopefully intializing with small random values does better. The important question is: how small should be these random values be? Lets find out in the next part!
358 |
359 | # ## 4 - He initialization
360 | #
361 | # Finally, try "He Initialization"; this is named for the first author of He et al., 2015. (If you have heard of "Xavier initialization", this is similar except Xavier initialization uses a scaling factor for the weights $W^{[l]}$ of `sqrt(1./layers_dims[l-1])` where He initialization would use `sqrt(2./layers_dims[l-1])`.)
362 | #
363 | # **Exercise**: Implement the following function to initialize your parameters with He initialization.
364 | #
365 | # **Hint**: This function is similar to the previous `initialize_parameters_random(...)`. The only difference is that instead of multiplying `np.random.randn(..,..)` by 10, you will multiply it by $\sqrt{\frac{2}{\text{dimension of the previous layer}}}$, which is what He initialization recommends for layers with a ReLU activation.
366 |
367 | # In[19]:
368 |
369 | # GRADED FUNCTION: initialize_parameters_he
370 |
371 | def initialize_parameters_he(layers_dims):
372 | """
373 | Arguments:
374 | layer_dims -- python array (list) containing the size of each layer.
375 |
376 | Returns:
377 | parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
378 | W1 -- weight matrix of shape (layers_dims[1], layers_dims[0])
379 | b1 -- bias vector of shape (layers_dims[1], 1)
380 | ...
381 | WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1])
382 | bL -- bias vector of shape (layers_dims[L], 1)
383 | """
384 |
385 | np.random.seed(3)
386 | parameters = {}
387 | L = len(layers_dims) - 1 # integer representing the number of layers
388 |
389 | for l in range(1, L + 1):
390 | ### START CODE HERE ### (≈ 2 lines of code)
391 | parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l-1]) * np.sqrt(2.0 / layers_dims[l-1])
392 | parameters['b' + str(l)] = np.zeros((layers_dims[l], 1))
393 | ### END CODE HERE ###
394 |
395 | return parameters
396 |
397 |
398 | # In[20]:
399 |
400 | parameters = initialize_parameters_he([2, 4, 1])
401 | print("W1 = " + str(parameters["W1"]))
402 | print("b1 = " + str(parameters["b1"]))
403 | print("W2 = " + str(parameters["W2"]))
404 | print("b2 = " + str(parameters["b2"]))
405 |
406 |
407 | # **Expected Output**:
408 | #
409 | #
410 | #
411 | #
412 | # **W1**
413 | # |
414 | #
415 | # [[ 1.78862847 0.43650985]
416 | # [ 0.09649747 -1.8634927 ]
417 | # [-0.2773882 -0.35475898]
418 | # [-0.08274148 -0.62700068]]
419 | # |
420 | #
421 | #
422 | #
423 | # **b1**
424 | # |
425 | #
426 | # [[ 0.]
427 | # [ 0.]
428 | # [ 0.]
429 | # [ 0.]]
430 | # |
431 | #
432 | #
433 | #
434 | # **W2**
435 | # |
436 | #
437 | # [[-0.03098412 -0.33744411 -0.92904268 0.62552248]]
438 | # |
439 | #
440 | #
441 | #
442 | # **b2**
443 | # |
444 | #
445 | # [[ 0.]]
446 | # |
447 | #
448 | #
449 | #
450 |
451 | # Run the following code to train your model on 15,000 iterations using He initialization.
452 |
453 | # In[21]:
454 |
455 | parameters = model(train_X, train_Y, initialization = "he")
456 | print ("On the train set:")
457 | predictions_train = predict(train_X, train_Y, parameters)
458 | print ("On the test set:")
459 | predictions_test = predict(test_X, test_Y, parameters)
460 |
461 |
462 | # In[22]:
463 |
464 | plt.title("Model with He initialization")
465 | axes = plt.gca()
466 | axes.set_xlim([-1.5,1.5])
467 | axes.set_ylim([-1.5,1.5])
468 | plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
469 |
470 |
471 | # **Observations**:
472 | # - The model with He initialization separates the blue and the red dots very well in a small number of iterations.
473 | #
474 |
475 | # ## 5 - Conclusions
476 |
477 | # You have seen three different types of initializations. For the same number of iterations and same hyperparameters the comparison is:
478 | #
479 | #
480 | #
481 | #
482 | # **Model**
483 | # |
484 | #
485 | # **Train accuracy**
486 | # |
487 | #
488 | # **Problem/Comment**
489 | # |
490 | #
491 | #
492 | #
493 | # 3-layer NN with zeros initialization
494 | # |
495 | #
496 | # 50%
497 | # |
498 | #
499 | # fails to break symmetry
500 | # |
501 | #
502 | #
503 | # 3-layer NN with large random initialization
504 | # |
505 | #
506 | # 83%
507 | # |
508 | #
509 | # too large weights
510 | # |
511 | #
512 | #
513 | #
514 | # 3-layer NN with He initialization
515 | # |
516 | #
517 | # 99%
518 | # |
519 | #
520 | # recommended method
521 | # |
522 | #
523 | #
524 |
525 | #
526 | # **What you should remember from this notebook**:
527 | # - Different initializations lead to different results
528 | # - Random initialization is used to break symmetry and make sure different hidden units can learn different things
529 | # - Don't intialize to values that are too large
530 | # - He initialization works well for networks with ReLU activations.
531 |
--------------------------------------------------------------------------------
/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization/Week 1/Practical aspects of deep learning.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization/Week 1/Practical aspects of deep learning.pdf
--------------------------------------------------------------------------------
/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization/Week 1/Regularization.py:
--------------------------------------------------------------------------------
1 |
2 | # coding: utf-8
3 |
4 | # # Regularization
5 | #
6 | # Welcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity that **overfitting can be a serious problem**, if the training dataset is not big enough. Sure it does well on the training set, but the learned network **doesn't generalize to new examples** that it has never seen!
7 | #
8 | # **You will learn to:** Use regularization in your deep learning models.
9 | #
10 | # Let's first import the packages you are going to use.
11 |
12 | # In[1]:
13 |
14 | # import packages
15 | import numpy as np
16 | import matplotlib.pyplot as plt
17 | from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec
18 | from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
19 | import sklearn
20 | import sklearn.datasets
21 | import scipy.io
22 | from testCases import *
23 |
24 | get_ipython().magic('matplotlib inline')
25 | plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
26 | plt.rcParams['image.interpolation'] = 'nearest'
27 | plt.rcParams['image.cmap'] = 'gray'
28 |
29 |
30 | # **Problem Statement**: You have just been hired as an AI expert by the French Football Corporation. They would like you to recommend positions where France's goal keeper should kick the ball so that the French team's players can then hit it with their head.
31 | #
32 | #
33 | # **Figure 1** : **Football field**
The goal keeper kicks the ball in the air, the players of each team are fighting to hit the ball with their head
34 | #
35 | #
36 | # They give you the following 2D dataset from France's past 10 games.
37 |
38 | # In[2]:
39 |
40 | train_X, train_Y, test_X, test_Y = load_2D_dataset()
41 |
42 |
43 | # Each dot corresponds to a position on the football field where a football player has hit the ball with his/her head after the French goal keeper has shot the ball from the left side of the football field.
44 | # - If the dot is blue, it means the French player managed to hit the ball with his/her head
45 | # - If the dot is red, it means the other team's player hit the ball with their head
46 | #
47 | # **Your goal**: Use a deep learning model to find the positions on the field where the goalkeeper should kick the ball.
48 |
49 | # **Analysis of the dataset**: This dataset is a little noisy, but it looks like a diagonal line separating the upper left half (blue) from the lower right half (red) would work well.
50 | #
51 | # You will first try a non-regularized model. Then you'll learn how to regularize it and decide which model you will choose to solve the French Football Corporation's problem.
52 |
53 | # ## 1 - Non-regularized model
54 | #
55 | # You will use the following neural network (already implemented for you below). This model can be used:
56 | # - in *regularization mode* -- by setting the `lambd` input to a non-zero value. We use "`lambd`" instead of "`lambda`" because "`lambda`" is a reserved keyword in Python.
57 | # - in *dropout mode* -- by setting the `keep_prob` to a value less than one
58 | #
59 | # You will first try the model without any regularization. Then, you will implement:
60 | # - *L2 regularization* -- functions: "`compute_cost_with_regularization()`" and "`backward_propagation_with_regularization()`"
61 | # - *Dropout* -- functions: "`forward_propagation_with_dropout()`" and "`backward_propagation_with_dropout()`"
62 | #
63 | # In each part, you will run this model with the correct inputs so that it calls the functions you've implemented. Take a look at the code below to familiarize yourself with the model.
64 |
65 | # In[3]:
66 |
67 | def model(X, Y, learning_rate = 0.3, num_iterations = 30000, print_cost = True, lambd = 0, keep_prob = 1):
68 | """
69 | Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.
70 |
71 | Arguments:
72 | X -- input data, of shape (input size, number of examples)
73 | Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (output size, number of examples)
74 | learning_rate -- learning rate of the optimization
75 | num_iterations -- number of iterations of the optimization loop
76 | print_cost -- If True, print the cost every 10000 iterations
77 | lambd -- regularization hyperparameter, scalar
78 | keep_prob - probability of keeping a neuron active during drop-out, scalar.
79 |
80 | Returns:
81 | parameters -- parameters learned by the model. They can then be used to predict.
82 | """
83 |
84 | grads = {}
85 | costs = [] # to keep track of the cost
86 | m = X.shape[1] # number of examples
87 | layers_dims = [X.shape[0], 20, 3, 1]
88 |
89 | # Initialize parameters dictionary.
90 | parameters = initialize_parameters(layers_dims)
91 |
92 | # Loop (gradient descent)
93 |
94 | for i in range(0, num_iterations):
95 |
96 | # Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID.
97 | if keep_prob == 1:
98 | a3, cache = forward_propagation(X, parameters)
99 | elif keep_prob < 1:
100 | a3, cache = forward_propagation_with_dropout(X, parameters, keep_prob)
101 |
102 | # Cost function
103 | if lambd == 0:
104 | cost = compute_cost(a3, Y)
105 | else:
106 | cost = compute_cost_with_regularization(a3, Y, parameters, lambd)
107 |
108 | # Backward propagation.
109 | assert(lambd==0 or keep_prob==1) # it is possible to use both L2 regularization and dropout,
110 | # but this assignment will only explore one at a time
111 | if lambd == 0 and keep_prob == 1:
112 | grads = backward_propagation(X, Y, cache)
113 | elif lambd != 0:
114 | grads = backward_propagation_with_regularization(X, Y, cache, lambd)
115 | elif keep_prob < 1:
116 | grads = backward_propagation_with_dropout(X, Y, cache, keep_prob)
117 |
118 | # Update parameters.
119 | parameters = update_parameters(parameters, grads, learning_rate)
120 |
121 | # Print the loss every 10000 iterations
122 | if print_cost and i % 10000 == 0:
123 | print("Cost after iteration {}: {}".format(i, cost))
124 | if print_cost and i % 1000 == 0:
125 | costs.append(cost)
126 |
127 | # plot the cost
128 | plt.plot(costs)
129 | plt.ylabel('cost')
130 | plt.xlabel('iterations (x1,000)')
131 | plt.title("Learning rate =" + str(learning_rate))
132 | plt.show()
133 |
134 | return parameters
135 |
136 |
137 | # Let's train the model without any regularization, and observe the accuracy on the train/test sets.
138 |
139 | # In[4]:
140 |
141 | parameters = model(train_X, train_Y)
142 | print ("On the training set:")
143 | predictions_train = predict(train_X, train_Y, parameters)
144 | print ("On the test set:")
145 | predictions_test = predict(test_X, test_Y, parameters)
146 |
147 |
148 | # The train accuracy is 94.8% while the test accuracy is 91.5%. This is the **baseline model** (you will observe the impact of regularization on this model). Run the following code to plot the decision boundary of your model.
149 |
150 | # In[5]:
151 |
152 | plt.title("Model without regularization")
153 | axes = plt.gca()
154 | axes.set_xlim([-0.75,0.40])
155 | axes.set_ylim([-0.75,0.65])
156 | plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
157 |
158 |
159 | # The non-regularized model is obviously overfitting the training set. It is fitting the noisy points! Lets now look at two techniques to reduce overfitting.
160 |
161 | # ## 2 - L2 Regularization
162 | #
163 | # The standard way to avoid overfitting is called **L2 regularization**. It consists of appropriately modifying your cost function, from:
164 | # $$J = -\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{[L](i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right) \large{)} \tag{1}$$
165 | # To:
166 | # $$J_{regularized} = \small \underbrace{-\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{[L](i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right) \large{)} }_\text{cross-entropy cost} + \underbrace{\frac{1}{m} \frac{\lambda}{2} \sum\limits_l\sum\limits_k\sum\limits_j W_{k,j}^{[l]2} }_\text{L2 regularization cost} \tag{2}$$
167 | #
168 | # Let's modify your cost and observe the consequences.
169 | #
170 | # **Exercise**: Implement `compute_cost_with_regularization()` which computes the cost given by formula (2). To calculate $\sum\limits_k\sum\limits_j W_{k,j}^{[l]2}$ , use :
171 | # ```python
172 | # np.sum(np.square(Wl))
173 | # ```
174 | # Note that you have to do this for $W^{[1]}$, $W^{[2]}$ and $W^{[3]}$, then sum the three terms and multiply by $ \frac{1}{m} \frac{\lambda}{2} $.
175 |
176 | # In[6]:
177 |
178 | # GRADED FUNCTION: compute_cost_with_regularization
179 |
180 | def compute_cost_with_regularization(A3, Y, parameters, lambd):
181 | """
182 | Implement the cost function with L2 regularization. See formula (2) above.
183 |
184 | Arguments:
185 | A3 -- post-activation, output of forward propagation, of shape (output size, number of examples)
186 | Y -- "true" labels vector, of shape (output size, number of examples)
187 | parameters -- python dictionary containing parameters of the model
188 |
189 | Returns:
190 | cost - value of the regularized loss function (formula (2))
191 | """
192 | m = Y.shape[1]
193 | W1 = parameters["W1"]
194 | W2 = parameters["W2"]
195 | W3 = parameters["W3"]
196 |
197 | cross_entropy_cost = compute_cost(A3, Y) # This gives you the cross-entropy part of the cost
198 |
199 | ### START CODE HERE ### (approx. 1 line)
200 | L2_regularization_cost = lambd / (2 * m) * (np.sum(np.square(W1)) + np.sum(np.square(W2)) + np.sum(np.square(W3)))
201 | ### END CODER HERE ###
202 |
203 | cost = cross_entropy_cost + L2_regularization_cost
204 |
205 | return cost
206 |
207 |
208 | # In[7]:
209 |
210 | A3, Y_assess, parameters = compute_cost_with_regularization_test_case()
211 |
212 | print("cost = " + str(compute_cost_with_regularization(A3, Y_assess, parameters, lambd = 0.1)))
213 |
214 |
215 | # **Expected Output**:
216 | #
217 | #
218 | #
219 | #
220 | # **cost**
221 | # |
222 | #
223 | # 1.78648594516
224 | # |
225 | #
226 | #
227 | #
228 | #
229 |
230 | # Of course, because you changed the cost, you have to change backward propagation as well! All the gradients have to be computed with respect to this new cost.
231 | #
232 | # **Exercise**: Implement the changes needed in backward propagation to take into account regularization. The changes only concern dW1, dW2 and dW3. For each, you have to add the regularization term's gradient ($\frac{d}{dW} ( \frac{1}{2}\frac{\lambda}{m} W^2) = \frac{\lambda}{m} W$).
233 |
234 | # In[8]:
235 |
236 | # GRADED FUNCTION: backward_propagation_with_regularization
237 |
238 | def backward_propagation_with_regularization(X, Y, cache, lambd):
239 | """
240 | Implements the backward propagation of our baseline model to which we added an L2 regularization.
241 |
242 | Arguments:
243 | X -- input dataset, of shape (input size, number of examples)
244 | Y -- "true" labels vector, of shape (output size, number of examples)
245 | cache -- cache output from forward_propagation()
246 | lambd -- regularization hyperparameter, scalar
247 |
248 | Returns:
249 | gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables
250 | """
251 |
252 | m = X.shape[1]
253 | (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache
254 |
255 | dZ3 = A3 - Y
256 |
257 | ### START CODE HERE ### (approx. 1 line)
258 | dW3 = 1./m * np.dot(dZ3, A2.T) + lambd / m * W3
259 | ### END CODE HERE ###
260 | db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)
261 |
262 | dA2 = np.dot(W3.T, dZ3)
263 | dZ2 = np.multiply(dA2, np.int64(A2 > 0))
264 | ### START CODE HERE ### (approx. 1 line)
265 | dW2 = 1./m * np.dot(dZ2, A1.T) + lambd / m * W2
266 | ### END CODE HERE ###
267 | db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)
268 |
269 | dA1 = np.dot(W2.T, dZ2)
270 | dZ1 = np.multiply(dA1, np.int64(A1 > 0))
271 | ### START CODE HERE ### (approx. 1 line)
272 | dW1 = 1./m * np.dot(dZ1, X.T) + lambd / m * W1
273 | ### END CODE HERE ###
274 | db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True)
275 |
276 | gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,"dA2": dA2,
277 | "dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1,
278 | "dZ1": dZ1, "dW1": dW1, "db1": db1}
279 |
280 | return gradients
281 |
282 |
283 | # In[9]:
284 |
285 | X_assess, Y_assess, cache = backward_propagation_with_regularization_test_case()
286 |
287 | grads = backward_propagation_with_regularization(X_assess, Y_assess, cache, lambd = 0.7)
288 | print ("dW1 = "+ str(grads["dW1"]))
289 | print ("dW2 = "+ str(grads["dW2"]))
290 | print ("dW3 = "+ str(grads["dW3"]))
291 |
292 |
293 | # **Expected Output**:
294 | #
295 | #
296 | #
297 | #
298 | # **dW1**
299 | # |
300 | #
301 | # [[-0.25604646 0.12298827 -0.28297129]
302 | # [-0.17706303 0.34536094 -0.4410571 ]]
303 | # |
304 | #
305 | #
306 | #
307 | # **dW2**
308 | # |
309 | #
310 | # [[ 0.79276486 0.85133918]
311 | # [-0.0957219 -0.01720463]
312 | # [-0.13100772 -0.03750433]]
313 | # |
314 | #
315 | #
316 | #
317 | # **dW3**
318 | # |
319 | #
320 | # [[-1.77691347 -0.11832879 -0.09397446]]
321 | # |
322 | #
323 | #
324 |
325 | # Let's now run the model with L2 regularization $(\lambda = 0.7)$. The `model()` function will call:
326 | # - `compute_cost_with_regularization` instead of `compute_cost`
327 | # - `backward_propagation_with_regularization` instead of `backward_propagation`
328 |
329 | # In[10]:
330 |
331 | parameters = model(train_X, train_Y, lambd = 0.7)
332 | print ("On the train set:")
333 | predictions_train = predict(train_X, train_Y, parameters)
334 | print ("On the test set:")
335 | predictions_test = predict(test_X, test_Y, parameters)
336 |
337 |
338 | # Congrats, the test set accuracy increased to 93%. You have saved the French football team!
339 | #
340 | # You are not overfitting the training data anymore. Let's plot the decision boundary.
341 |
342 | # In[11]:
343 |
344 | plt.title("Model with L2-regularization")
345 | axes = plt.gca()
346 | axes.set_xlim([-0.75,0.40])
347 | axes.set_ylim([-0.75,0.65])
348 | plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
349 |
350 |
351 | # **Observations**:
352 | # - The value of $\lambda$ is a hyperparameter that you can tune using a dev set.
353 | # - L2 regularization makes your decision boundary smoother. If $\lambda$ is too large, it is also possible to "oversmooth", resulting in a model with high bias.
354 | #
355 | # **What is L2-regularization actually doing?**:
356 | #
357 | # L2-regularization relies on the assumption that a model with small weights is simpler than a model with large weights. Thus, by penalizing the square values of the weights in the cost function you drive all the weights to smaller values. It becomes too costly for the cost to have large weights! This leads to a smoother model in which the output changes more slowly as the input changes.
358 | #
359 | #
360 | # **What you should remember** -- the implications of L2-regularization on:
361 | # - The cost computation:
362 | # - A regularization term is added to the cost
363 | # - The backpropagation function:
364 | # - There are extra terms in the gradients with respect to weight matrices
365 | # - Weights end up smaller ("weight decay"):
366 | # - Weights are pushed to smaller values.
367 |
368 | # ## 3 - Dropout
369 | #
370 | # Finally, **dropout** is a widely used regularization technique that is specific to deep learning.
371 | # **It randomly shuts down some neurons in each iteration.** Watch these two videos to see what this means!
372 | #
373 | #
380 | #
381 | #
382 | #
383 | #
385 | #
386 | #
387 | # Figure 2 : Drop-out on the second hidden layer.
At each iteration, you shut down (= set to zero) each neuron of a layer with probability $1 - keep\_prob$ or keep it with probability $keep\_prob$ (50% here). The dropped neurons don't contribute to the training in both the forward and backward propagations of the iteration.
388 | #
389 | #
390 | #
392 | #
393 | #
394 | # Figure 3 : Drop-out on the first and third hidden layers.
$1^{st}$ layer: we shut down on average 40% of the neurons. $3^{rd}$ layer: we shut down on average 20% of the neurons.
395 | #
396 | #
397 | # When you shut some neurons down, you actually modify your model. The idea behind drop-out is that at each iteration, you train a different model that uses only a subset of your neurons. With dropout, your neurons thus become less sensitive to the activation of one other specific neuron, because that other neuron might be shut down at any time.
398 | #
399 | # ### 3.1 - Forward propagation with dropout
400 | #
401 | # **Exercise**: Implement the forward propagation with dropout. You are using a 3 layer neural network, and will add dropout to the first and second hidden layers. We will not apply dropout to the input layer or output layer.
402 | #
403 | # **Instructions**:
404 | # You would like to shut down some neurons in the first and second layers. To do that, you are going to carry out 4 Steps:
405 | # 1. In lecture, we dicussed creating a variable $d^{[1]}$ with the same shape as $a^{[1]}$ using `np.random.rand()` to randomly get numbers between 0 and 1. Here, you will use a vectorized implementation, so create a random matrix $D^{[1]} = [d^{[1](1)} d^{[1](2)} ... d^{[1](m)}] $ of the same dimension as $A^{[1]}$.
406 | # 2. Set each entry of $D^{[1]}$ to be 0 with probability (`1-keep_prob`) or 1 with probability (`keep_prob`), by thresholding values in $D^{[1]}$ appropriately. Hint: to set all the entries of a matrix X to 0 (if entry is less than 0.5) or 1 (if entry is more than 0.5) you would do: `X = (X < 0.5)`. Note that 0 and 1 are respectively equivalent to False and True.
407 | # 3. Set $A^{[1]}$ to $A^{[1]} * D^{[1]}$. (You are shutting down some neurons). You can think of $D^{[1]}$ as a mask, so that when it is multiplied with another matrix, it shuts down some of the values.
408 | # 4. Divide $A^{[1]}$ by `keep_prob`. By doing this you are assuring that the result of the cost will still have the same expected value as without drop-out. (This technique is also called inverted dropout.)
409 |
410 | # In[16]:
411 |
412 | # GRADED FUNCTION: forward_propagation_with_dropout
413 |
414 | def forward_propagation_with_dropout(X, parameters, keep_prob = 0.5):
415 | """
416 | Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.
417 |
418 | Arguments:
419 | X -- input dataset, of shape (2, number of examples)
420 | parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":
421 | W1 -- weight matrix of shape (20, 2)
422 | b1 -- bias vector of shape (20, 1)
423 | W2 -- weight matrix of shape (3, 20)
424 | b2 -- bias vector of shape (3, 1)
425 | W3 -- weight matrix of shape (1, 3)
426 | b3 -- bias vector of shape (1, 1)
427 | keep_prob - probability of keeping a neuron active during drop-out, scalar
428 |
429 | Returns:
430 | A3 -- last activation value, output of the forward propagation, of shape (1,1)
431 | cache -- tuple, information stored for computing the backward propagation
432 | """
433 |
434 | np.random.seed(1)
435 |
436 | # retrieve parameters
437 | W1 = parameters["W1"]
438 | b1 = parameters["b1"]
439 | W2 = parameters["W2"]
440 | b2 = parameters["b2"]
441 | W3 = parameters["W3"]
442 | b3 = parameters["b3"]
443 |
444 | # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID
445 | Z1 = np.dot(W1, X) + b1
446 | A1 = relu(Z1)
447 | ### START CODE HERE ### (approx. 4 lines) # Steps 1-4 below correspond to the Steps 1-4 described above.
448 | D1 = np.random.rand(A1.shape[0], A1.shape[1]) # Step 1: initialize matrix D1 = np.random.rand(..., ...)
449 | D1 = D1 < keep_prob # Step 2: convert entries of D1 to 0 or 1 (using keep_prob as the threshold)
450 | A1 = A1 * D1 # Step 3: shut down some neurons of A1
451 | A1 = A1 / keep_prob # Step 4: scale the value of neurons that haven't been shut down
452 | ### END CODE HERE ###
453 | Z2 = np.dot(W2, A1) + b2
454 | A2 = relu(Z2)
455 | ### START CODE HERE ### (approx. 4 lines)
456 | D2 = np.random.rand(A2.shape[0], A2.shape[1]) # Step 1: initialize matrix D2 = np.random.rand(..., ...)
457 | D2 = D2 < keep_prob # Step 2: convert entries of D2 to 0 or 1 (using keep_prob as the threshold)
458 | A2 = A2 * D2 # Step 3: shut down some neurons of A2
459 | A2 = A2 / keep_prob # Step 4: scale the value of neurons that haven't been shut down
460 | ### END CODE HERE ###
461 | Z3 = np.dot(W3, A2) + b3
462 | A3 = sigmoid(Z3)
463 |
464 | cache = (Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3)
465 |
466 | return A3, cache
467 |
468 |
469 | # In[17]:
470 |
471 | X_assess, parameters = forward_propagation_with_dropout_test_case()
472 |
473 | A3, cache = forward_propagation_with_dropout(X_assess, parameters, keep_prob = 0.7)
474 | print ("A3 = " + str(A3))
475 |
476 |
477 | # **Expected Output**:
478 | #
479 | #
480 | #
481 | #
482 | # **A3**
483 | # |
484 | #
485 | # [[ 0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]]
486 | # |
487 | #
488 | #
489 | #
490 | #
491 |
492 | # ### 3.2 - Backward propagation with dropout
493 | #
494 | # **Exercise**: Implement the backward propagation with dropout. As before, you are training a 3 layer network. Add dropout to the first and second hidden layers, using the masks $D^{[1]}$ and $D^{[2]}$ stored in the cache.
495 | #
496 | # **Instruction**:
497 | # Backpropagation with dropout is actually quite easy. You will have to carry out 2 Steps:
498 | # 1. You had previously shut down some neurons during forward propagation, by applying a mask $D^{[1]}$ to `A1`. In backpropagation, you will have to shut down the same neurons, by reapplying the same mask $D^{[1]}$ to `dA1`.
499 | # 2. During forward propagation, you had divided `A1` by `keep_prob`. In backpropagation, you'll therefore have to divide `dA1` by `keep_prob` again (the calculus interpretation is that if $A^{[1]}$ is scaled by `keep_prob`, then its derivative $dA^{[1]}$ is also scaled by the same `keep_prob`).
500 | #
501 |
502 | # In[18]:
503 |
504 | # GRADED FUNCTION: backward_propagation_with_dropout
505 |
506 | def backward_propagation_with_dropout(X, Y, cache, keep_prob):
507 | """
508 | Implements the backward propagation of our baseline model to which we added dropout.
509 |
510 | Arguments:
511 | X -- input dataset, of shape (2, number of examples)
512 | Y -- "true" labels vector, of shape (output size, number of examples)
513 | cache -- cache output from forward_propagation_with_dropout()
514 | keep_prob - probability of keeping a neuron active during drop-out, scalar
515 |
516 | Returns:
517 | gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables
518 | """
519 |
520 | m = X.shape[1]
521 | (Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3) = cache
522 |
523 | dZ3 = A3 - Y
524 | dW3 = 1./m * np.dot(dZ3, A2.T)
525 | db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)
526 | dA2 = np.dot(W3.T, dZ3)
527 | ### START CODE HERE ### (≈ 2 lines of code)
528 | dA2 = dA2 * D2 # Step 1: Apply mask D2 to shut down the same neurons as during the forward propagation
529 | dA2 = dA2 / keep_prob # Step 2: Scale the value of neurons that haven't been shut down
530 | ### END CODE HERE ###
531 | dZ2 = np.multiply(dA2, np.int64(A2 > 0))
532 | dW2 = 1./m * np.dot(dZ2, A1.T)
533 | db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)
534 |
535 | dA1 = np.dot(W2.T, dZ2)
536 | ### START CODE HERE ### (≈ 2 lines of code)
537 | dA1 = dA1 * D1 # Step 1: Apply mask D1 to shut down the same neurons as during the forward propagation
538 | dA1 = dA1 / keep_prob # Step 2: Scale the value of neurons that haven't been shut down
539 | ### END CODE HERE ###
540 | dZ1 = np.multiply(dA1, np.int64(A1 > 0))
541 | dW1 = 1./m * np.dot(dZ1, X.T)
542 | db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True)
543 |
544 | gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,"dA2": dA2,
545 | "dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1,
546 | "dZ1": dZ1, "dW1": dW1, "db1": db1}
547 |
548 | return gradients
549 |
550 |
551 | # In[19]:
552 |
553 | X_assess, Y_assess, cache = backward_propagation_with_dropout_test_case()
554 |
555 | gradients = backward_propagation_with_dropout(X_assess, Y_assess, cache, keep_prob = 0.8)
556 |
557 | print ("dA1 = " + str(gradients["dA1"]))
558 | print ("dA2 = " + str(gradients["dA2"]))
559 |
560 |
561 | # **Expected Output**:
562 | #
563 | #
564 | #
565 | #
566 | # **dA1**
567 | # |
568 | #
569 | # [[ 0.36544439 0. -0.00188233 0. -0.17408748]
570 | # [ 0.65515713 0. -0.00337459 0. -0. ]]
571 | # |
572 | #
573 | #
574 | #
575 | #
576 | # **dA2**
577 | # |
578 | #
579 | # [[ 0.58180856 0. -0.00299679 0. -0.27715731]
580 | # [ 0. 0.53159854 -0. 0.53159854 -0.34089673]
581 | # [ 0. 0. -0.00292733 0. -0. ]]
582 | # |
583 | #
584 | #
585 | #
586 |
587 | # Let's now run the model with dropout (`keep_prob = 0.86`). It means at every iteration you shut down each neurons of layer 1 and 2 with 24% probability. The function `model()` will now call:
588 | # - `forward_propagation_with_dropout` instead of `forward_propagation`.
589 | # - `backward_propagation_with_dropout` instead of `backward_propagation`.
590 |
591 | # In[20]:
592 |
593 | parameters = model(train_X, train_Y, keep_prob = 0.86, learning_rate = 0.3)
594 |
595 | print ("On the train set:")
596 | predictions_train = predict(train_X, train_Y, parameters)
597 | print ("On the test set:")
598 | predictions_test = predict(test_X, test_Y, parameters)
599 |
600 |
601 | # Dropout works great! The test accuracy has increased again (to 95%)! Your model is not overfitting the training set and does a great job on the test set. The French football team will be forever grateful to you!
602 | #
603 | # Run the code below to plot the decision boundary.
604 |
605 | # In[21]:
606 |
607 | plt.title("Model with dropout")
608 | axes = plt.gca()
609 | axes.set_xlim([-0.75,0.40])
610 | axes.set_ylim([-0.75,0.65])
611 | plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y)
612 |
613 |
614 | # **Note**:
615 | # - A **common mistake** when using dropout is to use it both in training and testing. You should use dropout (randomly eliminate nodes) only in training.
616 | # - Deep learning frameworks like [tensorflow](https://www.tensorflow.org/api_docs/python/tf/nn/dropout), [PaddlePaddle](http://doc.paddlepaddle.org/release_doc/0.9.0/doc/ui/api/trainer_config_helpers/attrs.html), [keras](https://keras.io/layers/core/#dropout) or [caffe](http://caffe.berkeleyvision.org/tutorial/layers/dropout.html) come with a dropout layer implementation. Don't stress - you will soon learn some of these frameworks.
617 | #
618 | #
619 | # **What you should remember about dropout:**
620 | # - Dropout is a regularization technique.
621 | # - You only use dropout during training. Don't use dropout (randomly eliminate nodes) during test time.
622 | # - Apply dropout both during forward and backward propagation.
623 | # - During training time, divide each dropout layer by keep_prob to keep the same expected value for the activations. For example, if keep_prob is 0.5, then we will on average shut down half the nodes, so the output will be scaled by 0.5 since only the remaining half are contributing to the solution. Dividing by 0.5 is equivalent to multiplying by 2. Hence, the output now has the same expected value. You can check that this works even when keep_prob is other values than 0.5.
624 |
625 | # ## 4 - Conclusions
626 |
627 | # **Here are the results of our three models**:
628 | #
629 | #
630 | #
631 | #
632 | # **model**
633 | # |
634 | #
635 | # **train accuracy**
636 | # |
637 | #
638 | # **test accuracy**
639 | # |
640 | #
641 | #
642 | #
643 | # 3-layer NN without regularization
644 | # |
645 | #
646 | # 95%
647 | # |
648 | #
649 | # 91.5%
650 | # |
651 | #
652 | #
653 | # 3-layer NN with L2-regularization
654 | # |
655 | #
656 | # 94%
657 | # |
658 | #
659 | # 93%
660 | # |
661 | #
662 | #
663 | #
664 | # 3-layer NN with dropout
665 | # |
666 | #
667 | # 93%
668 | # |
669 | #
670 | # 95%
671 | # |
672 | #
673 | #
674 |
675 | # Note that regularization hurts training set performance! This is because it limits the ability of the network to overfit to the training set. But since it ultimately gives better test accuracy, it is helping your system.
676 |
677 | # Congratulations for finishing this assignment! And also for revolutionizing French football. :-)
678 |
679 | #
680 | # **What we want you to remember from this notebook**:
681 | # - Regularization will help you reduce overfitting.
682 | # - Regularization will drive your weights to lower values.
683 | # - L2 regularization and Dropout are two very effective regularization techniques.
684 |
--------------------------------------------------------------------------------
/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization/Week 2/Optimisation algorithms.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization/Week 2/Optimisation algorithms.pdf
--------------------------------------------------------------------------------
/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization/Week 3/Hyperparameter tuning, Batch Normalization, Programming Frameworks.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Improving Deep Neural Networks_Hyperparameter tuning_ Regularization/Week 3/Hyperparameter tuning, Batch Normalization, Programming Frameworks.pdf
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 1/Introduction to Deep Learning.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 1/Introduction to Deep Learning.pdf
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/datasets/test_catvnoncat.h5:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/datasets/test_catvnoncat.h5
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/datasets/train_catvnoncat.h5:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/datasets/train_catvnoncat.h5
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/LogReg_kiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/LogReg_kiank.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/cat_in_iran.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/cat_in_iran.jpg
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/gargouille.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/gargouille.jpg
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/image1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/image1.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/image2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/image2.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/la_defense.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/la_defense.jpg
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/my_image.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/my_image.jpg
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/my_image2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Logistic Regression as a Neural Network/images/my_image2.jpg
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Neural Network Basics.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Neural Network Basics.pdf
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Python Basics with Numpy/images/Sigmoid.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Python Basics with Numpy/images/Sigmoid.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Python Basics with Numpy/images/image2vector.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Python Basics with Numpy/images/image2vector.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Python Basics with Numpy/images/image2vector_kiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 2/Python Basics with Numpy/images/image2vector_kiank.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/Quiz.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 2,
6 | "metadata": {
7 | "collapsed": true
8 | },
9 | "outputs": [],
10 | "source": [
11 | "import numpy as np"
12 | ]
13 | },
14 | {
15 | "cell_type": "code",
16 | "execution_count": 3,
17 | "metadata": {
18 | "collapsed": false
19 | },
20 | "outputs": [
21 | {
22 | "name": "stdout",
23 | "output_type": "stream",
24 | "text": [
25 | "(2, 3)\n"
26 | ]
27 | }
28 | ],
29 | "source": [
30 | "a = np.random.randn(2, 3) # a.shape = (2, 3)\n",
31 | "b = np.random.randn(2, 1) # b.shape = (2, 1)\n",
32 | "c = a + b\n",
33 | "print(c.shape)"
34 | ]
35 | },
36 | {
37 | "cell_type": "code",
38 | "execution_count": 4,
39 | "metadata": {
40 | "collapsed": false
41 | },
42 | "outputs": [
43 | {
44 | "ename": "ValueError",
45 | "evalue": "operands could not be broadcast together with shapes (4,3) (3,2) ",
46 | "output_type": "error",
47 | "traceback": [
48 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
49 | "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
50 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0ma\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrandom\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrandn\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m3\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# a.shape = (4, 3)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mb\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrandom\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrandn\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# b.shape = (3, 2)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mc\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0ma\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mc\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mshape\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
51 | "\u001b[0;31mValueError\u001b[0m: operands could not be broadcast together with shapes (4,3) (3,2) "
52 | ]
53 | }
54 | ],
55 | "source": [
56 | "a = np.random.randn(4, 3) # a.shape = (4, 3)\n",
57 | "b = np.random.randn(3, 2) # b.shape = (3, 2)\n",
58 | "c = a*b\n",
59 | "print(c.shape)"
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": 5,
65 | "metadata": {
66 | "collapsed": false
67 | },
68 | "outputs": [
69 | {
70 | "name": "stdout",
71 | "output_type": "stream",
72 | "text": [
73 | "(12288, 45)\n"
74 | ]
75 | }
76 | ],
77 | "source": [
78 | "a = np.random.randn(12288, 150) # a.shape = (12288, 150)\n",
79 | "b = np.random.randn(150, 45) # b.shape = (150, 45)\n",
80 | "c = np.dot(a,b)\n",
81 | "print(c.shape)"
82 | ]
83 | },
84 | {
85 | "cell_type": "code",
86 | "execution_count": 3,
87 | "metadata": {
88 | "collapsed": false
89 | },
90 | "outputs": [
91 | {
92 | "name": "stdout",
93 | "output_type": "stream",
94 | "text": [
95 | "(4, 1)\n"
96 | ]
97 | }
98 | ],
99 | "source": [
100 | "A = np.random.randn(4,3)\n",
101 | "B = np.sum(A, axis = 1, keepdims = True)\n",
102 | "print(B.shape)"
103 | ]
104 | },
105 | {
106 | "cell_type": "code",
107 | "execution_count": null,
108 | "metadata": {
109 | "collapsed": true
110 | },
111 | "outputs": [],
112 | "source": []
113 | }
114 | ],
115 | "metadata": {
116 | "anaconda-cloud": {},
117 | "kernelspec": {
118 | "display_name": "Python [conda root]",
119 | "language": "python",
120 | "name": "conda-root-py"
121 | },
122 | "language_info": {
123 | "codemirror_mode": {
124 | "name": "ipython",
125 | "version": 3
126 | },
127 | "file_extension": ".py",
128 | "mimetype": "text/x-python",
129 | "name": "python",
130 | "nbconvert_exporter": "python",
131 | "pygments_lexer": "ipython3",
132 | "version": "3.5.2"
133 | }
134 | },
135 | "nbformat": 4,
136 | "nbformat_minor": 2
137 | }
138 |
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 2/README.md:
--------------------------------------------------------------------------------
1 | # Week 2 Exercises
2 |
3 | Exercises completed during the second week of the course:
4 | * Python Basics with numpy (optional)
5 | * Logistic Regression with a Neural Network mindset
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 3/Planar data classification with one hidden layer/README.md:
--------------------------------------------------------------------------------
1 | # Week 3 Exercises
2 |
3 | Exercises completed during the third week of the course:
4 | * Planar data classification with one hidden layer
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 3/Planar data classification with one hidden layer/images/classification_kiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 3/Planar data classification with one hidden layer/images/classification_kiank.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 3/Planar data classification with one hidden layer/images/grad_summary.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 3/Planar data classification with one hidden layer/images/grad_summary.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 3/Planar data classification with one hidden layer/images/sgd.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 3/Planar data classification with one hidden layer/images/sgd.gif
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 3/Planar data classification with one hidden layer/images/sgd_bad.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 3/Planar data classification with one hidden layer/images/sgd_bad.gif
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 3/Planar data classification with one hidden layer/planar_utils.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 | import numpy as np
3 | import sklearn
4 | import sklearn.datasets
5 | import sklearn.linear_model
6 |
7 | def plot_decision_boundary(model, X, y):
8 | # Set min and max values and give it some padding
9 | x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1
10 | y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1
11 | h = 0.01
12 | # Generate a grid of points with distance h between them
13 | xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
14 | # Predict the function value for the whole grid
15 | Z = model(np.c_[xx.ravel(), yy.ravel()])
16 | Z = Z.reshape(xx.shape)
17 | # Plot the contour and training examples
18 | plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
19 | plt.ylabel('x2')
20 | plt.xlabel('x1')
21 | plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)
22 |
23 |
24 | def sigmoid(x):
25 | """
26 | Compute the sigmoid of x
27 |
28 | Arguments:
29 | x -- A scalar or numpy array of any size.
30 |
31 | Return:
32 | s -- sigmoid(x)
33 | """
34 | s = 1/(1+np.exp(-x))
35 | return s
36 |
37 | def load_planar_dataset():
38 | np.random.seed(1)
39 | m = 400 # number of examples
40 | N = int(m/2) # number of points per class
41 | D = 2 # dimensionality
42 | X = np.zeros((m,D)) # data matrix where each row is a single example
43 | Y = np.zeros((m,1), dtype='uint8') # labels vector (0 for red, 1 for blue)
44 | a = 4 # maximum ray of the flower
45 |
46 | for j in range(2):
47 | ix = range(N*j,N*(j+1))
48 | t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # theta
49 | r = a*np.sin(4*t) + np.random.randn(N)*0.2 # radius
50 | X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
51 | Y[ix] = j
52 |
53 | X = X.T
54 | Y = Y.T
55 |
56 | return X, Y
57 |
58 | def load_extra_datasets():
59 | N = 200
60 | noisy_circles = sklearn.datasets.make_circles(n_samples=N, factor=.5, noise=.3)
61 | noisy_moons = sklearn.datasets.make_moons(n_samples=N, noise=.2)
62 | blobs = sklearn.datasets.make_blobs(n_samples=N, random_state=5, n_features=2, centers=6)
63 | gaussian_quantiles = sklearn.datasets.make_gaussian_quantiles(mean=None, cov=0.5, n_samples=N, n_features=2, n_classes=2, shuffle=True, random_state=None)
64 | no_structure = np.random.rand(N, 2), np.random.rand(N, 2)
65 |
66 | return noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 3/Planar data classification with one hidden layer/testCases.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def layer_sizes_test_case():
4 | np.random.seed(1)
5 | X_assess = np.random.randn(5, 3)
6 | Y_assess = np.random.randn(2, 3)
7 | return X_assess, Y_assess
8 |
9 | def initialize_parameters_test_case():
10 | n_x, n_h, n_y = 2, 4, 1
11 | return n_x, n_h, n_y
12 |
13 | def forward_propagation_test_case():
14 | np.random.seed(1)
15 | X_assess = np.random.randn(2, 3)
16 |
17 | parameters = {'W1': np.array([[-0.00416758, -0.00056267],
18 | [-0.02136196, 0.01640271],
19 | [-0.01793436, -0.00841747],
20 | [ 0.00502881, -0.01245288]]),
21 | 'W2': np.array([[-0.01057952, -0.00909008, 0.00551454, 0.02292208]]),
22 | 'b1': np.array([[ 0.],
23 | [ 0.],
24 | [ 0.],
25 | [ 0.]]),
26 | 'b2': np.array([[ 0.]])}
27 |
28 | return X_assess, parameters
29 |
30 | def compute_cost_test_case():
31 | np.random.seed(1)
32 | Y_assess = np.random.randn(1, 3)
33 | parameters = {'W1': np.array([[-0.00416758, -0.00056267],
34 | [-0.02136196, 0.01640271],
35 | [-0.01793436, -0.00841747],
36 | [ 0.00502881, -0.01245288]]),
37 | 'W2': np.array([[-0.01057952, -0.00909008, 0.00551454, 0.02292208]]),
38 | 'b1': np.array([[ 0.],
39 | [ 0.],
40 | [ 0.],
41 | [ 0.]]),
42 | 'b2': np.array([[ 0.]])}
43 |
44 | a2 = (np.array([[ 0.5002307 , 0.49985831, 0.50023963]]))
45 |
46 | return a2, Y_assess, parameters
47 |
48 | def backward_propagation_test_case():
49 | np.random.seed(1)
50 | X_assess = np.random.randn(2, 3)
51 | Y_assess = np.random.randn(1, 3)
52 | parameters = {'W1': np.array([[-0.00416758, -0.00056267],
53 | [-0.02136196, 0.01640271],
54 | [-0.01793436, -0.00841747],
55 | [ 0.00502881, -0.01245288]]),
56 | 'W2': np.array([[-0.01057952, -0.00909008, 0.00551454, 0.02292208]]),
57 | 'b1': np.array([[ 0.],
58 | [ 0.],
59 | [ 0.],
60 | [ 0.]]),
61 | 'b2': np.array([[ 0.]])}
62 |
63 | cache = {'A1': np.array([[-0.00616578, 0.0020626 , 0.00349619],
64 | [-0.05225116, 0.02725659, -0.02646251],
65 | [-0.02009721, 0.0036869 , 0.02883756],
66 | [ 0.02152675, -0.01385234, 0.02599885]]),
67 | 'A2': np.array([[ 0.5002307 , 0.49985831, 0.50023963]]),
68 | 'Z1': np.array([[-0.00616586, 0.0020626 , 0.0034962 ],
69 | [-0.05229879, 0.02726335, -0.02646869],
70 | [-0.02009991, 0.00368692, 0.02884556],
71 | [ 0.02153007, -0.01385322, 0.02600471]]),
72 | 'Z2': np.array([[ 0.00092281, -0.00056678, 0.00095853]])}
73 | return parameters, cache, X_assess, Y_assess
74 |
75 | def update_parameters_test_case():
76 | parameters = {'W1': np.array([[-0.00615039, 0.0169021 ],
77 | [-0.02311792, 0.03137121],
78 | [-0.0169217 , -0.01752545],
79 | [ 0.00935436, -0.05018221]]),
80 | 'W2': np.array([[-0.0104319 , -0.04019007, 0.01607211, 0.04440255]]),
81 | 'b1': np.array([[ -8.97523455e-07],
82 | [ 8.15562092e-06],
83 | [ 6.04810633e-07],
84 | [ -2.54560700e-06]]),
85 | 'b2': np.array([[ 9.14954378e-05]])}
86 |
87 | grads = {'dW1': np.array([[ 0.00023322, -0.00205423],
88 | [ 0.00082222, -0.00700776],
89 | [-0.00031831, 0.0028636 ],
90 | [-0.00092857, 0.00809933]]),
91 | 'dW2': np.array([[ -1.75740039e-05, 3.70231337e-03, -1.25683095e-03,
92 | -2.55715317e-03]]),
93 | 'db1': np.array([[ 1.05570087e-07],
94 | [ -3.81814487e-06],
95 | [ -1.90155145e-07],
96 | [ 5.46467802e-07]]),
97 | 'db2': np.array([[ -1.08923140e-05]])}
98 | return parameters, grads
99 |
100 | def nn_model_test_case():
101 | np.random.seed(1)
102 | X_assess = np.random.randn(2, 3)
103 | Y_assess = np.random.randn(1, 3)
104 | return X_assess, Y_assess
105 |
106 | def predict_test_case():
107 | np.random.seed(1)
108 | X_assess = np.random.randn(2, 3)
109 | parameters = {'W1': np.array([[-0.00615039, 0.0169021 ],
110 | [-0.02311792, 0.03137121],
111 | [-0.0169217 , -0.01752545],
112 | [ 0.00935436, -0.05018221]]),
113 | 'W2': np.array([[-0.0104319 , -0.04019007, 0.01607211, 0.04440255]]),
114 | 'b1': np.array([[ -8.97523455e-07],
115 | [ 8.15562092e-06],
116 | [ 6.04810633e-07],
117 | [ -2.54560700e-06]]),
118 | 'b2': np.array([[ 9.14954378e-05]])}
119 | return parameters, X_assess
120 |
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 3/README.md:
--------------------------------------------------------------------------------
1 | # Week 3 Exercises
2 |
3 | Exercises completed during the third week of the course:
4 | * Planar data classification with one hidden layer
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 3/Shallow Neural Networks.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 3/Shallow Neural Networks.pdf
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/dnn_utils_v2.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def sigmoid(Z):
4 | """
5 | Implements the sigmoid activation in numpy
6 |
7 | Arguments:
8 | Z -- numpy array of any shape
9 |
10 | Returns:
11 | A -- output of sigmoid(z), same shape as Z
12 | cache -- returns Z as well, useful during backpropagation
13 | """
14 |
15 | A = 1/(1+np.exp(-Z))
16 | cache = Z
17 |
18 | return A, cache
19 |
20 | def relu(Z):
21 | """
22 | Implement the RELU function.
23 |
24 | Arguments:
25 | Z -- Output of the linear layer, of any shape
26 |
27 | Returns:
28 | A -- Post-activation parameter, of the same shape as Z
29 | cache -- a python dictionary containing "A" ; stored for computing the backward pass efficiently
30 | """
31 |
32 | A = np.maximum(0,Z)
33 |
34 | assert(A.shape == Z.shape)
35 |
36 | cache = Z
37 | return A, cache
38 |
39 |
40 | def relu_backward(dA, cache):
41 | """
42 | Implement the backward propagation for a single RELU unit.
43 |
44 | Arguments:
45 | dA -- post-activation gradient, of any shape
46 | cache -- 'Z' where we store for computing backward propagation efficiently
47 |
48 | Returns:
49 | dZ -- Gradient of the cost with respect to Z
50 | """
51 |
52 | Z = cache
53 | dZ = np.array(dA, copy=True) # just converting dz to a correct object.
54 |
55 | # When z <= 0, you should set dz to 0 as well.
56 | dZ[Z <= 0] = 0
57 |
58 | assert (dZ.shape == Z.shape)
59 |
60 | return dZ
61 |
62 | def sigmoid_backward(dA, cache):
63 | """
64 | Implement the backward propagation for a single SIGMOID unit.
65 |
66 | Arguments:
67 | dA -- post-activation gradient, of any shape
68 | cache -- 'Z' where we store for computing backward propagation efficiently
69 |
70 | Returns:
71 | dZ -- Gradient of the cost with respect to Z
72 | """
73 |
74 | Z = cache
75 |
76 | s = 1/(1+np.exp(-Z))
77 | dZ = dA * s * (1-s)
78 |
79 | assert (dZ.shape == Z.shape)
80 |
81 | return dZ
82 |
83 |
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/2layerNN.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/2layerNN.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/NlayerNN.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/NlayerNN.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/backpass.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/backpass.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/backprop.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/backprop.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/backprop_kiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/backprop_kiank.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/final outline.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/final outline.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/imvector.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/imvector.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/linearback_kiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/linearback_kiank.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/mn_backward.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/mn_backward.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/model_architecture2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/model_architecture2.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/model_architecture_kiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/model_architecture_kiank.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/n_model_backward.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/n_model_backward.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/nm_backward.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/nm_backward.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/relu.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/relu.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/structure.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/images/structure.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Building your Deep Neural Network - Step by Step/testCases_v2.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def linear_forward_test_case():
4 | np.random.seed(1)
5 | """
6 | X = np.array([[-1.02387576, 1.12397796],
7 | [-1.62328545, 0.64667545],
8 | [-1.74314104, -0.59664964]])
9 | W = np.array([[ 0.74505627, 1.97611078, -1.24412333]])
10 | b = np.array([[1]])
11 | """
12 | A = np.random.randn(3,2)
13 | W = np.random.randn(1,3)
14 | b = np.random.randn(1,1)
15 |
16 | return A, W, b
17 |
18 | def linear_activation_forward_test_case():
19 | """
20 | X = np.array([[-1.02387576, 1.12397796],
21 | [-1.62328545, 0.64667545],
22 | [-1.74314104, -0.59664964]])
23 | W = np.array([[ 0.74505627, 1.97611078, -1.24412333]])
24 | b = 5
25 | """
26 | np.random.seed(2)
27 | A_prev = np.random.randn(3,2)
28 | W = np.random.randn(1,3)
29 | b = np.random.randn(1,1)
30 | return A_prev, W, b
31 |
32 | def L_model_forward_test_case():
33 | """
34 | X = np.array([[-1.02387576, 1.12397796],
35 | [-1.62328545, 0.64667545],
36 | [-1.74314104, -0.59664964]])
37 | parameters = {'W1': np.array([[ 1.62434536, -0.61175641, -0.52817175],
38 | [-1.07296862, 0.86540763, -2.3015387 ]]),
39 | 'W2': np.array([[ 1.74481176, -0.7612069 ]]),
40 | 'b1': np.array([[ 0.],
41 | [ 0.]]),
42 | 'b2': np.array([[ 0.]])}
43 | """
44 | np.random.seed(1)
45 | X = np.random.randn(4,2)
46 | W1 = np.random.randn(3,4)
47 | b1 = np.random.randn(3,1)
48 | W2 = np.random.randn(1,3)
49 | b2 = np.random.randn(1,1)
50 | parameters = {"W1": W1,
51 | "b1": b1,
52 | "W2": W2,
53 | "b2": b2}
54 |
55 | return X, parameters
56 |
57 | def compute_cost_test_case():
58 | Y = np.asarray([[1, 1, 1]])
59 | aL = np.array([[.8,.9,0.4]])
60 |
61 | return Y, aL
62 |
63 | def linear_backward_test_case():
64 | """
65 | z, linear_cache = (np.array([[-0.8019545 , 3.85763489]]), (np.array([[-1.02387576, 1.12397796],
66 | [-1.62328545, 0.64667545],
67 | [-1.74314104, -0.59664964]]), np.array([[ 0.74505627, 1.97611078, -1.24412333]]), np.array([[1]]))
68 | """
69 | np.random.seed(1)
70 | dZ = np.random.randn(1,2)
71 | A = np.random.randn(3,2)
72 | W = np.random.randn(1,3)
73 | b = np.random.randn(1,1)
74 | linear_cache = (A, W, b)
75 | return dZ, linear_cache
76 |
77 | def linear_activation_backward_test_case():
78 | """
79 | aL, linear_activation_cache = (np.array([[ 3.1980455 , 7.85763489]]), ((np.array([[-1.02387576, 1.12397796], [-1.62328545, 0.64667545], [-1.74314104, -0.59664964]]), np.array([[ 0.74505627, 1.97611078, -1.24412333]]), 5), np.array([[ 3.1980455 , 7.85763489]])))
80 | """
81 | np.random.seed(2)
82 | dA = np.random.randn(1,2)
83 | A = np.random.randn(3,2)
84 | W = np.random.randn(1,3)
85 | b = np.random.randn(1,1)
86 | Z = np.random.randn(1,2)
87 | linear_cache = (A, W, b)
88 | activation_cache = Z
89 | linear_activation_cache = (linear_cache, activation_cache)
90 |
91 | return dA, linear_activation_cache
92 |
93 | def L_model_backward_test_case():
94 | """
95 | X = np.random.rand(3,2)
96 | Y = np.array([[1, 1]])
97 | parameters = {'W1': np.array([[ 1.78862847, 0.43650985, 0.09649747]]), 'b1': np.array([[ 0.]])}
98 |
99 | aL, caches = (np.array([[ 0.60298372, 0.87182628]]), [((np.array([[ 0.20445225, 0.87811744],
100 | [ 0.02738759, 0.67046751],
101 | [ 0.4173048 , 0.55868983]]),
102 | np.array([[ 1.78862847, 0.43650985, 0.09649747]]),
103 | np.array([[ 0.]])),
104 | np.array([[ 0.41791293, 1.91720367]]))])
105 | """
106 | np.random.seed(3)
107 | AL = np.random.randn(1, 2)
108 | Y = np.array([[1, 0]])
109 |
110 | A1 = np.random.randn(4,2)
111 | W1 = np.random.randn(3,4)
112 | b1 = np.random.randn(3,1)
113 | Z1 = np.random.randn(3,2)
114 | linear_cache_activation_1 = ((A1, W1, b1), Z1)
115 |
116 | A2 = np.random.randn(3,2)
117 | W2 = np.random.randn(1,3)
118 | b2 = np.random.randn(1,1)
119 | Z2 = np.random.randn(1,2)
120 | linear_cache_activation_2 = ( (A2, W2, b2), Z2)
121 |
122 | caches = (linear_cache_activation_1, linear_cache_activation_2)
123 |
124 | return AL, Y, caches
125 |
126 | def update_parameters_test_case():
127 | """
128 | parameters = {'W1': np.array([[ 1.78862847, 0.43650985, 0.09649747],
129 | [-1.8634927 , -0.2773882 , -0.35475898],
130 | [-0.08274148, -0.62700068, -0.04381817],
131 | [-0.47721803, -1.31386475, 0.88462238]]),
132 | 'W2': np.array([[ 0.88131804, 1.70957306, 0.05003364, -0.40467741],
133 | [-0.54535995, -1.54647732, 0.98236743, -1.10106763],
134 | [-1.18504653, -0.2056499 , 1.48614836, 0.23671627]]),
135 | 'W3': np.array([[-1.02378514, -0.7129932 , 0.62524497],
136 | [-0.16051336, -0.76883635, -0.23003072]]),
137 | 'b1': np.array([[ 0.],
138 | [ 0.],
139 | [ 0.],
140 | [ 0.]]),
141 | 'b2': np.array([[ 0.],
142 | [ 0.],
143 | [ 0.]]),
144 | 'b3': np.array([[ 0.],
145 | [ 0.]])}
146 | grads = {'dW1': np.array([[ 0.63070583, 0.66482653, 0.18308507],
147 | [ 0. , 0. , 0. ],
148 | [ 0. , 0. , 0. ],
149 | [ 0. , 0. , 0. ]]),
150 | 'dW2': np.array([[ 1.62934255, 0. , 0. , 0. ],
151 | [ 0. , 0. , 0. , 0. ],
152 | [ 0. , 0. , 0. , 0. ]]),
153 | 'dW3': np.array([[-1.40260776, 0. , 0. ]]),
154 | 'da1': np.array([[ 0.70760786, 0.65063504],
155 | [ 0.17268975, 0.15878569],
156 | [ 0.03817582, 0.03510211]]),
157 | 'da2': np.array([[ 0.39561478, 0.36376198],
158 | [ 0.7674101 , 0.70562233],
159 | [ 0.0224596 , 0.02065127],
160 | [-0.18165561, -0.16702967]]),
161 | 'da3': np.array([[ 0.44888991, 0.41274769],
162 | [ 0.31261975, 0.28744927],
163 | [-0.27414557, -0.25207283]]),
164 | 'db1': 0.75937676204411464,
165 | 'db2': 0.86163759922811056,
166 | 'db3': -0.84161956022334572}
167 | """
168 | np.random.seed(2)
169 | W1 = np.random.randn(3,4)
170 | b1 = np.random.randn(3,1)
171 | W2 = np.random.randn(1,3)
172 | b2 = np.random.randn(1,1)
173 | parameters = {"W1": W1,
174 | "b1": b1,
175 | "W2": W2,
176 | "b2": b2}
177 | np.random.seed(3)
178 | dW1 = np.random.randn(3,4)
179 | db1 = np.random.randn(3,1)
180 | dW2 = np.random.randn(1,3)
181 | db2 = np.random.randn(1,1)
182 | grads = {"dW1": dW1,
183 | "db1": db1,
184 | "dW2": dW2,
185 | "db2": db2}
186 |
187 | return parameters, grads
188 |
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/datasets/test_catvnoncat.h5:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/datasets/test_catvnoncat.h5
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/datasets/train_catvnoncat.h5:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/datasets/train_catvnoncat.h5
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/dnn_app_utils_v2.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import matplotlib.pyplot as plt
3 | import h5py
4 |
5 |
6 | def sigmoid(Z):
7 | """
8 | Implements the sigmoid activation in numpy
9 |
10 | Arguments:
11 | Z -- numpy array of any shape
12 |
13 | Returns:
14 | A -- output of sigmoid(z), same shape as Z
15 | cache -- returns Z as well, useful during backpropagation
16 | """
17 |
18 | A = 1/(1+np.exp(-Z))
19 | cache = Z
20 |
21 | return A, cache
22 |
23 | def relu(Z):
24 | """
25 | Implement the RELU function.
26 |
27 | Arguments:
28 | Z -- Output of the linear layer, of any shape
29 |
30 | Returns:
31 | A -- Post-activation parameter, of the same shape as Z
32 | cache -- a python dictionary containing "A" ; stored for computing the backward pass efficiently
33 | """
34 |
35 | A = np.maximum(0,Z)
36 |
37 | assert(A.shape == Z.shape)
38 |
39 | cache = Z
40 | return A, cache
41 |
42 |
43 | def relu_backward(dA, cache):
44 | """
45 | Implement the backward propagation for a single RELU unit.
46 |
47 | Arguments:
48 | dA -- post-activation gradient, of any shape
49 | cache -- 'Z' where we store for computing backward propagation efficiently
50 |
51 | Returns:
52 | dZ -- Gradient of the cost with respect to Z
53 | """
54 |
55 | Z = cache
56 | dZ = np.array(dA, copy=True) # just converting dz to a correct object.
57 |
58 | # When z <= 0, you should set dz to 0 as well.
59 | dZ[Z <= 0] = 0
60 |
61 | assert (dZ.shape == Z.shape)
62 |
63 | return dZ
64 |
65 | def sigmoid_backward(dA, cache):
66 | """
67 | Implement the backward propagation for a single SIGMOID unit.
68 |
69 | Arguments:
70 | dA -- post-activation gradient, of any shape
71 | cache -- 'Z' where we store for computing backward propagation efficiently
72 |
73 | Returns:
74 | dZ -- Gradient of the cost with respect to Z
75 | """
76 |
77 | Z = cache
78 |
79 | s = 1/(1+np.exp(-Z))
80 | dZ = dA * s * (1-s)
81 |
82 | assert (dZ.shape == Z.shape)
83 |
84 | return dZ
85 |
86 |
87 | def load_data():
88 | train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")
89 | train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features
90 | train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels
91 |
92 | test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r")
93 | test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features
94 | test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels
95 |
96 | classes = np.array(test_dataset["list_classes"][:]) # the list of classes
97 |
98 | train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
99 | test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
100 |
101 | return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes
102 |
103 |
104 | def initialize_parameters(n_x, n_h, n_y):
105 | """
106 | Argument:
107 | n_x -- size of the input layer
108 | n_h -- size of the hidden layer
109 | n_y -- size of the output layer
110 |
111 | Returns:
112 | parameters -- python dictionary containing your parameters:
113 | W1 -- weight matrix of shape (n_h, n_x)
114 | b1 -- bias vector of shape (n_h, 1)
115 | W2 -- weight matrix of shape (n_y, n_h)
116 | b2 -- bias vector of shape (n_y, 1)
117 | """
118 |
119 | np.random.seed(1)
120 |
121 | W1 = np.random.randn(n_h, n_x)*0.01
122 | b1 = np.zeros((n_h, 1))
123 | W2 = np.random.randn(n_y, n_h)*0.01
124 | b2 = np.zeros((n_y, 1))
125 |
126 | assert(W1.shape == (n_h, n_x))
127 | assert(b1.shape == (n_h, 1))
128 | assert(W2.shape == (n_y, n_h))
129 | assert(b2.shape == (n_y, 1))
130 |
131 | parameters = {"W1": W1,
132 | "b1": b1,
133 | "W2": W2,
134 | "b2": b2}
135 |
136 | return parameters
137 |
138 |
139 | def initialize_parameters_deep(layer_dims):
140 | """
141 | Arguments:
142 | layer_dims -- python array (list) containing the dimensions of each layer in our network
143 |
144 | Returns:
145 | parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
146 | Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1])
147 | bl -- bias vector of shape (layer_dims[l], 1)
148 | """
149 |
150 | np.random.seed(1)
151 | parameters = {}
152 | L = len(layer_dims) # number of layers in the network
153 |
154 | for l in range(1, L):
155 | parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) / np.sqrt(layer_dims[l-1]) #*0.01
156 | parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))
157 |
158 | assert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1]))
159 | assert(parameters['b' + str(l)].shape == (layer_dims[l], 1))
160 |
161 |
162 | return parameters
163 |
164 | def linear_forward(A, W, b):
165 | """
166 | Implement the linear part of a layer's forward propagation.
167 |
168 | Arguments:
169 | A -- activations from previous layer (or input data): (size of previous layer, number of examples)
170 | W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
171 | b -- bias vector, numpy array of shape (size of the current layer, 1)
172 |
173 | Returns:
174 | Z -- the input of the activation function, also called pre-activation parameter
175 | cache -- a python dictionary containing "A", "W" and "b" ; stored for computing the backward pass efficiently
176 | """
177 |
178 | Z = W.dot(A) + b
179 |
180 | assert(Z.shape == (W.shape[0], A.shape[1]))
181 | cache = (A, W, b)
182 |
183 | return Z, cache
184 |
185 | def linear_activation_forward(A_prev, W, b, activation):
186 | """
187 | Implement the forward propagation for the LINEAR->ACTIVATION layer
188 |
189 | Arguments:
190 | A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)
191 | W -- weights matrix: numpy array of shape (size of current layer, size of previous layer)
192 | b -- bias vector, numpy array of shape (size of the current layer, 1)
193 | activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"
194 |
195 | Returns:
196 | A -- the output of the activation function, also called the post-activation value
197 | cache -- a python dictionary containing "linear_cache" and "activation_cache";
198 | stored for computing the backward pass efficiently
199 | """
200 |
201 | if activation == "sigmoid":
202 | # Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
203 | Z, linear_cache = linear_forward(A_prev, W, b)
204 | A, activation_cache = sigmoid(Z)
205 |
206 | elif activation == "relu":
207 | # Inputs: "A_prev, W, b". Outputs: "A, activation_cache".
208 | Z, linear_cache = linear_forward(A_prev, W, b)
209 | A, activation_cache = relu(Z)
210 |
211 | assert (A.shape == (W.shape[0], A_prev.shape[1]))
212 | cache = (linear_cache, activation_cache)
213 |
214 | return A, cache
215 |
216 | def L_model_forward(X, parameters):
217 | """
218 | Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation
219 |
220 | Arguments:
221 | X -- data, numpy array of shape (input size, number of examples)
222 | parameters -- output of initialize_parameters_deep()
223 |
224 | Returns:
225 | AL -- last post-activation value
226 | caches -- list of caches containing:
227 | every cache of linear_relu_forward() (there are L-1 of them, indexed from 0 to L-2)
228 | the cache of linear_sigmoid_forward() (there is one, indexed L-1)
229 | """
230 |
231 | caches = []
232 | A = X
233 | L = len(parameters) // 2 # number of layers in the neural network
234 |
235 | # Implement [LINEAR -> RELU]*(L-1). Add "cache" to the "caches" list.
236 | for l in range(1, L):
237 | A_prev = A
238 | A, cache = linear_activation_forward(A_prev, parameters['W' + str(l)], parameters['b' + str(l)], activation = "relu")
239 | caches.append(cache)
240 |
241 | # Implement LINEAR -> SIGMOID. Add "cache" to the "caches" list.
242 | AL, cache = linear_activation_forward(A, parameters['W' + str(L)], parameters['b' + str(L)], activation = "sigmoid")
243 | caches.append(cache)
244 |
245 | assert(AL.shape == (1,X.shape[1]))
246 |
247 | return AL, caches
248 |
249 | def compute_cost(AL, Y):
250 | """
251 | Implement the cost function defined by equation (7).
252 |
253 | Arguments:
254 | AL -- probability vector corresponding to your label predictions, shape (1, number of examples)
255 | Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)
256 |
257 | Returns:
258 | cost -- cross-entropy cost
259 | """
260 |
261 | m = Y.shape[1]
262 |
263 | # Compute loss from aL and y.
264 | cost = (1./m) * (-np.dot(Y,np.log(AL).T) - np.dot(1-Y, np.log(1-AL).T))
265 |
266 | cost = np.squeeze(cost) # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).
267 | assert(cost.shape == ())
268 |
269 | return cost
270 |
271 | def linear_backward(dZ, cache):
272 | """
273 | Implement the linear portion of backward propagation for a single layer (layer l)
274 |
275 | Arguments:
276 | dZ -- Gradient of the cost with respect to the linear output (of current layer l)
277 | cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer
278 |
279 | Returns:
280 | dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
281 | dW -- Gradient of the cost with respect to W (current layer l), same shape as W
282 | db -- Gradient of the cost with respect to b (current layer l), same shape as b
283 | """
284 | A_prev, W, b = cache
285 | m = A_prev.shape[1]
286 |
287 | dW = 1./m * np.dot(dZ,A_prev.T)
288 | db = 1./m * np.sum(dZ, axis = 1, keepdims = True)
289 | dA_prev = np.dot(W.T,dZ)
290 |
291 | assert (dA_prev.shape == A_prev.shape)
292 | assert (dW.shape == W.shape)
293 | assert (db.shape == b.shape)
294 |
295 | return dA_prev, dW, db
296 |
297 | def linear_activation_backward(dA, cache, activation):
298 | """
299 | Implement the backward propagation for the LINEAR->ACTIVATION layer.
300 |
301 | Arguments:
302 | dA -- post-activation gradient for current layer l
303 | cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently
304 | activation -- the activation to be used in this layer, stored as a text string: "sigmoid" or "relu"
305 |
306 | Returns:
307 | dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev
308 | dW -- Gradient of the cost with respect to W (current layer l), same shape as W
309 | db -- Gradient of the cost with respect to b (current layer l), same shape as b
310 | """
311 | linear_cache, activation_cache = cache
312 |
313 | if activation == "relu":
314 | dZ = relu_backward(dA, activation_cache)
315 | dA_prev, dW, db = linear_backward(dZ, linear_cache)
316 |
317 | elif activation == "sigmoid":
318 | dZ = sigmoid_backward(dA, activation_cache)
319 | dA_prev, dW, db = linear_backward(dZ, linear_cache)
320 |
321 | return dA_prev, dW, db
322 |
323 | def L_model_backward(AL, Y, caches):
324 | """
325 | Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group
326 |
327 | Arguments:
328 | AL -- probability vector, output of the forward propagation (L_model_forward())
329 | Y -- true "label" vector (containing 0 if non-cat, 1 if cat)
330 | caches -- list of caches containing:
331 | every cache of linear_activation_forward() with "relu" (there are (L-1) or them, indexes from 0 to L-2)
332 | the cache of linear_activation_forward() with "sigmoid" (there is one, index L-1)
333 |
334 | Returns:
335 | grads -- A dictionary with the gradients
336 | grads["dA" + str(l)] = ...
337 | grads["dW" + str(l)] = ...
338 | grads["db" + str(l)] = ...
339 | """
340 | grads = {}
341 | L = len(caches) # the number of layers
342 | m = AL.shape[1]
343 | Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL
344 |
345 | # Initializing the backpropagation
346 | dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))
347 |
348 | # Lth layer (SIGMOID -> LINEAR) gradients. Inputs: "AL, Y, caches". Outputs: "grads["dAL"], grads["dWL"], grads["dbL"]
349 | current_cache = caches[L-1]
350 | grads["dA" + str(L)], grads["dW" + str(L)], grads["db" + str(L)] = linear_activation_backward(dAL, current_cache, activation = "sigmoid")
351 |
352 | for l in reversed(range(L-1)):
353 | # lth layer: (RELU -> LINEAR) gradients.
354 | current_cache = caches[l]
355 | dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads["dA" + str(l + 2)], current_cache, activation = "relu")
356 | grads["dA" + str(l + 1)] = dA_prev_temp
357 | grads["dW" + str(l + 1)] = dW_temp
358 | grads["db" + str(l + 1)] = db_temp
359 |
360 | return grads
361 |
362 | def update_parameters(parameters, grads, learning_rate):
363 | """
364 | Update parameters using gradient descent
365 |
366 | Arguments:
367 | parameters -- python dictionary containing your parameters
368 | grads -- python dictionary containing your gradients, output of L_model_backward
369 |
370 | Returns:
371 | parameters -- python dictionary containing your updated parameters
372 | parameters["W" + str(l)] = ...
373 | parameters["b" + str(l)] = ...
374 | """
375 |
376 | L = len(parameters) // 2 # number of layers in the neural network
377 |
378 | # Update rule for each parameter. Use a for loop.
379 | for l in range(L):
380 | parameters["W" + str(l+1)] = parameters["W" + str(l+1)] - learning_rate * grads["dW" + str(l+1)]
381 | parameters["b" + str(l+1)] = parameters["b" + str(l+1)] - learning_rate * grads["db" + str(l+1)]
382 |
383 | return parameters
384 |
385 | def predict(X, y, parameters):
386 | """
387 | This function is used to predict the results of a L-layer neural network.
388 |
389 | Arguments:
390 | X -- data set of examples you would like to label
391 | parameters -- parameters of the trained model
392 |
393 | Returns:
394 | p -- predictions for the given dataset X
395 | """
396 |
397 | m = X.shape[1]
398 | n = len(parameters) // 2 # number of layers in the neural network
399 | p = np.zeros((1,m))
400 |
401 | # Forward propagation
402 | probas, caches = L_model_forward(X, parameters)
403 |
404 |
405 | # convert probas to 0/1 predictions
406 | for i in range(0, probas.shape[1]):
407 | if probas[0,i] > 0.5:
408 | p[0,i] = 1
409 | else:
410 | p[0,i] = 0
411 |
412 | #print results
413 | #print ("predictions: " + str(p))
414 | #print ("true labels: " + str(y))
415 | print("Accuracy: " + str(np.sum((p == y)/m)))
416 |
417 | return p
418 |
419 | def print_mislabeled_images(classes, X, y, p):
420 | """
421 | Plots images where predictions and truth were different.
422 | X -- dataset
423 | y -- true labels
424 | p -- predictions
425 | """
426 | a = p + y
427 | mislabeled_indices = np.asarray(np.where(a == 1))
428 | plt.rcParams['figure.figsize'] = (40.0, 40.0) # set default size of plots
429 | num_images = len(mislabeled_indices[0])
430 | for i in range(num_images):
431 | index = mislabeled_indices[1][i]
432 |
433 | plt.subplot(2, num_images, i + 1)
434 | plt.imshow(X[:,index].reshape(64,64,3), interpolation='nearest')
435 | plt.axis('off')
436 | plt.title("Prediction: " + classes[int(p[0,index])].decode("utf-8") + " \n Class: " + classes[y[0,index]].decode("utf-8"))
437 |
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/images/2layerNN_kiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/images/2layerNN_kiank.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/images/LlayerNN_kiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/images/LlayerNN_kiank.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/images/imvector.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/images/imvector.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/images/imvectorkiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/images/imvectorkiank.png
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/images/my_image.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Deep Neural Network Application Image Classification/images/my_image.jpg
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/Key concepts on Deep Neural Networks.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Neural Networks and Deep Learning/Week 4/Key concepts on Deep Neural Networks.pdf
--------------------------------------------------------------------------------
/Neural Networks and Deep Learning/Week 4/README.md:
--------------------------------------------------------------------------------
1 | # Week 4 Exercises
2 |
3 | Exercises completed during the fourth week of the course:
4 | * Exercise-1
5 | * Exercise-2
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | * This is my assignment on Andrew Ng's special course "[***Deep Learning Specialization***](https://www.coursera.org/specializations/deep-learning)" This course consists of five courses:
2 | * [***Neural Networks and Deep Learning***](https://www.coursera.org/learn/neural-networks-deep-learning/home/welcome)
3 | * [***Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimization***](https://www.coursera.org/learn/deep-neural-network/home/welcome)
4 | * [***Structuring Machine Learning Projects***](https://www.coursera.org/learn/machine-learning-projects/home/welcome)
5 | * [***Convolutional Neural Networks***](https://www.coursera.org/learn/convolutional-neural-networks)
6 | * [***Sequence Models***](https://www.coursera.org/learn/nlp-sequence-models)
7 |
8 | 
9 |
10 | 
11 |
12 | 
13 |
14 | 
15 |
16 | 
17 |
18 | # Deep Learning
19 | + [x] Neural Networks and Deep Learning
20 | + [x] Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimization
21 | + [x] Structuring Machine Learning Projects
22 | + [x] Convolutional Neural Networks
23 | + [x] Sequence Models
24 |
25 | # Deep Learning - deeplearning.ai
26 | Coursera Deep Learning Course by deeplearning.ai projects
27 |
28 | ## Course 1. Neural Networks and Deep Learning
29 | 1. Week1 - Introduction to deep learning
30 | 2. Week2 - Neural Networks Basics
31 | 3. Week3 - Shallow neural networks
32 | 4. Week4 - Deep Neural Networks
33 |
34 | ## Course 2. Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization
35 | 1. Week1 - Practical aspects of Deep Learning
36 | - Setting up your Machine Learning Application
37 | - Regularizing your neural network
38 | - Setting up your optimization problem
39 | 2. Week2 - Optimization algorithms
40 | 3. Week3 - Hyperparameter tuning, Batch Normalization and Programming Frameworks
41 |
42 | ## Course 3. Structuring Machine Learning Projects
43 | 1. Week1 - Introduction to ML Strategy
44 | - Setting up your goal
45 | - Comparing to human-level performance
46 | 2. Week2 - ML Strategy (2)
47 | - Error Analysis
48 | - Mismatched training and dev/test set
49 | - Learning from multiple tasks
50 | - End-to-end deep learning
51 |
52 | ## Course 4. Convolutional Neural Networks
53 | 1. Week1 - Foundations of Convolutional Neural Networks
54 | 2. Week2 - Deep convolutional models: case studies
55 | 3. Week3 - Object detection - Papers for read: [You Only Look Once:
56 | Unified, Real-Time Object Detection](https://arxiv.org/pdf/1506.02640.pdf), [YOLO](https://arxiv.org/pdf/1612.08242.pdf)
57 | 4. Week4 - Special applications: Face recognition & Neural style transfer - Papers for read: [DeepFace](https://www.cs.toronto.edu/~ranzato/publications/taigman_cvpr14.pdf), [FaceNet](https://www.cv-foundation.org/openaccess/content_cvpr_2015/papers/Schroff_FaceNet_A_Unified_2015_CVPR_paper.pdf)
58 |
59 | ## Course 5. Sequence Models
60 | 1. Week1 - Recurrent Neural Networks
61 | 2. Week2 - Natural Language Processing & Word Embeddings
62 | 3. Week3 - Sequence models & Attention mechanism
63 |
64 | ---
65 | *source from **Andrew Ng**'s [Deep learning](https://www.coursera.org/specializations/deep-learning) course on Coursera*
66 |
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/LSTM.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/LSTM.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/LSTM_rnn.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/LSTM_rnn.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/clip.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/clip.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/initial_state.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/initial_state.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/rnn.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/rnn.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/rnn_cell_backprop.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/rnn_cell_backprop.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/rnn_step_forward.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/rnn_step_forward.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/sampling.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/images/sampling.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/clip.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/clip.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/dino.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/dino.jpg
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/dinos3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/dinos3.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/fountain.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/fountain.jpg
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/mangosaurus.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/mangosaurus.jpeg
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/rnn.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/rnn.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/shakespeare.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Dinosaur Island -- Character-level language model/images/shakespeare.jpg
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Jazz improvisation with LSTM/data/30s_seq.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Jazz improvisation with LSTM/data/30s_seq.mp3
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Jazz improvisation with LSTM/data/30s_trained_model.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Jazz improvisation with LSTM/data/30s_trained_model.mp3
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Jazz improvisation with LSTM/data/training_example.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Jazz improvisation with LSTM/data/training_example.mp3
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Jazz improvisation with LSTM/images/chord_symbols.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Jazz improvisation with LSTM/images/chord_symbols.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Jazz improvisation with LSTM/images/dataset.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Jazz improvisation with LSTM/images/dataset.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Jazz improvisation with LSTM/images/jazz.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Jazz improvisation with LSTM/images/jazz.jpg
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Jazz improvisation with LSTM/images/model.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Jazz improvisation with LSTM/images/model.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Jazz improvisation with LSTM/images/music_gen.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Jazz improvisation with LSTM/images/music_gen.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Jazz improvisation with LSTM/images/music_generation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Jazz improvisation with LSTM/images/music_generation.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Jazz improvisation with LSTM/images/tones.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Jazz improvisation with LSTM/images/tones.png
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Jazz improvisation with LSTM/inference_code.py:
--------------------------------------------------------------------------------
1 | def inference_model(LSTM_cell, densor, n_x = 78, n_a = 64, Ty = 100):
2 | """
3 | Uses the trained "LSTM_cell" and "densor" from model() to generate a sequence of values.
4 |
5 | Arguments:
6 | LSTM_cell -- the trained "LSTM_cell" from model(), Keras layer object
7 | densor -- the trained "densor" from model(), Keras layer object
8 | n_x -- number of unique values
9 | n_a -- number of units in the LSTM_cell
10 | Ty -- number of time steps to generate
11 |
12 | Returns:
13 | inference_model -- Keras model instance
14 | """
15 |
16 | # Define the input of your model with a shape
17 | x0 = Input(shape=(1, n_x))
18 |
19 | # Define s0, initial hidden state for the decoder LSTM
20 | a0 = Input(shape=(n_a,), name='a0')
21 | c0 = Input(shape=(n_a,), name='c0')
22 | a = a0
23 | c = c0
24 | x = x0
25 |
26 | ### START CODE HERE ###
27 | # Step 1: Create an empty list of "outputs" to later store your predicted values (≈1 line)
28 | outputs = []
29 |
30 | # Step 2: Loop over Ty and generate a value at every time step
31 | for t in range(Ty):
32 |
33 | # Step 2.A: Perform one step of LSTM_cell (≈1 line)
34 | a, _, c = LSTM_cell(x, initial_state=[a, c])
35 |
36 | # Step 2.B: Apply Dense layer to the hidden state output of the LSTM_cell (≈1 line)
37 | out = densor(a)
38 |
39 | # Step 2.C: Append the prediction "out" to "outputs" (≈1 line)
40 | outputs.append(out)
41 |
42 | # Step 2.D: Set the prediction "out" to be the next input "x". You will need to use RepeatVector(1). (≈1 line)
43 | x = RepeatVector(1)(out)
44 |
45 | # Step 3: Create model instance with the correct "inputs" and "outputs" (≈1 line)
46 | inference_model = Model(inputs=[x0, a0, c0], outputs=outputs)
47 | ### END CODE HERE ###
48 |
49 | return inference_model
50 |
51 |
52 | inference_model = inference_model(LSTM_cell, densor)
53 |
54 |
55 | x1 = np.zeros((1, 1, 78))
56 | x1[:,:,35] = 1
57 | a1 = np.zeros((1, n_a))
58 | c1 = np.zeros((1, n_a))
59 | predicting = inference_model.predict([x1, a1, c1])
60 |
61 |
62 | indices = np.argmax(predicting, axis = -1)
63 | results = to_categorical(indices, num_classes=78)
--------------------------------------------------------------------------------
/Sequence Models/Week 1/Recurrent Neural Networks.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 1/Recurrent Neural Networks.pdf
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Emojify/images/data_set.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Emojify/images/data_set.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Emojify/images/dataset_kiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Emojify/images/dataset_kiank.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Emojify/images/emb_kiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Emojify/images/emb_kiank.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Emojify/images/embedding1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Emojify/images/embedding1.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Emojify/images/emo_model.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Emojify/images/emo_model.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Emojify/images/emoji_list.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Emojify/images/emoji_list.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Emojify/images/emojifier-v2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Emojify/images/emojifier-v2.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Emojify/images/emojifierv1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Emojify/images/emojifierv1.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Emojify/images/emojify_model.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Emojify/images/emojify_model.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Emojify/images/emojiss.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Emojify/images/emojiss.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Emojify/images/image_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Emojify/images/image_1.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Emojify/images/woebot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Emojify/images/woebot.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Natural Language Processing & Word Embeddings.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Natural Language Processing & Word Embeddings.pdf
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/1-hot-vector.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/1-hot-vector.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/cosine_sim.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/cosine_sim.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/equalize.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/equalize.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/equalize1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/equalize1.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/equalize10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/equalize10.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/equalize7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/equalize7.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/equalize8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/equalize8.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/equalize9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/equalize9.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/equalize_kiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/equalize_kiank.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/equalize_kiank1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/equalize_kiank1.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/equalize_kiank2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/equalize_kiank2.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/equalize_kiank3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/equalize_kiank3.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/lookup.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/lookup.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/neutral.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/neutral.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/neutralize.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/neutralize.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/neutralize_kiank.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/neutralize_kiank.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/skipgram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/skipgram.png
--------------------------------------------------------------------------------
/Sequence Models/Week 2/Word Vector Representation/images/slide_window.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 2/Word Vector Representation/images/slide_window.mp4
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Machine Translation/images/attn_mechanism.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Machine Translation/images/attn_mechanism.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Machine Translation/images/attn_model.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Machine Translation/images/attn_model.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Machine Translation/images/date_attention.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Machine Translation/images/date_attention.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Machine Translation/images/date_attention2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Machine Translation/images/date_attention2.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Machine Translation/images/poorly_trained_model.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Machine Translation/images/poorly_trained_model.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Machine Translation/images/table.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Machine Translation/images/table.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Sequence models & Attention mechanism.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Sequence models & Attention mechanism.pdf
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/audio_examples/chime.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/audio_examples/chime.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/audio_examples/example_train.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/audio_examples/example_train.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/audio_examples/insert_reference.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/audio_examples/insert_reference.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/audio_examples/my_audio.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/audio_examples/my_audio.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/audio_examples/train_reference.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/audio_examples/train_reference.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/chime_output.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/chime_output.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/images/label_diagram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/images/label_diagram.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/images/model.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/images/model.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/images/ones_reference.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/images/ones_reference.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/images/sound.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/images/sound.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/images/spectrogram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/images/spectrogram.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/images/train_label.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/images/train_label.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/images/train_reference.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/images/train_reference.png
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/insert_test.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/insert_test.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/activates/1.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/activates/1.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/activates/1_act2.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/activates/1_act2.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/activates/1_act3.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/activates/1_act3.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/activates/2.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/activates/2.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/activates/2_act2.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/activates/2_act2.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/activates/2_act3.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/activates/2_act3.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/activates/3.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/activates/3.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/activates/3_act2.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/activates/3_act2.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/activates/3_act3.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/activates/3_act3.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/activates/4_act2.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/activates/4_act2.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/backgrounds/1.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/backgrounds/1.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/backgrounds/2.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/backgrounds/2.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/dev/1.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/dev/1.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/dev/2.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/dev/2.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/1.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/1.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/1_0.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/1_0.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/2.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/2.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/2_1.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/2_1.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/3.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/3.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/3_2.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/3_2.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/4.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/4.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/4_0.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/4_0.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/5.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/5.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/5_1.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/raw_data/negatives/5_1.wav
--------------------------------------------------------------------------------
/Sequence Models/Week 3/Trigger word detection/train.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Sequence Models/Week 3/Trigger word detection/train.wav
--------------------------------------------------------------------------------
/Structuring Machine Learning Projects/Autonomous driving (case study).pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Structuring Machine Learning Projects/Autonomous driving (case study).pdf
--------------------------------------------------------------------------------
/Structuring Machine Learning Projects/Bird recognition in the city of Peacetopia (case study).pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rvarun7777/Deep_Learning/3a59def70cfb8dc766dc0d2da3f3514c37f5a577/Structuring Machine Learning Projects/Bird recognition in the city of Peacetopia (case study).pdf
--------------------------------------------------------------------------------