Docsity

Deep learning 100 pages notes, Study notes of Computer science

Toggle sidebar
bg1
Course summary
Here are the course summary as its given on the course link:
If you want to break into cutting-edge AI, this course will help you do so. Deep learning engineers are highly sought
after, and mastering deep learning will give you numerous new career opportunities. Deep learning is also a new
"superpower" that will let you build AI systems that just weren't possible a few years ago.
In this course, you will learn the foundations of deep learning. When you finish this class, you will:
Understand the major technology trends driving Deep Learning
Be able to build, train and apply fully connected deep neural networks
Know how to implement efficient (vectorized) neural networks
Understand the key parameters in a neural network's architecture
This course also teaches you how Deep Learning actually works, rather than presenting only a cursory or surface-level
description. So after completing it, you will be able to apply deep learning to a your own applications. If you are looking
for a job in AI, after this course you will also be able to answer basic interview questions.
Introduction to deep learning
Be able to explain the major trends driving the rise of deep learning, and understand where and how it is applied today.
What is a (Neural Network) NN?
Single neuron == linear regression without applying activation(perceptron)
Basically a single neuron will calculate weighted sum of input(W.T*X) and then we can set a threshold to predict output
in a perceptron. If weighted sum of input cross the threshold, perceptron fires and if not then perceptron doesn't
predict.
Perceptron can take real values input or boolean values.
Actually, when w⋅x+b=0 the perceptron outputs 0.
Disadvantage of perceptron is that it only output binary values and if we try to give small change in weight and bais
then perceptron can flip the output. We need some system which can modify the output slightly according to small
change in weight and bias. Here comes sigmoid function in picture.
If we change perceptron with a sigmoid function, then we can make slight change in output.
e.g. output in perceptron = 0, you slightly changed weight and bias, output becomes = 1 but actual output is 0.7. In case
of sigmoid, output1 = 0, slight change in weight and bias, output = 0.7.
If we apply sigmoid activation function then Single neuron will act as Logistic Regression.
we can understand difference between perceptron and sigmoid function by looking at sigmoid function graph.
Simple NN graph:
Image taken from tutorialspoint.com
RELU stands for rectified linear unit is the most popular activation function right now that makes deep NNs train faster
now.
Hidden layers predicts connection between inputs automatically, thats what deep learning is good at.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Deep learning 100 pages notes and more Study notes Computer science in PDF only on Docsity!

Course summary

Here are the course summary as its given on the course link:

If you want to break into cutting-edge AI, this course will help you do so. Deep learning engineers are highly sought after, and mastering deep learning will give you numerous new career opportunities. Deep learning is also a new "superpower" that will let you build AI systems that just weren't possible a few years ago.

In this course, you will learn the foundations of deep learning. When you finish this class, you will:

Understand the major technology trends driving Deep Learning Be able to build, train and apply fully connected deep neural networks Know how to implement efficient (vectorized) neural networks Understand the key parameters in a neural network's architecture

This course also teaches you how Deep Learning actually works, rather than presenting only a cursory or surface-level description. So after completing it, you will be able to apply deep learning to a your own applications. If you are looking for a job in AI, after this course you will also be able to answer basic interview questions.

Introduction to deep learning

Be able to explain the major trends driving the rise of deep learning, and understand where and how it is applied today.

What is a (Neural Network) NN?

Single neuron == linear regression without applying activation(perceptron)

Basically a single neuron will calculate weighted sum of input(W.T*X) and then we can set a threshold to predict output in a perceptron. If weighted sum of input cross the threshold, perceptron fires and if not then perceptron doesn't predict.

Perceptron can take real values input or boolean values.

Actually, when w⋅x+b=0 the perceptron outputs 0.

Disadvantage of perceptron is that it only output binary values and if we try to give small change in weight and bais then perceptron can flip the output. We need some system which can modify the output slightly according to small change in weight and bias. Here comes sigmoid function in picture.

If we change perceptron with a sigmoid function, then we can make slight change in output.

