cs 502 directed studies: adversarial machine learning
TRANSCRIPT
CS 502
Directed Studies: Adversarial Machine Learning
Dr. Alex Vakanski
2
CS 502, Fall 2020
Lecture 2
Deep Learning Overview
3
CS 502, Fall 2020
Lecture Outline
β’ Machine learning basics
β Supervised and unsupervised learning
β Linear and non-linear classification methods
β’ Introduction to deep learning
β’ Elements of neural networks (NNs)
β Activation functions
β’ Training NNs
β Gradient descent
β Regularization methods
β’ NN architectures
β Convolutional NNs
β Recurrent NNs
4
CS 502, Fall 2020
Machine Learning Basics
β’ Artificial Intelligence is a scientific field concerned with the development of algorithms that allow computers to learn without being explicitly programmed
β’ Machine Learning is a branch of Artificial Intelligence, which focuses on methods that learn from data and make predictions on unseen data
Labeled Data
Labeled Data
Machine Learning algorithm
Learned model
Prediction
Training
Prediction
Picture from: Ismini Lourentzou β Introduction to Deep Learning
5
CS 502, Fall 2020
Machine Learning Types
β’ Supervised: learning with labeled data
β Example: email classification, image classification
β Example: regression for predicting real-valued outputs
β’ Unsupervised: discover patterns in unlabeled data
β Example: cluster similar data points
β’ Reinforcement learning: learn to act based on feedback/reward
β Example: learn to play Go
class A
class B
Classification Regression Clustering
Slide credit: Ismini Lourentzou β Introduction to Deep Learning
6
CS 502, Fall 2020
Supervised Learning
β’ Supervised learning categories and techniques
β Numerical classifier functions
βͺ Linear classifier, perceptron, logistic regression, support vector machines (SVM), neural networks
β Parametric (probabilistic) functions
βͺ NaΓ―ve Bayes, Gaussian discriminant analysis (GDA), hidden Markov models (HMM), probabilistic graphical models
β Non-parametric (instance-based) functions
βͺ k-nearest neighbors, kernel regression, kernel density estimation, local regression
β Symbolic functions
βͺ Decision trees, classification and regression trees (CART)
β Aggregation (ensemble) learning
βͺ Bagging, boosting (Adaboost), random forest
Slide credit: Y-Fan Chang β An Overview of Machine Learning
7
CS 502, Fall 2020
Unsupervised Learning
β’ Unsupervised learning categories and techniques
β Clustering
βͺ k-means clustering
βͺ Mean-shift clustering
βͺ Spectral clustering
β Density estimation
βͺ Gaussian mixture model (GMM)
βͺ Graphical models
β Dimensionality reduction
βͺ Principal component analysis (PCA)
βͺ Factor analysis
Slide credit: Y-Fan Chang β An Overview of Machine Learning
8
CS 502, Fall 2020
Nearest Neighbor Classifier
β’ Nearest Neighbor - for each test data point, assign the class label of the nearest training data point
β Adopt a distance function to find the nearest neighbor
βͺ Calculate the distance to each data point in the training set, and assign the class of the nearest data point (minimum distance)
β No parameter training required
Test
exampleTraining
examples
from class 1
Training
examples
from class 2
Picture from: James Hays β Machine Learning Overview
9
CS 502, Fall 2020
Nearest Neighbor Classifier
β’ For image classification, the distance between all pixels is calculated (e.g., using β1 norm, or β2 norm)
β Accuracy on CIFAR10: 38.6%
β’ Disadvantages:
β The classifier must remember all training data and store it for future comparisons with the test data
β Classifying a test image is expensive since it requires a comparison to all training images
Picture from: https://cs231n.github.io/classification/
β1 norm(Manhattan distance)
10
CS 502, Fall 2020
Nearest Neighbor Classifier
β’ k-Nearest Neighbors approach considers multiple neighboring data points to classify a test data point
β E.g., 3-nearest neighbors
βͺ The test example in the figure is the + mark
βͺ The class of the test example is obtained by voting (of 3 closest points)
x x
xx
x
x
x
xo
oo
o
o
oo
x2
x1
oo
x+
+
Picture from: James Hays β Machine Learning Overview
11
CS 502, Fall 2020
Linear Classifier
β’ Linear classifier
β Find a linear function f of the inputs xi that separates the classes
β Use pairs of inputs and labels to find the weights matrix W and the bias vector b
βͺ The weights and biases are the parameters of the function f
βͺ Parameter learning is solved by minimizing a loss function
β Perceptron algorithm is often used to find optimal parameters
βͺ Updates the parameters until a minimal error is reached (similar togradient descent)
β Linear classifier is a simple approach, but it is a building block of advanced classification algorithms, such as SVM and neural networks
12
CS 502, Fall 2020
Linear Classifier
β’ The decision boundary is linear
β A straight line in 2D, a flat plane in 3D, a hyperplane in 3D and higher dimensional space
β’ Example: classify an input image
β The selected parameters in this example are not good, because the predicted cat score is low
Picture from: https://cs231n.github.io/classification/
13
CS 502, Fall 2020
Support Vector Machines
β’ Support vector machines (SVM)
β How to find the best decision boundary?
βͺ All lines in the figure correctly separate the 2 classes
βͺ The line that is farthest from all training examples will have better generalization capabilities
β SVM solves an optimization problem:
βͺ First, identify a decision boundary that correctly classifies all examples
βͺ Next, increase the geometric margin between the boundary and all examples
β The data points that define the maximum margin width are called support vectors
β Find W and b by solving:
14
CS 502, Fall 2020
Linear vs Non-linear Techniques
β’ Linear classification techniques
β Linear classifier
β Perceptron
β Logistic regression
β Linear SVM
β NaΓ―ve Bayes
β’ Non-linear classification techniques
β k-nearest neighbors
β Non-linear SVM
β Neural networks
β Decision trees
β Random forest
15
CS 502, Fall 2020
Linear vs Non-linear Techniques
β’ For some tasks, input data can be linearly separable, and linear classifiers can be suitably applied
β’ For other tasks, linear classifiers may have difficulties to produce adequate decision boundaries
Picture from: Y-Fan Chang β An Overview of Machine Learning
16
CS 502, Fall 2020
Non-linear Techniques
β’ Non-linear classification
β Features π§π are obtained as non-linear functions of the inputs π₯πβ It results in non-linear decision boundaries
β Can deal with non-linearly separable data
Picture from: Y-Fan Chang β An Overview of Machine Learning
Inputs: π₯π = π₯π1 π₯π2
Features: π§π = π₯π1 π₯π2 π₯π1 β π₯π2 π₯π12 π₯π2
2
Outputs: π π₯π ,π, π = ππ§π + π
17
CS 502, Fall 2020
Non-linear Support Vector Machines
β’ Non-linear SVM
β The original input space is mapped to a higher-dimensional feature space where the training set is linearly separable
β Define a non-linear kernel function to calculate a non-linear decision boundary in the original feature space
Ξ¦: π₯ β¦ π π₯
Picture from: James Hays β Machine Learning Overview
18
CS 502, Fall 2020
Binary vs Multi-class Classification
β’ A problem with only 2 classes is referred to as binary classification
β The output labels are 0 or 1
β E.g., benign or malignant tumor, spam or no spam email
β’ A problem with 3 or more classes is referred to as multi-class classification
19
CS 502, Fall 2020
Binary vs Multi-class Classification
β’ Both the binary and multi-class classification problems can be linearly or non-linearly separated
β Linearly and non-linearly separated data for binary classification problem
20
CS 502, Fall 2020
No-Free-Lunch Theorem
β’ Wolpert (2002) - The Supervised Learning No-Free-Lunch Theorems
β’ The derived classification models for supervised learning are simplifications of the reality
β The simplifications are based on certain assumptions
β The assumptions fail in some situations
βͺ E.g., due to inability to perfectly estimate parameters from limited data
β’ In summary, the theorem states:
β No single classifier works the best for all possible situations
β Since we need to make assumptions to generalize
21
CS 502, Fall 2020
ML vs. Deep Learning
β’ Most machine learning methods rely on human-designed feature representations
β ML becomes just optimizing weights to best make a final prediction
Picture from: Ismini Lourentzou β Introduction to Deep Learning
22
CS 502, Fall 2020
ML vs. Deep Learning
β’ Deep learning (DL) is a machine learning subfield that uses multiple layers for learning data representations
β DL is exceptionally effective at learning patterns
Picture from: https://www.xenonstack.com/blog/static/public/uploads/media/machine-learning-vs-deep-learning.png
23
CS 502, Fall 2020
ML vs. Deep Learning
β’ DL applies a multi-layer process for learning rich hierarchical features (i.e., data representations)
β Input image pixels β Edges β Textures β Parts β Objects
Low-Level Features
Mid-Level Features
OutputHigh-Level Features
Trainable Classifier
Slide credit: Param Vir Singh β Deep Learning
24
CS 502, Fall 2020
Why is DL Useful?
β’ DL provides a flexible, learnable framework for representing visual, text, linguistic information
β Can learn in unsupervised and supervised manner
β’ DL represents an effective end-to-end system learning
β’ Requires large amounts of training data
β’ Since about 2010, DL has outperformed other ML techniques
β First in vision and speech, then NLP, and other applications
25
CS 502, Fall 2020
Representational Power
β’ NNs with at least one hidden layer are universal approximators
β Given any continuous function h(x) and some π > 0, there exists a NN with one hidden layer (and with a reasonable choice of non-linearity) described with the function f(x), such that βπ₯, β π₯ β π(π₯) < π
β I.e., NN can approximate any arbitrary complex continuous function
β’ NNs use nonlinear mapping of the inputs to the outputs f(x) to compute complex decision boundaries
β’ But then, why use deeper NNs?
β The fact that deep NNs work better is an empirical observation
β Mathematically, deep NNs have the same representational power as a one-layer NN
26
CS 502, Fall 2020
Introduction to Neural Networks
β’ Handwritten digit recognition (MNIST dataset)β The intensity of each pixel is considered an input element
β The output is the class of the digit
Input
16 x 16 = 256
1x
2x
256xβ¦
β¦
Ink β 1No ink β 0
β¦β¦
y1
y2
y10
Each dimension represents the confidence of a digit
is 1
is 2
is 0
β¦β¦
0.1
0.7
0.2
The image is β2β
Output
Slide credit: Hung-yi Lee β Deep Learning Tutorial
27
CS 502, Fall 2020
Introduction to Neural Networks
β’ Handwritten digit recognition
Machine β2β
1x
2x
256x
β¦β¦ β¦β¦
y1
y2
y10π: π 256 β π 10
The function π is represented by a neural network
Slide credit: Hung-yi Lee β Deep Learning Tutorial
28
CS 502, Fall 2020
Elements of Neural Networks
β’ NNs consist of hidden layers with neurons (i.e., computational units)
β’ A single neuron maps a set of inputs into an output number, or π: π πΎ β π
bwawawaz KK ++++= 2211
z
1w
2w
Kwβ¦
1a
2a
Ka
+
b
( )z
bias
a
Activation functionweights
π = π π§
input
output
β¦Slide credit: Hung-yi Lee β Deep Learning Tutorial
29
CS 502, Fall 2020
Elements of Neural Networks
β’ A NN with one hidden layer and one output layer
π
π
π
πππ π ππ πππππ π = π(πππ + ππ)
ππππππ πππππ π = π(πΎππ + ππ)
Weights Biases
Activation functions
4 + 2 = 6 neurons (not counting inputs)[3 Γ 4] + [4 Γ 2] = 20 weights
4 + 2 = 6 biases26 learnable parameters
Slide credit: Ismini Lourentzou β Introduction to Deep Learning
30
CS 502, Fall 2020
Elements of Neural Networks
β’ A neural network playground link
31
CS 502, Fall 2020
Elements of Neural Networks
β’ Deep NNs have many hidden layers
β Fully-connected (dense) layers (a.k.a. Multi-Layer Perceptron or MLP)
β Each neuron is connected to all neurons in the succeeding layer
Output LayerHidden Layers
Input Layer
Input Output
1x
2x
Layer 1
β¦β¦
Nx
β¦β¦
Layer 2
β¦β¦
Layer L
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
y1
y2
yM
Slide credit: Hung-yi Lee β Deep Learning Tutorial
32
CS 502, Fall 2020
Elements of Neural Networks
β’ A simple network, toy example
( )z
z
( )ze
zβ+
=1
1
Sigmoid Function
1
-1
1
-2
1
-1
1
0
4
-2
0.98
0.12
1 β 1 + β1 β β2 + 1 = 4
1 β β1 + β1 β 1 + 0 =-2
Slide credit: Hung-yi Lee β Deep Learning Tutorial
33
CS 502, Fall 2020
Elements of Neural Networks
β’ A simple network, toy example (contβd)
β For an input vector [1 β1]π, the output is [0.62 0.83]π
1
-2
1
-1
1
0
4
-2
0.98
0.12
2
-1
-1
-2
3
-1
4
-1
0.86
0.11
0.62
0.83
0
0
-2
2
1
-1
π: π 2 β π 2 π1β1
=0.620.83
Slide credit: Hung-yi Lee β Deep Learning Tutorial
34
CS 502, Fall 2020
Matrix Operation
β’ Matrix operations are helpful when working with multidimensional inputs and outputs
π
1
-2
1
-1
1
0
4
-2
0.98
0.12
1β1
1 β2β1 1 +
10
0.980.12=
1
-14β2
Slide credit: Hung-yi Lee β Deep Learning Tutorial
35
CS 502, Fall 2020
Matrix Operation
β’ Multilayer NN, matrix calculations for the first layer
β Input vector x, weights matrix W1, bias vector b1, output vector a1
1x
2x
β¦β¦
Nx
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
y1
y2
yM
W1
x a1
b1W1 x += π
b1
a1
Slide credit: Hung-yi Lee β Deep Learning Tutorial
36
CS 502, Fall 2020
Matrix Operation
β’ Multilayer NN, matrix calculations for all layers
1x
2x
β¦β¦
Nx
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
y1
y2
yM
W1 W2 WL
b2 bL
x a1 a2 y
b1W1 x +πb2W2 a1 +π
bLWL +π aL-1
b1
Slide credit: Hung-yi Lee β Deep Learning Tutorial
37
CS 502, Fall 2020
Matrix Operation
β’ Multilayer NN, function f maps inputs x to outputs y, i.e., π¦ = π(π₯)
= π π
1x
2x
β¦β¦
Nx
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
y1
y2
yM
W1 W2 WL
b2 bL
x a1 a2 y
y = π x b1W1 x +π b2W2 + bLWL +β¦
b1
β¦
Slide credit: Hung-yi Lee β Deep Learning Tutorial
38
CS 502, Fall 2020
Softmax Layer
β’ In multi-class classification tasks, the output layer is typically a softmax layer
β If a regular hidden layer with sigmoid activations is used instead, the output of the NN may not be easy to interpret
βͺ Sigmoid activations can still be used for binary classification
A Regular Hidden Layer
( )11 zy =
( )22 zy =
( )33 zy =
1z
2z
3z
3
-3
1
0.95
0.05
0.73
Slide credit: Hung-yi Lee β Deep Learning Tutorial
39
CS 502, Fall 2020
Softmax Layer
β’ The softmax layer applies softmax activations to output a probability value in the range [0, 1]
β The values z inputted to the softmax layer are referred to as logits
1z
2z
3z
A Softmax Layer
e
e
e
1ze
2ze
3ze
+
=
=3
1
11
j
zz jeey
=
3
1j
z je
3
-3
1 2.7
20
0.05
0.88
0.12
β0
=
=3
1
22
j
zz jeey
=
=3
1
33
j
zz jeey
Probability:βͺ 0 < π¦π < 1βͺ Οπ π¦π = 1
Slide credit: Hung-yi Lee β Deep Learning Tutorial
40
CS 502, Fall 2020
Activation Functions
β’ Non-linear activations are needed to learn complex (non-linear) data representations
β Otherwise, NNs would be just a linear function (such as W1W2π₯ = ππ₯)
β NNs with large number of layers (and neurons) can approximate more complex functions
βͺ Figure: more neurons improve representation (but, may overfit)
Picture from: http://cs231n.github.io/assets/nn1/layer_sizes.jpeg
41
CS 502, Fall 2020
Activation: Sigmoid
β’ Sigmoid function Ο: takes a real-valued number and βsquashesβ it into the range between 0 and 1
β The output can be interpreted as the firing rate of a biological neuron
βͺ Not firing = 0; Fully firing = 1
β When the neuronβs activation are 0 or 1, sigmoid neurons saturate
βͺ Gradients at these regions are almost zero (almost no signal will flow)
β Sigmoid activations are less common in modern NNs
βπ β 0,1
Slide credit: Ismini Lourentzou β Introduction to Deep Learning
42
CS 502, Fall 2020
Activation: Tanh
β’ Tanh function: takes a real-valued number and βsquashesβ it into range between -1 and 1
β Like sigmoid, tanh neurons saturate
β Unlike sigmoid, the output is zero-centered
βͺ It is therefore preferred than sigmoid
β Tanh is a scaled sigmoid: tanh(π₯)=2Ο(2π₯)β1
βπ β β1,1
Slide credit: Ismini Lourentzou β Introduction to Deep Learning
43
CS 502, Fall 2020
Activation: ReLU
β’ ReLU (Rectified Linear Unit): takes a real-valued number and thresholds it at zero
π π₯ = max(0, π₯)βπ β β+
π
β Most modern deep NNs use ReLUactivations
β ReLU is fast to compute
βͺ Compared to sigmoid, tanh
βͺ Simply threshold a matrix at zero
β Accelerates the convergence of gradient descent
βͺ Due to linear, non-saturating form
β Prevents the gradient vanishing problem
44
CS 502, Fall 2020
Activation: Leaky ReLU
β’ The problem of ReLU activations: they can βdieβ
β ReLU could cause weights to update in a way that the gradients can become zero and the neuron will not activate again on any data
β E.g., when a large learning rate is used
β’ Leaky ReLU activation function is a variant of ReLU
β Instead of the function being 0 when π₯ < 0, a leaky ReLU has a small negative slope (e.g., Ξ± = 0.01, or similar)
β This resolves the dying ReLUproblem
β Most current works still use ReLU
βͺ With a proper setting of the learning rate, the problem of dying ReLU can be avoided
π π₯ = απΌπ₯ for π₯ < 0π₯ for π₯ β« 0
45
CS 502, Fall 2020
Activation: Linear Function
β’ Linear function means that the output signal is proportional to the input signal to the neuron
π π₯ = ππ₯
β If the value of the constant c is 1, it is also called identity activation function
β This activation type is used in regression problems
βͺ E.g., the last layer can have linear activation function, in order to output a real number (and not a class membership)
βπ β βπ
46
CS 502, Fall 2020
Training NNs
β’ The network parameters π include the weight matrices and bias vectors from all layers
β’ Training a model to learn a set of parameters π that are optimal (according to a criterion) is one of the greatest challenges in ML
π = π1, π1,π2, π2, β―ππΏ, ππΏ
16 x 16 = 256
1x
2xβ¦
β¦
256xβ¦
β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
y1
y2
y10
0.1
0.7
0.2
is 1
is 2
is 0
Softm
ax
Slide credit: Hung-yi Lee β Deep Learning Tutorial
47
CS 502, Fall 2020
Training NNs
β’ Data preprocessing - helps convergence during training
β Mean subtraction
βͺ Zero-centered data
β Subtract the mean for each individual data dimension (feature)
β Normalization
βͺ Divide each image by its standard deviation
β To obtain standard deviation of 1 for each data dimension (feature)
βͺ Or, scale the data within the range [-1, 1]
Picture from: https://cs231n.github.io/neural-networks-2/
48
CS 502, Fall 2020
Training NNs
β’ To train a NN, set the parameters π such that for a training subset of images, the corresponding elements in the predicted output have maximum values
y1 has the maximum valueInput:
y2 has the maximum valueInput:...
Input: y9 has the maximum value
Input: y10 has the maximum value
Slide credit: Hung-yi Lee β Deep Learning Tutorial
49
CS 502, Fall 2020
Training NNs
β’ Define an objective function/cost function/loss function β π that calculates the difference between the model prediction and the true label
β E.g., β π can be mean-squared error, cross-entropy, etc.
1x
2x
β¦β¦
256x
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
y1
y2
y10
Cost
0.2
0.3
0.5
β¦β¦
1
0
0
β¦β¦
True label β1β
β(π)
β¦β¦
Slide credit: Hung-yi Lee β Deep Learning Tutorial
50
CS 502, Fall 2020
Training NNs
β’ For n training images, calculate the total loss: β π = Οπ=1π βπ π
β’ Find the optimal NN parameters πβ that minimize the total loss β π
x1
x2
xN
NN
NN
NN
β¦β¦
β¦β¦
y1
y2
yN
ΰ·π¦1
ΰ·π¦2
ΰ·π¦π
β1 π
β¦β¦
β¦β¦
x3 NN y3ΰ·π¦3
β2 π
β3 π
βπ π
Slide credit: Hung-yi Lee β Deep Learning Tutorial
51
CS 502, Fall 2020
Training NNs
β’ Optimizing the loss function β π
β Almost all DL models these days are trained with a variant of the gradient descent (GD) algorithm
β GD applies iterative refinement of the network parameters π
β GD uses the opposite direction of the gradient of the loss with respect to the NN parameters (i.e.,π»β π = Ξ€πβ πππ ) for updating π
βͺ The gradient of the loss function π»β π gives the direction of fastest increase of the loss function β π when the parameters π are changed
β π
ππ
πβ
πππ
52
CS 502, Fall 2020
Training NNs
β’ The loss functions for most DL tasks are defined over very high-dimensional spaces
β E.g., ResNet50 NN has about 23 million parameters
β This makes the loss function impossible to visualize
β’ We can still gain intuitions by studying 1-dimensional and 2-dimensional examples of loss functions
1D loss (the minimum point is obvious) 2D loss (blue = low loss, red = high loss)
Picture from: https://cs231n.github.io/optimization-1/
53
CS 502, Fall 2020
Gradient Descent Algorithm
β’ Steps in the gradient descent algorithm:
1. Randomly initialize the model parameters, π0
βͺ In the figure, the parameters are denoted π€
2. Compute the gradient of the loss function at π0: π»β π0
3. Update the parameters as: ππππ€ = π0 β πΌπ»β π0
βͺ Where Ξ± is the learning rate
4. Go to step 2 and repeat (until a terminating criterion is reached)
54
CS 502, Fall 2020
Gradient Descent Algorithm
β’ Example: a NN with only 2 parameters π€1 and π€2, i.e., π = π€1, π€2
β Different colors are the values of the loss (minimum loss πβ is β 1.3)
π€1
π€2
2. Compute the gradient at π0, π»β π0
π0
3. Times the learning rate π, and update π,ππππ€ = π0 β πΌπ»β π0
π1
1. Randomly pick a starting point π0
4. Go to step 2, repeatβπ»β π0
π1 =π0 β πΌπ»β π0
πβ
π»β π0 =πβ π0 /ππ€1πβ π0 /ππ€2
Slide credit: Hung-yi Lee β Deep Learning Tutorial
55
CS 502, Fall 2020
Gradient Descent Algorithm
β’ Example (contd.)
π€1
π€2
2. Compute the gradient at π0,π»β π0
π0
3. Times the learning rate π, and update π,ππππ€ = π0 β πΌπ»β π0
π1
π1 β πΌπ»β π1π2 β πΌπ»β π2
π2
Eventually, we would reach a minimum β¦..
1. Randomly pick a starting point π0
4. Go to step 2, repeat
Slide credit: Hung-yi Lee β Deep Learning Tutorial
56
CS 502, Fall 2020
Gradient Descent Algorithm
β’ Gradient descent algorithm stops when a local minimum of the loss surface is reached
β GD does not guarantee reaching a global minimum
β However, empirical evidence suggests that GD works well for NNs
β π
π
Picture from: https://blog.paperspace.com/intro-to-optimization-in-deep-learning-gradient-descent/
57
CS 502, Fall 2020
Gradient Descent Algorithm
β’ For most tasks, the loss surface β π is highly complex (and non-convex)
β
π€1 π€2
β’ Random initialization in NNs results in different initial parameters π0
β Gradient descent may reach different minima at every run
β Therefore, NN will produce different predicted outputs
β’ Currently, we donβt have an algorithm that guarantees reaching a global minimum for an arbitrary loss function
Slide credit: Hung-yi Lee β Deep Learning Tutorial
58
CS 502, Fall 2020
Backpropagation
β’ How to calculate the gradients of the loss function in NNs?
β’ There are two ways:
1. Numerical gradient: slow, approximate, but easy way
2. Analytic gradient: requires calculus, fast, but more error-prone way
β’ In practice the analytic gradient is used
β Analytical differentiation for gradient computation is available in almost all deep learning libraries
59
CS 502, Fall 2020
Mini-batch Gradient Descent
β’ It is wasteful to compute the loss over the entire set to perform a single parameter update for large datasets
β E.g., ImageNet has 14M images
β GD (a.k.a. vanilla GD) is replaced with mini-batch GD
β’ Mini-batch gradient descent
β Approach:
βͺ Compute the loss β π on a batch of images, update the parameters π, and repeat until all images are used
βͺ At the next epoch, shuffle the training data, and repeat above process
β Mini-batch GD results in much faster training
β Typical batch size: 32 to 256 images
β It works because the examples in the training data are correlated
βͺ I.e., the gradient from a mini-batch is a good approximation of the gradient of the entire training set
60
CS 502, Fall 2020
Stochastic Gradient Descent
β’ Stochastic gradient descent
β SGD uses mini-batches that consist of a single input example
βͺ E.g., one image mini-batch
β Although this method is very fast, it may cause significant fluctuations in the loss function
βͺ Therefore, it is less commonly used, and mini-batch GD is preferred
β In most DL libraries, SGD is typically a mini-batch SGD (with an option to add momentum)
61
CS 502, Fall 2020
Problems with Gradient Descent
β’ Besides the local minima problem, the GD algorithm can be very slow at plateaus, and it can get stuck at saddle points
cost β π
Very slow at the plateau
Stuck at a local minimum
π»β π = 0
Stuck at a saddle point
π»β π = 0π»β π β 0
πSlide credit: Hung-yi Lee β Deep Learning Tutorial
62
CS 502, Fall 2020
Gradient Descent with Momentum
β’ Gradient descent with momentum uses the momentum of the gradient for parameter optimization
Movement = Negative of Gradient + Momentum
Gradient = 0
Negative of Gradient
Momentum
Real Movement
cost β π
π
Slide credit: Hung-yi Lee β Deep Learning Tutorial
63
CS 502, Fall 2020
Gradient Descent with Momentum
β’ Parameters update in GD with momentum : ππππ€ = ππππ β ππππ€
βͺ Where: ππππ€= π½ππππ + πΌπ»β ππππ
β’ Compare to vanilla GD: ππππ€ = ππππ β πΌπ»β ππππ
β’ The term ππππ€ is called momentum
β This term accumulates the gradients from the past several steps
β It is similar to a momentum of a heavy ball rolling down the hill
β’ The parameter π½ referred to as a coefficient of momentum
β A typical value of the parameter π½ is 0.9
β’ This method updates the parameters π in the direction of the weighted average of the past gradients
64
CS 502, Fall 2020
Nesterov Accelerated Momentum
β’ Gradient descent with Nesterov accelerated momentum
β Parameters update: ππππ€ = ππππ β ππππ€
βͺ Where: ππππ€= π½ππππ + πΌπ»β ππππ β π½ππππ
β The term ππππ β π½ππππ allows us to predict the position of the parameters in the next step (i.e., ππππ₯π‘ β ππππ β π½ππππ)
β The gradient is calculated with respect to the approximate future position of the parameters in the next step, ππππ₯π‘
Picture from: https://towardsdatascience.com/learning-parameters-part-2-a190bef2d12
GD with momentumGD with Nesterov
momentum
65
CS 502, Fall 2020
Learning Rate
β’ Learning rate
β The gradient tells us the direction in which the loss has the steepest rate of increase, but it does not tell us how far along the opposite direction we should step
β Choosing the learning rate (also called the step size) is one of the most important hyper-parameter settings for NN training
LR too small
LR too large
66
CS 502, Fall 2020
Learning Rate
β’ Training loss for different learning rates
β High learning rate: the loss increases or plateaus too quickly
β Low learning rate: the loss decreases too slowly (takes many epochs to reach a solution)
Picture from: https://cs231n.github.io/neural-networks-3/
67
CS 502, Fall 2020
Annealing the Learning Rate
β’ Reduce the learning rate over time (learning rate decay)
β Approach 1
βͺ Reduce the learning rate by some factor every few epochs
β Typical values: reduce the learning rate by a half every 5 epochs, or by 10 every 20 epochs
β Exponential decay reduces the learning rate exponentially over time
β These numbers depend heavily on the type of problem and the model
β Approach 2
βͺ Reduce the learning rate by a constant (e.g., by half) whenever the validation loss stops improving
β In TensorFlow: tf.keras.callbacks.ReduceLROnPleateau()
Β» Monitor: validation loss
Β» Factor: 0.1 (i.e., divide by 10)
Β» Patience: 10 (how many epochs to wait before applying it)
Β» Minimum learning rate: 1e-6 (when to stop)
68
CS 502, Fall 2020
Adam
β’ Adaptive Moment Estimation (Adam)
β Adam computes adaptive learning rates for each dimension of π
βͺ Similar to GD with momentum, Adam computes a weighted average of
past gradients, i.e., ππππ€= π½1ππππ + 1 β π½1 π»β ππππ
βͺ Adam also computes a weighted average of past squared gradients, i.e.,
ππππ€= π½2ππππ + 1 β π½2 π»β ππππ
2
β The parameters update is: ππππ€ = ππππ βπΌ
ππππ€+πππππ€
βͺ Where: ππππ€ =ππππ€
1βπ½1and ππππ€ =
ππππ€
1βπ½2
βͺ The proposed default values are π½1 = 0.9, π½2 = 0.999, and π = 10β8
β’ Other commonly used optimization methods include:
β Adagrad, Adadelta, RMSprop, Nadam, etc.
β Most papers nowadays used Adam and SGD with momentum
69
CS 502, Fall 2020
Vanishing Gradient Problem
β’ In some cases, during training, the gradients can become either very small (vanishing gradients) of very large (exploding gradients)
β They result in very small or very large update of the parameters
β Solutions: ReLU activations, regularization, LSTM units in RNNs
1x
2x
β¦β¦
Nx
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
β¦β¦
y1
y2
yM
Small gradients, learns very slowSlide credit: Hung-yi Lee β Deep Learning Tutorial
70
CS 502, Fall 2020
Loss Functions
β’ Classification tasks
Training examples
βπ Γ ππππ π 1, β¦ , ππππ π π (one-hot encoding)
Output Layer
Softmax Activation[maps βπ to a probability distribution]
Loss function Cross-entropy β π = β1
π
π=1
π
π=1
πΎ
π¦π(π)log ΰ·π¦π
(π)+ 1 β π¦π
(π)log 1 β ΰ·π¦π
π
Slide credit: Ismini Lourentzou β Introduction to Deep Learning
71
CS 502, Fall 2020
Loss Functions
β’ Regression tasks
Training examples
Output Layer
Loss functionMean Squared Error β π =
1
π
π=1
π
π¦(π) β ΰ·π¦(π)2
Linear (Identity) or Sigmoid Activation
βπ Γ βπ
Mean Absolute Error β π =1
π
π=1
π
π¦(π) β ΰ·π¦(π)
Slide credit: Ismini Lourentzou β Introduction to Deep Learning
72
CS 502, Fall 2020
Generalization
β’ Underfitting
β The model is too βsimpleβ to represent all the relevant class characteristics
β Model with too few parameters
β High error on the training set and high error on the testing set
β’ Overfitting
β The model is too βcomplexβ and fits irrelevant characteristics (noise) in the data
β Model with too many parameters
β Low error on the training error and high error on the testing set
Blue line β decision boundary by the modelGreen line β optimal decision boundary
73
CS 502, Fall 2020
Overfitting
β’ A model with high capacity fits the noise in the data instead of the underlying relationship
Picture from: http://cs231n.github.io/assets/nn1/layer_sizes.jpeg
β’ The model may fit the training data very well, but fails to generalize to new examples (test data)
74
CS 502, Fall 2020
Regularization: Weight Decay
β’ βπ weight decay
β A regularization term that penalizes large weights is added to the loss function
βπππ π = β π + π
π
ππ2
β For every weight in the network, we add the regularization term to the loss value
βͺ During gradient descent parameter update, every weight is decayed linearly toward zero
β The weight decay coefficient π determines how dominant the regularization is during the gradient computation
Data loss Regularization loss
75
CS 502, Fall 2020
Regularization: Weight Decay
β’ Effect of the decay coefficient π
β Large weight decay coefficient β penalty for weights with large values
76
CS 502, Fall 2020
Regularization: Weight Decay
β’ βπ weight decay
β The regularization term is based on the β1 norm of the weights
βπππ π = β π + πΟπ ππ
β β1 weight decay is less common with NN
βͺ Often performs worse than β2 weight decay
β It is also possible to combine β1 and β2 regularization
βͺ Called elastic net regularization
βπππ π = β π + π1 Οπ ππ + π2 Οπ ππ2
77
CS 502, Fall 2020
Regularization: Dropout
β’ Dropout
β Randomly drop units (along with their connections) during training
β Each unit is retained with a fixed dropout rate p, independent of other units
β The hyper-parameter p to be chosen (tuned)
βͺ Often between 20 and 50 % of the units are dropped
Slide credit: Hung-yi Lee β Deep Learning Tutorial
78
CS 502, Fall 2020
Regularization: Dropout
β’ Dropout is a kind of ensemble learningβ Using one mini-batch to train one network with a slightly different
architecture
minibatch1
minibatch2
minibatch3
minibatchn
β¦β¦
Slide credit: Hung-yi Lee β Deep Learning Tutorial
79
CS 502, Fall 2020
Regularization: Early Stopping
β’ Early-stopping
β During model training, use a validation set, along with a training set
βͺ A ratio of about 25% to 75% of the data is often used
β Stop when the validation accuracy (or loss) has not improved after nsubsequent epochs
βͺ The parameter n is called patience
Stop training
validation
80
CS 502, Fall 2020
Batch Normalization
β’ Batch normalization layers act similar to the data preprocessing steps mentioned earlier
β They calculate the mean ΞΌ and variance Ο of a batch of input data, and normalize the data x to a zero mean and unit variance
β I.e., ΰ·π₯ =π₯βπ
π
β’ BatchNorm layers alleviate the problems of proper initialization of the parameters and hyper-parameters
β Result in faster convergence training, allow larger learning rates
β Reduce the internal covariate shift
β’ The BatchNorm layers are inserted immediately after convolutional layers or fully-connected layers, and before activation layers
β They are very common with convolutional NNs
81
CS 502, Fall 2020
Hyper-parameter Tuning
β’ Training NNs can involve many hyper-parameter settings
β’ The most common hyper-parameters include:
β Number of layers, and number of neurons per layer
β Initial learning rate
β Learning rate decay schedule (e.g., decay constant)
β’ Other hyper-parameters may include:
β Regularization parameters (β2 penalty, dropout rate)
β Batch size
β’ Hyper-parameter tuning can be time-consuming for larger NNs
82
CS 502, Fall 2020
Hyper-parameter Tuning
β’ Grid search
β Check all values in a range with a step value
β’ Random search
β Randomly sample values for the parameter
β Often preferred to grid search
β’ Bayesian hyper-parameters optimization
β Is an active area of research
83
CS 502, Fall 2020
k-Fold Cross-Validation
β’ Using k-fold cross-validation for hyper-parameter tuning is common when the size of the training data is small
β It leads to a better and less noisy estimate of the model performance by averaging the results across several folds
β’ E.g., 5-fold cross-validation (see the figure on the next slide)
1. Split the train data into 5 equal folds
2. First use folds 2-5 for training and fold 1 for validation
3. Repeat by using fold 2 for validation, then fold 3, fold 4, and fold 5
4. Average the results over the 5 runs
5. Once the best hyper-parameters are determined, evaluate the model on the set aside test data
84
CS 502, Fall 2020
k-Fold Cross-Validation
β’ Illustration of a 5-fold cross-validation
Picture from: https://scikit-learn.org/stable/modules/cross_validation.html
85
CS 502, Fall 2020
Ensemble Learning
β’ Ensemble learning is training multiple classifiers separately and combining their predictions
β Ensemble learning often outperforms individual classifiers
β Better results obtained with higher model variety in the ensemble
β Bagging (bootstrap aggregating)
βͺ Randomly draw subsets from the training set (i.e., bootstrap samples)
βͺ Train separate classifiers on each subset of the training set
βͺ Perform classification based on the average vote of all classifiers
β Boosting
βͺ Train a classifier, and apply weights on the training set (apply higher weights on misclassified examples, focus on βhard examplesβ)
βͺ Train new classifier, reweight training set according to prediction error
βͺ Repeat
βͺ Perform classification based on weighted vote of the classifiers
86
CS 502, Fall 2020
Deep vs Shallow Networks
β’ Deeper networks perform better than shallow networks
β But only up to some limit: after a certain number of layers, the performance of deeper networks plateaus
1x 2x β¦β¦Nx
Deep
1x 2x β¦β¦Nx
β¦β¦
Shallow
Slide credit: Hung-yi Lee β Deep Learning Tutorial
87
CS 502, Fall 2020
Convolutional Neural Networks (CNNs)
β’ Convolutional neural networks (CNNs) were primarily designed for image data
β’ CNNs use a convolutional operator for extracting data features
β Allows parameter sharing
β Efficient to train
β Have less parameters than NNs with fully-connected layers
β’ CNNs are robust to spatial translations of objects in images
β’ A convolutional filter slides (i.e., convolves) across the image
Input matrix
Convolutional 3x3 filter
Picture from: http://deeplearning.stanford.edu/wiki/index.php/Feature_extraction_using_convolution
88
CS 502, Fall 2020
Convolutional Neural Networks (CNNs)
β’ When the convolutional filters are scanned over the image, they capture useful features
β E.g., edge detection by convolutions
Filter
1 1 1 1 1 1 0.015686 0.015686 0.011765 0.015686 0.015686 0.015686 0.015686 0.964706 0.988235 0.964706 0.866667 0.031373 0.023529 0.007843
0.007843 0.741176 1 1 0.984314 0.023529 0.019608 0.015686 0.015686 0.015686 0.011765 0.101961 0.972549 1 1 0.996078 0.996078 0.996078 0.058824 0.015686
0.019608 0.513726 1 1 1 0.019608 0.015686 0.015686 0.015686 0.007843 0.011765 1 1 1 0.996078 0.031373 0.015686 0.019608 1 0.011765
0.015686 0.733333 1 1 0.996078 0.019608 0.019608 0.015686 0.015686 0.011765 0.984314 1 1 0.988235 0.027451 0.015686 0.007843 0.007843 1 0.352941
0.015686 0.823529 1 1 0.988235 0.019608 0.019608 0.015686 0.015686 0.019608 1 1 0.980392 0.015686 0.015686 0.015686 0.015686 0.996078 1 0.996078
0.015686 0.913726 1 1 0.996078 0.019608 0.019608 0.019608 0.019608 1 1 0.984314 0.015686 0.015686 0.015686 0.015686 0.952941 1 1 0.992157
0.019608 0.913726 1 1 0.988235 0.019608 0.019608 0.019608 0.039216 0.996078 1 0.015686 0.015686 0.015686 0.015686 0.996078 1 1 1 0.007843
0.019608 0.898039 1 1 0.988235 0.019608 0.015686 0.019608 0.968628 0.996078 0.980392 0.027451 0.015686 0.019608 0.980392 0.972549 1 1 1 0.019608
0.043137 0.905882 1 1 1 0.015686 0.035294 0.968628 1 1 0.023529 1 0.792157 0.996078 1 1 0.980392 0.992157 0.039216 0.023529
1 1 1 1 1 0.992157 0.992157 1 1 0.984314 0.015686 0.015686 0.858824 0.996078 1 0.992157 0.501961 0.019608 0.019608 0.023529
0.996078 0.992157 1 1 1 0.933333 0.003922 0.996078 1 0.988235 1 0.992157 1 1 1 0.988235 1 1 1 1
0.015686 0.74902 1 1 0.984314 0.019608 0.019608 0.031373 0.984314 0.023529 0.015686 0.015686 1 1 1 0 0.003922 0.027451 0.980392 1
0.019608 0.023529 1 1 1 0.019608 0.019608 0.564706 0.894118 0.019608 0.015686 0.015686 1 1 1 0.015686 0.015686 0.015686 0.05098 1
0.015686 0.015686 1 1 1 0.047059 0.019608 0.992157 0.007843 0.011765 0.011765 0.015686 1 1 1 0.015686 0.019608 0.996078 0.023529 0.996078
0.019608 0.015686 0.243137 1 1 0.976471 0.035294 1 0.003922 0.011765 0.011765 0.015686 1 1 1 0.988235 0.988235 1 0.003922 0.015686
0.019608 0.019608 0.027451 1 1 0.992157 0.223529 0.662745 0.011765 0.011765 0.011765 0.015686 1 1 1 0.015686 0.023529 0.996078 0.011765 0.011765
0.015686 0.015686 0.011765 1 1 1 1 0.035294 0.011765 0.011765 0.011765 0.015686 1 1 1 0.015686 0.015686 0.964706 0.003922 0.996078
0.007843 0.019608 0.011765 0.054902 1 1 0.988235 0.007843 0.011765 0.011765 0.015686 0.011765 1 1 1 0.015686 0.015686 0.015686 0.023529 1
0.007843 0.007843 0.015686 0.015686 0.960784 1 0.490196 0.015686 0.015686 0.015686 0.007843 0.027451 1 1 1 0.011765 0.011765 0.043137 1 1
0.023529 0.003922 0.007843 0.023529 0.980392 0.976471 0.039216 0.019608 0.007843 0.019608 0.015686 1 1 1 1 1 1 1 1 1
0 1 0
1 -4 1
0 1 0
Input Image Convoluted Image
Slide credit: Param Vir Singh β Deep Learning
89
CS 502, Fall 2020
Convolutional Neural Networks (CNNs)
β’ In CNNs, hidden units in a layer are only connected to a small region of the layer before it (called local receptive field)
β The depth of each feature map corresponds to the number of convolutional filters used at each layer
Input Image
Layer 1
Feature Map Layer 2
Feature Map
w1 w2
w3 w4 w5 w6
w7 w8
Filter 1
Filter 2
Slide credit: Param Vir Singh β Deep Learning
90
CS 502, Fall 2020
Convolutional Neural Networks (CNNs)
β’ Max pooling: reports the maximum output within a rectangular neighborhood
β’ Average pooling: reports the average output of a rectangular neighborhood
β’ Pooling layers reduce the spatial size of the feature maps
β Reduce the number of parameters, prevent overfitting
1 3 5 3
4 2 3 1
3 1 1 3
0 1 0 4
MaxPool with a 2Γ2 filter with stride of 2
Input Matrix
Output Matrix
4 5
3 4
Slide credit: Param Vir Singh β Deep Learning
91
CS 502, Fall 2020
Convolutional Neural Networks (CNNs)
β’ Feature extraction architecture
β After 2 convolutional layers, a max-pooling layer reduces the size of the feature maps (typically by 2)
β A fully convolutional and a softmax layers are added last to perform classification
64
64
128
128
256
256
256
512
512
512
512
512
512
Co
nv
laye
r
Max
Po
ol
Fully Connected Layer
Living Room
Bed Room
Kitchen
Bathroom
Outdoor
Slide credit: Param Vir Singh β Deep Learning
92
CS 502, Fall 2020
Residual CNNs
β’ Residual networks (ResNets)
β Introduce βidentityβ skip connections
βͺ Layer inputs are propagated and added to the layer output
βͺ Mitigate the problem of vanishing gradients during training
βͺ Allow training very deep NN (with over 1,000 layers)
β Several variants exist: 18, 34, 50, 101, 152, and 200 layers
β Are used as base models of other state-of-the-art NNs
βͺ Other similar models: ResNeXT, DenseNet
93
CS 502, Fall 2020
Recurrent Neural Networks (RNNs)
β’ Recurrent NNs are used for modeling sequential data and data with varying length of inputs and outputs
β Videos, text, speech, DNA sequences, human skeletal data
β’ RNNs introduce recurrent connections between the neurons units
β This allows processing sequential data one element at a time by selectively passing information across a sequence
β Memory of the previous inputs is stored in the modelβs internal state and affect the model predictions
β Can capture correlations in sequential data
β’ RNNs use backpropagation-through-time for training
β’ RNNs are more sensitive to the vanishing gradient problem
94
CS 502, Fall 2020
Recurrent Neural Networks (RNNs)
β’ RNNs can have one of many inputs and one of many outputs
A person riding a motorbike on dirt road
Awesome movie. Highly recommended. Positive
Happy Diwali ΰ€Άΰ₯ΰ€ ΰ€¦ΰ₯ΰ€ͺΰ€Ύΰ€΅ΰ€²ΰ₯
Image Captioning
Sentiment Analysis
Machine Translation
RNN Application Input Output
Slide credit: Param Vir SInghβ Deep Learning
95
CS 502, Fall 2020
Recurrent Neural Networks (RNNs)
β’ RNN use same set of weights π€β and biases π€π₯ across all time steps
β’ An RNN is shown rolled over time
x1
h0 πβ()π€β
π€π₯
h1
x2
πβ()π€β
π€π₯
h2
x3
πβ()π€β
π€π₯
h3 ππ¦()π€π¦
OUTPUT
β π‘ = πβ π€β β β π‘ β 1 + π€π₯ β π₯ π‘
Slide credit: Param Vir Singh β Deep Learning
96
CS 502, Fall 2020
Bidirectional RNNs
β’ Bidirectional RNNs incorporate both forward and backward passes through sequential data
β The output may not only depend on the previous elements in the sequence, but also on future elements in the sequence
β It resembles two RNNs stacked on top of each other
βπ‘ = π(π(ββ)βπ‘+1 +π(βπ₯)π₯π‘)
βπ‘ = π(π(ββ)βπ‘β1 +π(βπ₯)π₯π‘)
π¦π‘ = π βπ‘; βπ‘
Output both past and future elements
Slide credit: Param Vir Singh β Deep Learning
97
CS 502, Fall 2020
LSTM Networks
β’ Long Short Term Memory (LSTM) networks are a variant of RNNs
β’ LSTM mitigates the vanishing/exploding gradient problem
β Solution: a Memory Cell, updated at each step in the sequence
β’ Three gates control the flow of information to and from the Memory Cell
β Input Gate: protects the current step from irrelevant inputs
β Output Gate: prevents current step from passing irrelevant information to later steps
β Forget Gate: limits information passed from one cell to the next
β’ Most modern RNN models use either LSTM units or other more advanced types of recurrent units (e.g., GRU units)
98
CS 502, Fall 2020
LSTM Networks
β’ LSTM cell
β Input gate, output gate, forget gate, memory cell
β LSTM can learn long-term correlations within the data sequences
99
CS 502, Fall 2020
References
1. Hung-yi Lee β Deep Learning Tutorial
2. Ismini Lourentzou β Introduction to Deep Learning
3. CS231n Convolutional Neural Networks for Visual Recognition (Stanford CS course) (link)
4. James Hays, Brown β Machine Learning Overview
5. Param Vir Singh, Shunyuan Zhang, Nikhil Malik β Deep Learning
6. Sebastian Ruder β An Overview of Gradient Descent Optimization Algorithms (link)