e.g. output in perceptron = 0, you slightly changed weight and bias, output becomes = 1 but actual output is 0.7. In case of sigmoid, output1 = 0, slight change in weight and bias, output = 0.7.

If we apply sigmoid activation function then Single neuron will act as Logistic Regression.

we can understand difference between perceptron and sigmoid function by looking at sigmoid function graph.

Simple NN graph:

Image taken from tutorialspoint.com

RELU stands for rectified linear unit is the most popular activation function right now that makes deep NNs train faster now.

Hidden layers predicts connection between inputs automatically, thats what deep learning is good at.

Deep NN consists of more hidden layers (Deeper layers)

Image taken from opennn.net

Each Input will be connected to the hidden layer and the NN will decide the connections.

Supervised learning means we have the (X,Y) and we need to get the function that maps X to Y.

Supervised learning with neural networks

Different types of neural networks for supervised learning which includes: CNN or convolutional neural networks (Useful in computer vision) RNN or Recurrent neural networks (Useful in Speech recognition or NLP) Standard NN (Useful for Structured data) Hybrid/custom NN or a Collection of NNs types Structured data is like the databases and tables. Unstructured data is like images, video, audio, and text. Structured data gives more money because companies relies on prediction on its big data.

Why is deep learning taking off?

Deep learning is taking off for 3 reasons:

i. Data: Using this image we can conclude:

For small data NN can perform as Linear regression or SVM (Support vector machine) For big data a small NN is better that SVM For big data a big NN is better that a medium NN is better that small NN. Hopefully we have a lot of data because the world is using the computer a little bit more Mobiles IOT (Internet of things) ii. Computation: GPUs. Powerful CPUs. Distributed computing. ASICs iii. Algorithm: a. Creative algorithms has appeared that changed the way NN works. For example using RELU function is so much better than using SIGMOID function in training a NN because it helps with the vanishing gradient problem.

The actual equations we will implement:

w = w - alpha * d(J(w,b) / dw) (how much the function slopes in the w direction) b = b - alpha * d(J(w,b) / db) (how much the function slopes in the d direction)

Derivatives

We will talk about some of required calculus. You don't need to be a calculus geek to master deep learning but you'll need some skills from it. Derivative of a linear line is its slope. ex. f(a) = 3a d(f(a))/d(a) = 3 if a = 2 then f(a) = 6 if we move a a little bit a = 2.001 then f(a) = 6.003 means that we multiplied the derivative (Slope) to the moved area and added it to the last result.

More Derivatives examples

f(a) = a^2 ==> d(f(a))/d(a) = 2a a = 2 ==> f(a) = 4 a = 2.0001 ==> f(a) = 4.0004 approx. f(a) = a^3 ==> d(f(a))/d(a) = 3a^ f(a) = log(a) ==> d(f(a))/d(a) = 1/a To conclude, Derivative is the slope and slope is different in different points in the function thats why the derivative is a function.

Computation graph

Its a graph that organizes the computation from left to right.

Derivatives with a Computation Graph

Calculus chain rule says: If x -> y -> z (x effect y and y effects z) Then d(z)/d(x) = d(z)/d(y) * d(y)/d(x) The video illustrates a big example.

We compute the derivatives on a graph from right to left and it will be a lot more easier. dvar means the derivatives of a final output variable with respect to various intermediate quantities.

Logistic Regression Gradient Descent

In the video he discussed the derivatives of gradient decent example for one sample with two features x1 and x.

Gradient Descent on m Examples

Lets say we have these variables:

X1 Feature X2 Feature W1 Weight of the first feature. W2 Weight of the second feature. B Logistic Regression parameter. M Number of training examples Y(i) Expected output of i

So we have:

Then from right to left we will calculate derivations compared to the result:

d(a) = d(l)/d(a) = -(y/a) + ((1-y)/(1-a)) d(z) = d(l)/d(z) = a - y d(W1) = X1 * d(z) d(W2) = X2 * d(z) d(B) = d(z)

From the above we can conclude the logistic regression pseudo code:

J = 0; dw1 = 0; dw2 =0; db = 0; # Devs. w1 = 0; w2 = 0; b=0; # Weights for i = 1 to m

Forward pass

z(i) = W1x1(i) + W2x2(i) + b a(i) = Sigmoid(z(i)) J += (Y(i)log(a(i)) + (1-Y(i))log(1-a(i)))

Backward pass

dz(i) = a(i) - Y(i) dw1 += dz(i) * x1(i) dw2 += dz(i) * x2(i) db += dz(i) J /= m dw1/= m dw2/= m db/= m

Gradient descent

w1 = w1 - alpa * dw w2 = w2 - alpa * dw b = b - alpa * db

The above code should run for some iterations to minimize error.

So there will be two inner loops to implement the logistic regression.

Vectorization is so important on deep learning to reduce loops. In the last code we can make the whole loop in one step using vectorization!

Vectorization

Deep learning shines when the dataset are big. However for loops will make you wait a lot for a result. Thats why we need vectorization to get rid of some of our for loops.

kaggle.com is a good place for datasets and competitions. Pieter Abbeel is one of the best in deep reinforcement learning.

Shallow neural networks

Learn to build a neural network with one hidden layer, using forward propagation and backpropagation.

Neural Networks Overview

In logistic regression we had:

X1 X2 ==> z = XW + B ==> a = Sigmoid(z) ==> l(a,Y) X3 /

In neural networks with one layer we will have:

X1 X2 => z1 = XW1 + B1 => a1 = Sigmoid(z1) => z2 = a1W2 + B2 => a2 = Sigmoid(z2) => l(a2,Y) X3 /

X is the input vector (X1, X2, X3) , and Y is the output variable (1x1)

NN is stack of logistic regression objects.

Neural Network Representation

We will define the neural networks that has one hidden layer. NN contains of input layers, hidden layers, output layers. Hidden layer means we cant see that layers in the training set. a0 = x (the input layer) a1 will represent the activation of the hidden neurons. a2 will represent the output layer. We are talking about 2 layers NN. The input layer isn't counted.

Computing a Neural Network's Output

Equations of Hidden layers:

Here are some informations about the last image: noOfHiddenNeurons = 4 Nx = 3 Shapes of the variables: W1 is the matrix of the first hidden layer, it has a shape of (noOfHiddenNeurons,nx) b1 is the matrix of the first hidden layer, it has a shape of (noOfHiddenNeurons,1) z1 is the result of the equation z1 = W1X + b , it has a shape of (noOfHiddenNeurons,1) a1 is the result of the equation a1 = sigmoid(z1) , it has a shape of (noOfHiddenNeurons,1) W2 is the matrix of the second hidden layer, it has a shape of (1,noOfHiddenNeurons) b2 is the matrix of the second hidden layer, it has a shape of (1,1) z2 is the result of the equation z2 = W2a1 + b , it has a shape of (1,1) a2 is the result of the equation a2 = sigmoid(z2) , it has a shape of (1,1)

Vectorizing across multiple examples

Pseudo code for forward propagation for the 2 layers NN:

for i = 1 to m z[1, i] = W1x[i] + b1 # shape of z[1, i] is (noOfHiddenNeurons,1) a[1, i] = sigmoid(z[1, i]) # shape of a[1, i] is (noOfHiddenNeurons,1) z[2, i] = W2a[1, i] + b2 # shape of z[2, i] is (1,1) a[2, i] = sigmoid(z[2, i]) # shape of a[2, i] is (1,1)

Lets say we have X on shape (Nx,m). So the new pseudo code:

Z1 = W1X + b1 # shape of Z1 (noOfHiddenNeurons,m) A1 = sigmoid(Z1) # shape of A1 (noOfHiddenNeurons,m) Z2 = W2A1 + b2 # shape of Z2 is (1,m) A2 = sigmoid(Z2) # shape of A2 is (1,m)

If you notice always m is the number of columns.

In the last example we can call X = A0. So the previous step can be rewritten as:

Z1 = W1A0 + b1 # shape of Z1 (noOfHiddenNeurons,m) A1 = sigmoid(Z1) # shape of A1 (noOfHiddenNeurons,m) Z2 = W2A1 + b2 # shape of Z2 is (1,m) A2 = sigmoid(Z2) # shape of A2 is (1,m)

Activation functions

So far we are using sigmoid, but in some cases other functions can be a lot better. Sigmoid can lead us to gradient decent problem where the updates are so low. Sigmoid activation function range is [0,1] A = 1 / (1 + np.exp(-z)) # Where z is the input matrix Tanh activation function range is [-1,1] (Shifted version of sigmoid function)

In NumPy we can implement Tanh using one of these methods: A = (np.exp(z) - np.exp(-z)) / (np.exp(z) + np.exp(-z)) # Where z is the input matrix

Or A = np.tanh(z) # Where z is the input matrix

It turns out that the tanh activation usually works better than sigmoid activation function for hidden units because the mean of its output is closer to zero, and so it centers the data better for the next layer. Sigmoid or Tanh function disadvantage is that if the input is too small or too high, the slope will be near zero which will cause us the gradient decent problem. One of the popular activation functions that solved the slow gradient decent is the RELU function. RELU = max(0,z) # so if z is negative the slope is 0 and if z is positive the slope remains linear. So here is some basic rule for choosing activation functions, if your classification is between 0 and 1, use the output activation as sigmoid and the others as RELU. Leaky RELU activation function different of RELU is that if the input is negative the slope will be so small. It works as RELU but most people uses RELU. Leaky_RELU = max(0.01z,z) #the 0.01 can be a parameter for your algorithm. In NN you will decide a lot of choices like: No of hidden layers. No of neurons in each hidden layer. Learning rate. (The most important parameter) Activation functions. And others.. It turns out there are no guide lines for that. You should try all activation functions for example.

Why do you need non-linear activation functions?

If we removed the activation function from our algorithm that can be called linear activation function. Linear activation function will output linear activations Whatever hidden layers you add, the activation will be always linear like logistic regression (So its useless in a lot of complex problems) You might use linear activation function in one place - in the output layer if the output is real numbers (regression problem). But even in this case if the output value is non-negative you could use RELU instead.

Derivatives of activation functions

Derivation of Sigmoid activation function:

g(z) = 1 / (1 + np.exp(-z)) g'(z) = (1 / (1 + np.exp(-z))) * (1 - (1 / (1 + np.exp(-z)))) g'(z) = g(z) * (1 - g(z))

Derivation of Tanh activation function:

How we derived the 6 equations of the backpropagation:

Random Initialization

In logistic regression it wasn't important to initialize the weights randomly, while in NN we have to initialize them randomly.

If we initialize all the weights with zeros in NN it won't work (initializing bias with zero is OK):

all hidden units will be completely identical (symmetric) - compute exactly the same function on each gradient descent iteration all the hidden units will always update the same

To solve this we initialize the W's with a small random numbers:

W1 = np.random.randn((2,2)) * 0.01 # 0.01 to make it small enough b1 = np.zeros((2,1)) # its ok to have b as zero, it won't get us to the symmetry breaking problem

We need small values because in sigmoid (or tanh), for example, if the weight is too large you are more likely to end up even at the very start of training with very large values of Z. Which causes your tanh or your sigmoid activation function to be saturated, thus slowing down learning. If you don't have any sigmoid or tanh activation functions throughout your neural network, this is less of an issue.

Constant 0.01 is alright for 1 hidden layer networks, but if the NN is deep this number can be changed but it will always be a small number.

Deep Neural Networks

Understand the key computations underlying deep learning, use them to build and train deep neural networks, and apply it to computer vision.

Deep L-layer neural network

Shallow NN is a NN with one or two layers. Deep NN is a NN with three or more layers. We will use the notation L to denote the number of layers in a NN. n[l] is the number of neurons in a specific layer l. n[0] denotes the number of neurons input layer. n[L] denotes the number of neurons in output layer. g[l] is the activation function. a[l] = gl w[l] weights is used for z[l] x = a[0] , a[l] = y' These were the notation we will use for deep neural network. So we have: A vector n of shape (1, NoOfLayers+1) A vector g of shape (1, NoOfLayers) A list of different shapes w based on the number of neurons on the previous and the current layer. A list of different shapes b based on the number of neurons on the current layer.

Forward Propagation in a Deep Network

Forward propagation general rule for one input:

z[l] = W[l]a[l-1] + b[l] a[l] = gl

Forward propagation general rule for m inputs:

Z[l] = W[l]A[l-1] + B[l] A[l] = gl

We can't compute the whole layers forward propagation without a for loop so its OK to have a for loop here.

The dimensions of the matrices are so important you need to figure it out.

Getting your matrix dimensions right

The best way to debug your matrices dimensions is by a pencil and paper. Dimension of W is (n[l],n[l-1]). Can be thought by right to left. Dimension of b is (n[l],1) dw has the same shape as W , while db is the same shape as b Dimension of Z[l], A[l] , dZ[l] , and dA[l] is (n[l],m)

Why deep representations?

Why deep NN works well, we will discuss this question in this section. Deep NN makes relations with data from simpler to complex. In each layer it tries to make a relation with the previous layer. E.g.: a. Face recognition application: Image ==> Edges ==> Face parts ==> Faces ==> desired face b. Audio recognition application: Audio ==> Low level sound features like (sss,bb) ==> Phonemes ==> Words ==> Sentences Neural Researchers think that deep neural networks "think" like brains (simple ==> complex) Circuit theory and deep learning:

When starting on an application don't start directly by dozens of hidden layers. Try the simplest solutions (e.g. Logistic Regression), then try the shallow neural network and so on.

Building blocks of deep neural networks

Forward and back propagation for a layer l:

Deep NN blocks:

Training a Softmax classifier

Deep learning frameworks

TensorFlow

Extra Notes

Course summary

Here are the course summary as its given on the course link:

This course will teach you the "magic" of getting deep learning to work well. Rather than the deep learning process

being a black box, you will understand what drives performance, and be able to more systematically get good results.

You will also learn TensorFlow.

After 3 weeks, you will:

Understand industry best-practices for building deep learning applications.

Be able to effectively use the common neural network "tricks", including initialization, L2 and dropout

regularization, Batch normalization, gradient checking,

Be able to implement and apply a variety of optimization algorithms, such as mini-batch gradient descent,

Momentum, RMSprop and Adam, and check for their convergence.

Understand new best-practices for the deep learning era of how to set up train/dev/test sets and analyze

bias/variance

Be able to implement a neural network in TensorFlow.

This is the second course of the Deep Learning Specialization.

Practical aspects of Deep Learning

Train / Dev / Test sets

Its impossible to get all your hyperparameters right on a new application from the first time.

So the idea is you go through the loop: Idea ==> Code ==> Experiment.

You have to go through the loop many times to figure out your hyperparameters.

Your data will be split into three parts:

Training set. (Has to be the largest set)

Hold-out cross validation set / Development or "dev" set.

Testing set.

You will try to build a model upon training set then try to optimize hyperparameters on dev set as much as possible.

Then after your model is ready you try and evaluate the testing set.

so the trend on the ratio of splitting the models:

If size of the dataset is 100 to 1000000 ==> 60/20/

If size of the dataset is 1000000 to INF ==> 98/1/1 or 99.5/0.25/0.

The trend now gives the training data the biggest sets.

Make sure the dev and test set are coming from the same distribution.

For example if cat training pictures is from the web and the dev/test pictures are from users cell phone they will

mismatch. It is better to make sure that dev and test set are from the same distribution.

The dev set rule is to try them on some of the good models you've created.

Its OK to only have a dev set without a testing set. But a lot of people in this case call the dev set as the test set. A better

terminology is to call it a dev set as its used in the development.

Bias / Variance

Bias / Variance techniques are Easy to learn, but difficult to master.

So here the explanation of Bias / Variance:

If your model is underfitting (logistic regression of non linear data) it has a "high bias"

If your model is overfitting then it has a "high variance"

Your model will be alright if you balance the Bias / Variance

For more:

Another idea to get the bias / variance if you don't have a 2D plotting mechanism:

High variance (overfitting) for example:

Training error: 1%

Dev error: 11%

high Bias (underfitting) for example:

Training error: 15%

Dev error: 14%

high Bias (underfitting) && High variance (overfitting) for example:

Training error: 15%

Test error: 30%

Best:

Training error: 0.5%

Test error: 1%

These Assumptions came from that human has 0% error. If the problem isn't like that you'll need to use human

error as baseline.

Basic Recipe for Machine Learning

If your algorithm has a high bias:

Try to make your NN bigger (size of hidden units, number of layers)

Try a different model that is suitable for your data.

Try to run it longer.

Different (advanced) optimization algorithms.

If your algorithm has a high variance:

More data.

Try regularization.

Try a different model that is suitable for your data.

You should try the previous two points until you have a low bias and low variance.

In the older days before deep learning, there was a "Bias/variance tradeoff". But because now you have more

options/tools for solving the bias and variance problem its really helpful to use deep learning.

Training a bigger neural network never hurts.

Regularization

Adding regularization to NN will help it reduce variance (overfitting)

L1 matrix norm:

||W|| = Sum(|w[i,j]|) # sum of absolute values of all w

L2 matrix norm because of arcane technical math reasons is called Frobenius norm:

||W||^2 = Sum(|w[i,j]|^2) # sum of all w squared

Also can be calculated as ||W||^2 = W.T * W if W is a vector

Regularization for logistic regression:

The normal cost function that we want to minimize is: J(w,b) = (1/m) * Sum(L(y(i),y'(i)))

The L2 regularization version: J(w,b) = (1/m) * Sum(L(y(i),y'(i))) + (lambda/2m) * Sum(|w[i]|^2)

The L1 regularization version: J(w,b) = (1/m) * Sum(L(y(i),y'(i))) + (lambda/2m) * Sum(|w[i]|)

The L1 regularization version makes a lot of w values become zeros, which makes the model size smaller.

L2 regularization is being used much more often.

lambda here is the regularization parameter (hyperparameter)

Regularization for NN:

Dropout can have different keep_prob per layer.

The input layer dropout has to be near 1 (or 1 - no dropout) because you don't want to eliminate a lot of features.

If you're more worried about some layers overfitting than others, you can set a lower keep_prob for some layers than

others. The downside is, this gives you even more hyperparameters to search for using cross-validation. One other

alternative might be to have some layers where you apply dropout and some layers where you don't apply dropout and

then just have one hyperparameter, which is a keep_prob for the layers for which you do apply dropouts.

A lot of researchers are using dropout with Computer Vision (CV) because they have a very big input size and almost

never have enough data, so overfitting is the usual problem. And dropout is a regularization technique to prevent

overfitting.

A downside of dropout is that the cost function J is not well defined and it will be hard to debug (plot J by iteration).

To solve that you'll need to turn off dropout, set all the keep_prob s to 1, and then run the code and check that it

monotonically decreases J and then turn on the dropouts again.

Other regularization methods

Data augmentation :

For example in a computer vision data:

You can flip all your pictures horizontally this will give you m more data instances.

You could also apply a random position and rotation to an image to get more data.

For example in OCR, you can impose random rotations and distortions to digits/letters.

New data obtained using this technique isn't as good as the real independent data, but still can be used as a

regularization technique.

Early stopping :

In this technique we plot the training set and the dev set cost together for each iteration. At some iteration the dev

set cost will stop decreasing and will start increasing.

We will pick the point at which the training set error and dev set error are best (lowest training cost with lowest dev

cost).

We will take these parameters as the best parameters.

Andrew prefers to use L2 regularization instead of early stopping because this technique simultaneously tries to

minimize the cost function and not to overfit which contradicts the orthogonalization approach (will be discussed

further).

But its advantage is that you don't need to search a hyperparameter like in other regularization approaches (like

lambda in L2 regularization).

Model Ensembles :

Algorithm:

Train multiple independent models.

At test time average their results.

It can get you extra 2% performance.

It reduces the generalization error.

You can use some snapshots of your NN at the training ensembles them and take the results.

Normalizing inputs

If you normalize your inputs this will speed up the training process a lot.

Normalization are going on these steps:

i. Get the mean of the training set: mean = (1/m) * sum(x(i))

ii. Subtract the mean from each input: X = X - mean

This makes your inputs centered around 0.

iii. Get the variance of the training set: variance = (1/m) * sum(x(i)^2)

iv. Normalize the variance. X /= variance

These steps should be applied to training, dev, and testing sets (but using mean and variance of the train set).

Why normalize?

If we don't normalize the inputs our cost function will be deep and its shape will be inconsistent (elongated) then

optimizing it will take a long time.

But if we normalize it the opposite will occur. The shape of the cost function will be consistent (look more

symmetric like circle in 2D example) and we can use a larger learning rate alpha - the optimization will be faster.

Vanishing / Exploding gradients

The Vanishing / Exploding gradients occurs when your derivatives become very small or very big.

To understand the problem, suppose that we have a deep neural network with number of layers L, and all the activation

functions are linear and each b = 0

Then:

Y' = W[L]W[L-1].....W[2]W[1]X

Then, if we have 2 hidden units per layer and x1 = x2 = 1, we result in:

if W[l] = [1.5 0] [0 1.5] (l != L because of different dimensions in the output layer) Y' = W[L] [1.5 0]^(L-1) X = 1.5^L # which will be very large [0 1.5]

if W[l] = [0.5 0] [0 0.5] Y' = W[L] [0.5 0]^(L-1) X = 0.5^L # which will be very small [0 0.5]

The last example explains that the activations (and similarly derivatives) will be decreased/increased exponentially as a

function of number of layers.

So If W > I (Identity matrix) the activation and gradients will explode.

And If W < I (Identity matrix) the activation and gradients will vanish.

Recently Microsoft trained 152 layers (ResNet)! which is a really big number. With such a deep neural network, if your

activations or gradients increase or decrease exponentially as a function of L, then these values could get really big or

really small. And this makes training difficult, especially if your gradients are exponentially smaller than L, then gradient

descent will take tiny little steps. It will take a long time for gradient descent to learn anything.

There is a partial solution that doesn't completely solve this problem but it helps a lot - careful choice of how you

initialize the weights (next video).

Weight Initialization for Deep Networks

A partial solution to the Vanishing / Exploding gradients in NN is better or more careful choice of the random

initialization of weights

In a single neuron (Perceptron model): Z = w1x1 + w2x2 + ... + wnxn

So if n_x is large we want W 's to be smaller to not explode the cost.

So it turns out that we need the variance which equals 1/n_x to be the range of W 's

So lets say when we initialize W 's like this (better to use with tanh activation):

np.random.rand(shape) * np.sqrt(1/n[l-1])

or variation of this (Bengio et al.):

np.random.rand(shape) * np.sqrt(2/(n[l-1] + n[l]))

Setting initialization part inside sqrt to 2/n[l-1] for ReLU is better:

np.random.rand(shape) * np.sqrt(2/n[l-1])

Number 1 or 2 in the nominator can also be a hyperparameter to tune (but not the first to start with)

This is one of the best way of partially solution to Vanishing / Exploding gradients (ReLU + Weight Initialization with

variance) which will help gradients not to vanish/explode too quickly

The initialization in this video is called "He Initialization / Xavier Initialization" and has been published in 2015 paper.

Numerical approximation of gradients

Observations :

The value of λ is a hyperparameter that you can tune using a dev set.

L2 regularization makes your decision boundary smoother. If λ is too large, it is also possible to "oversmooth", resulting

in a model with high bias.

What is L2-regularization actually doing? :

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.

What you should remember:

Implications of L2-regularization on:

cost computation:

A regularization term is added to the cost

backpropagation function:

There are extra terms in the gradients with respect to weight matrices

weights:

weights end up smaller ("weight decay") - are pushed to smaller values.

2. Dropout

What you should remember about dropout:

Dropout is a regularization technique.

You only use dropout during training. Don't use dropout (randomly eliminate nodes) during test time.

Apply dropout both during forward and backward propagation.

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.

Optimization algorithms

Mini-batch gradient descent

Training NN with a large data is slow. So to find an optimization algorithm that runs faster is a good idea.

Suppose we have m = 50 million. To train this data it will take a huge processing time for one step.

because 50 million won't fit in the memory at once we need other processing to make such a thing.

It turns out you can make a faster algorithm to make gradient descent process some of your items even before you

finish the 50 million items.

Suppose we have split m to mini batches of size 1000.

X{1} = 0 ... 1000 X{2} = 1001 ... 2000 ... X{bs} = ...

We similarly split X & Y.

So the definition of mini batches ==> t: X{t}, Y{t}

In Batch gradient descent we run the gradient descent on the whole dataset.

While in Mini-Batch gradient descent we run the gradient descent on the mini datasets.

Mini-Batch algorithm pseudo code:

for t = 1:No_of_batches # this is called an epoch AL, caches = forward_prop(X{t}, Y{t}) cost = compute_cost(AL, Y{t}) grads = backward_prop(AL, caches) update_parameters(grads)

The code inside an epoch should be vectorized.

Mini-batch gradient descent works much faster in the large datasets.

Understanding mini-batch gradient descent

In mini-batch algorithm, the cost won't go down with each step as it does in batch algorithm. It could contain some ups

and downs but generally it has to go down (unlike the batch gradient descent where cost function descreases on each

iteration).

Mini-batch size:

( mini batch size = m ) ==> Batch gradient descent

( mini batch size = 1 ) ==> Stochastic gradient descent (SGD)

( mini batch size = between 1 and m ) ==> Mini-batch gradient descent

Batch gradient descent:

too long per iteration (epoch)

Stochastic gradient descent:

too noisy regarding cost minimization (can be reduced by using smaller learning rate)

won't ever converge (reach the minimum cost)

lose speedup from vectorization

Mini-batch gradient descent:

i. faster learning:

you have the vectorization advantage

make progress without waiting to process the entire training set

ii. doesn't always exactly converge (oscelates in a very small region, but you can reduce learning rate)

Guidelines for choosing mini-batch size:

i. If small training set (< 2000 examples) - use batch gradient descent.

ii. It has to be a power of 2 (because of the way computer memory is layed out and accessed, sometimes your code

runs faster if your mini-batch size is a power of 2): 64, 128, 256, 512, 1024, ...

iii. Make sure that mini-batch fits in CPU/GPU memory.

Mini-batch size is a hyperparameter.

Exponentially weighted averages

There are optimization algorithms that are better than gradient descent , but you should first learn about Exponentially

weighted averages.

If we have data like the temperature of day through the year it could be like this:

t(1) = 40 t(2) = 49 t(3) = 45 ... t(180) = 60 ...

This data is small in winter and big in summer. If we plot this data we will find it some noisy.

Now lets compute the Exponentially weighted averages:

V0 = 0 V1 = 0.9 * V0 + 0.1 * t(1) = 4 # 0.9 and 0.1 are hyperparameters V2 = 0.9 * V1 + 0.1 * t(2) = 8. V3 = 0.9 * V2 + 0.1 * t(3) = 12. ...

General equation

V(t) = beta * v(t-1) + (1-beta) * theta(t)

If we plot this it will represent averages over ~ (1 / (1 - beta)) entries:

beta = 0.9 will average last 10 entries

beta = 0.98 will average last 50 entries

beta = 0.5 will average last 2 entries