Docsity

Deep Learning: Architectures, Techniques, and Applications - Prof. Sperduti, Sintesi del corso di Machine learning

Toggle sidebar
bg1
Tutto Deep learning
Gradient-based optimization
The function we want to minimize or maximize is called the objective function or criterion. When we are
minimizing it, we may also call it the cost function, loss function, or error function.
Suppose we have a function y = f(x) where x is a single variable and y is a number.
The derivate f’(x) gives the slope of f (x) at the point x. The derivative is therefore useful for minimizing a
function because it tells us how to change x in order to make a small improvement in y. Se x>0 allora la
derivata è positiva e si può diminuire la funziona andando verso sinistra, viceversa se x<0.
Ergo: We can thus reduce f (x) by moving x in small steps with opposite sign of the derivative. This
technique is called gradient descent.
With gradient descent we want to find the minimum given a function f(x). In fact we want to decrease the
function moving in the direction of negative gradient. In order to do that we need to compute the
gradient(derivative) ∇xf(x). The idea is to start with a random value for x and then you update x’ doing a
little step in the oppisite direction w.r.t. the gradient x’=x- αJ’(z) and then you repeat this last step until
convergence(i.e. gradient very small). Alpha>0 is the learning rate.
When f’(x) = 0, the derivative provides no information about which direction to move. Points where f’(x) = 0
are known as critical points or stationary points. Comprendono max, min e saddle points.
• A local minimum is a point where f(x) is lower than at all neighboring points, so it is no longer
possible to decrease f(x) by making infinitesimal steps
• A local maximum is a point where f(x) is higher than at all neighboring points, so it is not possible to
increase f(x) by making infinitesimal steps.
• Some critical points are neither maxima nor minima. These are known as saddle points.
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

Anteprima parziale del testo

Scarica Deep Learning: Architectures, Techniques, and Applications - Prof. Sperduti e più Sintesi del corso in PDF di Machine learning solo su Docsity!

Tutto Deep learning

Gradient-based optimization

The function we want to minimize or maximize is called the objective function or criterion. When we are minimizing it, we may also call it the cost function, loss function, or error function. Suppose we have a function y = f(x) where x is a single variable and y is a number. The derivate f’(x) gives the slope of f (x) at the point x. The derivative is therefore useful for minimizing a function because it tells us how to change x in order to make a small improvement in y. Se x>0 allora la derivata è positiva e si può diminuire la funziona andando verso sinistra, viceversa se x<0. Ergo: We can thus reduce f (x) by moving x in small steps with opposite sign of the derivative. This technique is called gradient descent. With gradient descent we want to find the minimum given a function f(x). In fact we want to decrease the function moving in the direction of negative gradient. In order to do that we need to compute the gradient(derivative) ∇xf(x). The idea is to start with a random value for x and then you update x’ doing a little step in the oppisite direction w.r.t. the gradient x’=x- αJ’(z) and then you repeat this last step until convergence(i.e. gradient very small). Alpha>0 is the learning rate. When f’(x) = 0, the derivative provides no information about which direction to move. Points where f’(x) = 0 are known as critical points or stationary points. Comprendono max, min e saddle points.

  • A local minimum is a point where f(x) is lower than at all neighboring points, so it is no longer possible to decrease f(x) by making infinitesimal steps
  • A local maximum is a point where f(x) is higher than at all neighboring points, so it is not possible to increase f(x) by making infinitesimal steps.
  • Some critical points are neither maxima nor minima. These are known as saddle points.

A point that obtains the absolute lowest value of f(x) is a global minimum. It is possible for there to be only one global minimum or multiple global minima of the function. It is also possible for there to be local minima that are not globally optimal but also is an acceptable halting point. It depends on the point. For functions with multiple inputs, we must make use of the concept of partial derivatives (∂/∂xi)f(x). The gradient is related to the derivation with respect of a vector x=[x1,x2,..,xm]. The gradient of a function f is basically a row vector denoted as ∇xf(x) that contains all the partial derivatives of the corrisponding component in the vector x. Per fare i conti e calcolare il gradiente devo usare le regole di derivazione solite(sum,product,chain rule ecc) ma in questo caso dato che ci sono più variabili(multiple inputs) quando faccio la derivata considero le altre come costanti. La chain rule consiste praticamente nel dividere una funzione h in due funzioni f e g e cacolare le loro derivate parziali. Queste poi fanno parte del gradiente. Jacobian matrix: The matrix containing all such partial derivatives(If input and output are both vectors). Second derivatives 𝑓’’(𝑥) measures the curvature of a function. Hessian matrix: The matrix of second derivatives (the Jacobian of the gradient). Condition number of the Hessian matrix is the ratio of the largest eigenvalue to the smalles that tells us how much the second derivatives differ from one to each other(how different is the curve in different dimension):

  • Gradient descent is a first order method, so it ignores information in the hessian.
  • second-order optimization algorithms (such as Newton’s method) considers the Hessian
  • Slow (need to compute Hessian) so not widely used for deep learning We can solve a constrained problem using unconstrained optimization (The Karush–Kuhn–Tucker (KKT) approach provides a very general solution to constrained optimization). Underfitting: occurs when the model is not able to obtain a sufficiently low error value on the training set. Overfitting: occurs when the gap between the training error and test error is too large. The learning rate: is a tuning parameter in an optimization algorithm that determines the step size at each iteration while moving toward a minimum of a loss function. Usually a small constant value. Maximum likelihood estimation: a method of estimating the parameters of a probability distribution by maximizing a likelihood function(measures the goodness of fit of a statistical model to a sample of data for) given values of the unknown parameters. It is formed from the joint probability distribution of the sample, but viewed and used as a function of the parameters only, thus treating the random variables as fixed at the observed values), so that under the assumed statistical model the observed data is most probable. In fact it is the principled way to derive estimators (models). Maximum likelihood provides a guide to design almost any output layer. TLDR: Modo per stimare i parametri dei modelli. Mean squared error: the mean squared error of an estimator (of a procedure for estimating an unobserved quantity) measures the average of the squares of the errors—that is, the average squared difference between the estimated values and the actual value. Epoch: means a step on the entire training set. Batch: means that you use all your data to calculate the gradient during an iteration. Mini-batch: means that you take a subset of all your data during one iteration.

Deep Feedforward Networks

An Artificial Neural Network is a system consisting of interconnected units that compute nonlinear (numerical) functions:

  • input units represent input variables;
  • output units represent output variables;
  • hidden units (if present) represent internal variables thatcodify (after learning) correlations among input and desired output variables.
  • adjustable weights are associated to connections among units. The goal of a feedforward network is to approximate some function f∗. The model is associated with a directed acyclic graph describing how the functions are composed together. For example, we might have three functions f(1), f(2), and f(3) connected in a chain, to form f(x) = f(3)(f(2)(f(1)(x))). In this case, f(1) is called the first layer of the network, f(2) is called the second layer, and so on. The overall length of the chain gives the depth (Empirically, greater depth seem to result in better generalization) of the model. The final layer of a feedforward network is called the output layer. We can think the output layer as a linear model and the last hidden layer as providing a non linear representation of the input(praticamente l’output alla fine ti fornisce il risultato). The training examples specify directly what the output layer must do at each pointx; it must produce a value that is close to y. We can also think of the layer as consisting of many units that act in parallel, each representing a vector-to-scalar function. Each unit resembles a neuron in the sense that it receives input from many other units and computes its own activation value. Deeper networks that have less parameters generalize better but hare harder to train. Ideal architecture should be validated (validation set). The following are advantages of using deep neural networks over shallow ones:
  • The number of neurons required at each layer in a deep network may be exponentially smaller compared to the neurons required for a shallow network and A deep network tend to overfit less than a wider shallow network(i.e. a shallow network with more neurons) Hidden layers: the hidden layers perform nonlinear transformations of the inputs entered into the network. They allow you to model complex data thanks to their nodes/neurons. They are “hidden” because the true values of their nodes are unknown in the training dataset. Each hidden layer of the network is typically vector-valued(Non nelle CNN). The dimensionality of these hidden layers determines the width of the model. Activation function: the activation function of a node defines the output of that node given an input or set of inputs. It is used to determine the output of neural network like yes or no. It maps the resulting values in between 0 to 1 or - 1 to 1 etc. The Nonlinear Activation Functions are the most used activation functions. It makes it easy for the model to generalize or adapt with variety of data and to differentiate between the output. Examples are relu or sigmoid. TLDR: will be used to compute the hidden layer values.

Cost function: A cost function is a measure of error between what value your model predicts and what the value actually is. For example, say we wish to predict the value yi for data point xi. The cost function choice is tightly coupled with the choice of output units. Most of the times, we simply use cross-entropy between data and model distributions. The choice of how to represent output determines the form of the cross- entropy function. Why do we need non linearity? Consider a network with n layers. If the functions f(i) are linear, we can represent them as a matrix multiplication so the deep network would be linear, i.e. it is equivalent to a single-layer network. The non-linearity in neural networks makes the problem non-convex. (Linear models are formulated as convex model). Neural networks face the "credit assignment problem" in situations in which only incomplete performance evaluations are available. The credit assignment problem is that a network should assign credit or blame for its behaviors according to the contribution to the network performance. (It is not clear how to assign “credit” or “blame” to the hidden units). A possibile solution is to make a single neuron derivable and exploit the Gradient Descent technique to learn the “right” weights. Linear units for Gaussian output: Produces the mean of a gaussian distribution. Maximizing the likelihood corresponds to minimize the mean squared error. Sigmoid units for Bernoulli out distr: Many tasks require predicting the value of a binary variable y. Classification problems with two classes can be cast in this form. The maximum-likelihood approach is to define a Bernoulli distribution over y conditioned on. it is better to use a different approach that ensures there is always a strong gradient whenever the model has the wrong answer. This approach is based on using sigmoid output units combined with maximum likelihood. We can think of the sigmoid output unit as having two components. First, it uses a linear layer to compute z = w^(T)h + b. Next, it uses the sigmoid activation function to convert into a probability. Sigmoid is the best way for computing gradient in the case of output layer with binary classification. IT doesn't make sense to use mean squared error if you are using sigmoid(would saturate). The best with sigmoid is negative log likelihood loss. In the end we want to have the gradient big when we are predicting wrong and a small gradient when we are doing a good prediction. Softmax for Multinoulli out distr: Any time we wish to represent a probability distribution over a discrete variable with n possible values, we may use the softmax function. This can be seen as a generalization of the sigmoid function which was used to represent a probability distribution over a binary variable. (So we use this in non binary case). Same approach as before: linear layer to predict log prob. Again, the exp works well when coupled with negative log likelihood. Softmax is a continuous and differentiable argmax. Rectified Linear Units and Their Generalizations: Rectified linear units(RELU) use the activation function g(z)= max{0,z}. Rectified linear units are easy to optimize because they are so similar to linear units. The only difference between a linear unit and a rectified linear unit is that a rectified linear unit outputs zero across half its domain. This makes the derivatives through a rectified linear unit remain large whenever the unit is active. The gradients are not only large but also consistent. The second derivative of the rectifying operation is almost everywhere, and the derivative of the rectifying 0 operation is everywhere that the unit is active. This means that the gradient 1 direction is far more useful for learning than it would be with activation functions that introduce second-order effects. Problems:

  • ReLU does not learn on examples that gives 0 gradient.
  • Some units are nondifferentiable at specific points: return right or left derivative. Principle: models are easier to optimize if their behaviour is close to linear.

Regularization

Many strategies used in machine learning are explicitly designed to reduce the test error, possibly at the expense of increased training error. These strategies are known collectively as regularization. In the context of deep learning, most regularization strategies are based on regularizing estimators. Regularization of an estimator works by trading increased bias for reduced variance. An effective regularizer is one that makes a profitable trade, reducing variance significantly while not overly increasing the bias. Deep neural networks tend to represent very complex functions - > risk of overfitting.

  • Regularization is necessary in some ill-posed ML problems, in general when the solution is not unique
  • Regularization (in particular l2) warrantees that the optimization problem is well-defined
  • Useful to avoid overfitting
  • Regularization reduces the generalization error
  • Regularization increases the inductive bias of the model
  • With Parameter norm penalties, the higher we weight the norm the more the model is regularized Many regularization approaches are based on limiting the capacity of models, such as neural networks, linear regression, or logistic regression, by adding a parameter norm penalty Ω(θ) to the objective function J. Larger values of α correspond to more regularization. Usually we can define alpha with a middle value between 0 and +inf due to apply regularization. We typically choose to use a parameter norm penalty that Ω penalizes of the affine transformation at each layer and leaves only the weights the biases unregularized. L2 Parameter Regularization: The L2 parameter norm penalty is commonly known as weight decay since it makes the weights smaller(shrinked – vengono ridotti) on each step. This regularization strategy drives the weights closer to the origin by adding a regularization term Ω(θ) =1/2 ||w||^2 to the objective function. With this tecnique im defining a prior over my hypothesis space, they are not more equally likely. The hypothesis with smaller weights are more likely(L2-regularization relies on the assumption that a model with small weights is simpler than a model with large weights. The smallness of weights implies that the network behaviour won’t change much if we change a few random inputs here and there which in turn makes it difficult for the regularized network to learn local noise in the data. This forces the network to learn only those features which are seen often across the training set. Weight decay is not applied to the bias.

L1 Regularization: L1 regularization on the model parameter is defined as Ω(θ) =||W|| that is, as the sum of absolute values of the individual parameters. In comparison to L2 regularization, L1 regularization results in a solution that is more sparse. Sparsity in this context refers to the fact that some parameters have an optimal value of zero(many of the weights are 0 so L1-regularization is more likely to create 0- weights.). The sparsity property induced by L1 regularization has been used extensively as a feature selection mechanism. Feature selection simplifies a machine learning problem by choosing which subset of the available features should be used. Why does 𝐿1 reg. enforce sparsity?: L1 norm is defined as the summation of absolute values of a vector’s all components. Now if we draw all points that have a L1 norm equals to a constant c those points should form something that looks like a tilted square(L 2 points with constant norm make a circle) where points are sparse on the tips. Now the way to find a sparse solution is enlarging this shape from the origin by giving an ever-growing c to “touch” the solution line. The intuition is that the touch point is most likely at a tip of the shape. Since the tip is a sparse point, the solution defined by the touch point is also a sparse solution. Not always, but in high-dimensional spaces it is likely that. Data augmentation: The best way to make a machine learning model generalize better is to train it on more data. Of course, in practice, the amount of data we have is limited. One way to get around this problem is to create fake data and add it to the training set.

  • Applying transformations to the training instances
  • Injecting noise in the input examples
  • Noise in the hidden representations → dropout This approach is easiest for classification. A classifier needs to take a complicated, high dimensional input x and summarize it with a single category identity y.This means that the main task facing a classifier is to be invariant to a wide variety of transformations. We can generate new (x, y) pairs easily just by transforming the inputs in our training set. Dataset augmentation has been a particularly effective technique for a specific classification problem: object recognition. Semi-Supervised Learning: In the paradigm of semi-supervised learning, both unlabeled examples from P(x) and labeled examples from P (x ,y ) are used to estimate P (y |x ) or predict y from x. In the context of deep learning, semi-supervised learning usually refers to learning a representation h = f (x). The goal is to learn a representation so that examples from the same class have similar representations. Multi-Task Learning: Multi-task learning is a way to improve generalization by using examples from different (related) tasks. Part of the model is shared across different tasks, and is driven to learn a representation that generalizes well. Assumes shared factors that explain variation in data. Multi-task learning can improve the predictive performance over single-task learning only if the considered tasks are somehow related.

Dropout: Dropout provides an efficient way of performing bagging on neural networks. It’s obtained by removing hidden/input units, we just need to multiply the output of a unit(=neuron) by 0. Formally, Dropout is a regularization technique used in NNs to train an ensemble of networks composed by the original network where all possible combination of units have been set to zero. If using a minibatch training technique, we can sample a binary mask to apply to the output of each neuron and train the resulting network on the minibatch. This is like training each network for just one step, but the weights are shared among all networks in the ensemble. When making predictions, we should average the output of all networks, but since their number is exponential it is unfeasible. If we consider the geometric mean instead, we can approximate the result with the output of the network where the output of each unit is multiplied by the probability of including it. This result is actually exact with a linear network and softmax activation. Dropout is a regularization technique since it forces the network to be strong against hidden units and in some particular cases it can be seen as L2 regularization. Weight scaling inference rule: Multiplying the weights going out from a unit by the probability of including that unit. It has to be done with the dropout. (bisogna aggiornare I pesi) The goal is to make sure that the expected total input to a unit at test time is roughly the same as the expected total input to that unit at train time, even though half the units at train time are missing on average. However, the weight scaling rule is only an approximation for deep models that have nonlinearities. Adversarial training: Adversarial is a machine learning technique that attempts to fool models by supplying deceptive(false) input. Training on adversarial examples is mostly intended to improve security,but can sometimes provide generic regularization.

Optimization for Training Deep Models

This chapter focuses on one particular case of optimization: finding the parameters θ of a neural network that significantly reduce a cost function J(θ). Goal is to optimize a performance measure. Empirical Risk Minimization: The goal of a machine learning algorithm is to reduce the expected generalizationerror given by equation. This quantity is known as the risk. We optimize it indirectlythrough the Loss function on the training set. Prone to overfitting (memorizing training data) Many loss functions (e.g. 0-1 Loss) are not differentiable ‣ → no grandient descent. Surrogate Loss: Sometimes, the loss function we actually care about (say classification error) is not one that can be optimized efficiently. In such situations, one typically optimizes a surrogate loss function instead, which acts as a proxy but has advantages(easier to optimize). E.g. negative log likelihood as surrogate for 0- 1 loss. A very important difference between optimization in general and optimization as we use it for training algorithms is that training algorithms do not usually halt at a local minimum. Batch Algorithms: Optimization algorithms that use the entire training set are called batch or deterministic gradient methods, because they process all of the training examples simultaneously in a large batch. Online methods: Optimization algorithms that use only a single example at a time are sometimes called stochastic or sometimes online methods. Minibatch algorithms: Most algorithms used for deep learning fall somewhere in between, using more than one but less than all of the training examples. These were traditionally called minibatch or minibatch stochastic methods and it is now common to simply call them stochastic methods. Mini-batch gradient descent commonly used for training deep neural networks instead of gradient descent or stochastic (online) gradient descent because:

  • Mini-batch gradient descent estimates the gradient better than online gradient descent
  • The gradient in Mini-batch gradient descent is faster to compute compared to gradient descent
  • The gradient in online gradient descent is too noisy and in gradient descent it may be too slow to compute

Stochastic gradient descent: In SGD we are taking directions that are not exactly the ones given by the gradient but that on average the direction will be similar. As we get closer to the end, it wont end exactly in the local minimum but there’s going to be some noise. The main idea so is that instead of using exactly the gradient we take a random vector with expected value equal to the gradient direction. The sgd converges to a good solution. The main advantage of SGD on GD is that we just need to compute the gradient for a single point and this requires much less computation. Momentum: SGD can be slow. The method of momentum is designed to accelerate learning, especially in the face of high curvature, small but consistent gradients, or noisy gradients. The momentum algorithm accumulates an exponentially decaying moving average of past gradients and continues to move in their direction. The gradient step depends on how aligned the sequence of last gradient. Formally, the momentum algorithm introduces a variable v that plays the role of velocity—it is the direction and speed at which the parameters move through parameter space. The velocity is set to an exponentially decaying average of the negative gradient. Momentum aims primarily to solve two problems: poor conditioning of the Hessian matrix and variance in the stochastic gradient. Nesterov momentum: variant, with gradient evaluated after applying current velocity to 𝜽(the parameter that the algorithm will tweak to achieve acceptable loss). Parameter initialization: DL training algorithms are iterative and depends on initialization so some bad initial points may let the algorithm fail due to numerical instabilities. Starting points with similar training error may have different generalization error (different starting points - > different solutions).

  • Random initialization for weights: ‣ Gaussian or uniform distribution (scale is important) ‣ Large weights have a stronger symmetry breaking effect but.. ‣ Exploding values or gradient, saturation ‣ Gradient descent + early stopping is like imposing a gaussian prior around the initialization weights → close to 𝟎
  • Some heuristics for a FC layers with 𝑚 inputs and 𝑛 outputs
  • Pre-defined constant for biases (usually 0 ot 0.1 for ReLU to avoid saturation)

Weights Initialization:

  • the variance of the outputs of each layer should be equal to the variance of its inputs
  • the same should hold for the gradient
  • trade-off: for each unit normalize the initial weights with respect to the number of incoming and outcoming connections
  • Gradient Clipping can alleviate the explonding gradient problem
  • Local minima are probably associated with low cost
  • Saddle points are probably associated with high cost The backpropagated gradient signal should not be multiplied by values too small or too large in any layer. It should travel to the input layer without exploding or vanishing. The weight can be initialized as zero (zero initialization ), but it causes neurons to perform the same calculation in each iterations and produces the same outputs. If all the weights are initialized with 0, the derivative with respect to loss function is the same for every w in W[l](weight matrix of dimension l), thus all weights have the same value in subsequent iterations. This makes hidden units symmetric and continues for all the n iterations. Biases have no effect what so ever when initialized with 0. Zero initialization isn’t successful in classification. In fact initializing all the weights with zeros leads the neurons to learn the same features during training. The weight can be initialized randomly but we can go in a local minima. This is because each time we start from a random point of loss function and moving in the opposite direction of its gradient , we can end in a minimum which is not global. We can use a pre-training approach in which we itialize the weights with a model trained on a related task. Unsupervised pre-training: Train an unsupervised model on the training data, use the resulting model as initialization. Supervised pre-training (transfer learning): Initialize the weights with a model trained on a related task. Especially effective with CNNs. Delta-bar-delta algorithm: The algorithm is an early heuristic approach to adapting individual learning rates for model parameters during training. The approach is based on a simple idea: if the partial derivative of the loss, with respect to a given model parameter, remains the same sign, then the learning rate should increase. If the partial derivative with respect to that parameter changes sign, then the learning rate should decrease. Of course, this kind of rule can only be applied to full batch optimization.

Newton’s method: In contrast to first order methods, second-order methods make use of second derivatives to improve optimization. The most widely used second-order method is Newton’s method. Newton’s method is an optimization scheme based on using a second-order Taylor series expansion to approximate J (θ) near some point θ0.

  • If the function is quadratic, Newton’s method finds directly the minimum
  • If not, it can be used as update rule
  • Computing 𝑯 and 𝑯^-1 is unfeasible for medium-sized networks (H hessian(or curvature matrix) matrix, 𝑯ij specifies how gradient in direction 𝑖 changes as we move in direction 𝑗. Steepest descent methods(method in which we don’t have a fixed learning rate, you explore different possibilities of the learning rate) are not effective when off-diagonal elements are large (disturbance in simultaneous weight change)) Conjugate Gradients(Hessian-Free Optimization): Conjugate gradients is a method to efficiently avoid the calculation of the inverse Hessian by iteratively descending conjugate directions.
  • since 𝐽(𝜽 + 𝜹) is approximated, there is no hope to get the (local) minimum in one step
  • an alternative is to perform multiple update steps, each of which finds the minimum along one direction
  • however, avoid to undo previous work by choosing a new “conjugate” direction, i.e. which does not change the gradients in the previous directions
  • the second direction has zero gradient with respect to the first direction Batch Normalization: it is a method of adaptive reparametrization to normalize hidden (pre-)activations with like mean subtraction and standard deviation division and this is useful because it can help to keep the pre-activation in a non-saturating regime(the linear range). Basically you compute the mean, the variance and then you normalize. You can use use two parameter (to scale and shift) that you can learn with backpropagation.

Convolutional Neural Networks

Convolutional networks also known convolutional neural networks or CNNs, are a specialized kind of neural network for processing data that has a known, grid-like topology. The network employs a mathematical operation called convolution. In fact convolutional networks are simply neural networks that use convolution in place of general matrix multiplication in at least one of their layers. By definition, convolution is a mathematical operation on two functions (f and g) that produces a third function expressing how the shape of one is modified by the other. In its most general form, convolution is an operation on two functions of a real-valued argument. The first argument to the convolution is often referred to as the input and the second argument as the kernel. The output is sometimes referred to as the feature map. In machine learning applications, the input is usually a multidimensional array of data and the kernel is usually a multidimensional array of parameters that are adapted by the learning algorithm. We will refer to these multidimensional arrays as tensors. When the input data are images, the learning bias induced by a CNN layer allows to improve the predictive performance over a dense layer not all the times. Moreover, convolution provides a means for working with inputs of variable size. Adavantages of CNN:

  • They make the forward function more efficient to implement.
  • They significantly reduce the amount of parameters in the network(in terms of test error better than using dense layers). We have three main types of layers and we stack these layers to form a full CNN architecture: ‣ Fully Connected Layer (as in “regular” ANN) ‣ Convolutional Layer ‣ Pooling Layer Fully Connected layers in a neural networks are those layers where all the inputs from one layer are connected to every activation unit of the next layer. Convolutional layer convolves the input with a particular filter. Basically a convolution converts all the pixels in its receptive field into a single value. Final output of the convolutional layer is an activation map which is the result of taking a dot product between the filter and a chunk of the image. Convolution leverages three important ideas that can help improve a machine learning system: sparse interactions, parameter sharing and equivariant representations. Sparse interactions: This is accomplished by making the kernel smaller than the input. This means that we need to store fewer parameters, which both reduces the memory requirements of the model and improves its statistical efficiency. It also means that computing the output requires fewer operations. These improvements in efficiency are usually quite large.

Pooling: Pooling layer is used to reduce the size of the representations and to speed up calculations, as well as to make some of the features it detects a bit more robust. We use a pooling function to modify the output of the layer further. It makes the network approximately invariant to small translations(per esempio spostamenti). Pooling is basically a down sampling of an image. Role of pooling layer is to reduce the resolution of the feature map but retaining(trattenere) features of the map required for classification through translational and rotational invariants. In addition to spatial invariance robustness, pooling will reduce the computation cost by a great deal. In all cases, pooling helps to make the representation become approximately invariant to small translations of the input. Invariance to translation means that if we translate the input by a small amount, the values of most of the pooled outputs do not change. The most common strategy is max pooling which consints in taking max of the region represented by the filter and create a new, output matrix where each element is the max of a region in the original input. Downsampling: reduces the size of the input for the subsequent layers (Pooling to improve efficiency). Padding: In the convolution product, the pixels in the edges are used less than those central. Then pixels are added to the edges. Padding is a term relevant to convolutional neural networks as it refers to the amount of pixels added to an image when it is being processed by the kernel of a CNN. For example, if the padding in a CNN is set to zero, then every pixel value that is added will be of value zero. Zero padding the input allows us to control the kernel width and the size of the output independently. Without zero padding, we are forced to choose between shrinking the spatial extent of the network rapidly(ridurre estensione rete) and using small kernels. Unshared convolution: Similar to convolution, without shared weights. Structured Outputs: Convolutional networks can be used to output a high-dimensional, structured object, rather than just predicting a class label for a classification task or a real value for a regression task. Typically this object is just a tensor, emitted by a standard convolutional layer. No pooling/ padding same.

Practical Methodology

General methodology:

  • Determine your goals
  • Build an end-to-end pipeline
  • Be prepared to analyse your system to understand which component is performing worse than expected and if poor performance is due to underfitting, overfitting or a bug
  • Repeatedly make incremental changes(one at time, E.g. gathering new data, changing hyperparameters) Performance metrics: We have to decide which error metric to use and this metric will drive all future decisions. If the classifier outputs a score, metrics depend on a threshold. We also need to choose a desired level of performance. Zero error is often not possible(Bayes error rate: lowest possible error rate for any classifier). If the task is similar to another task we should use a pre- trained model. We need to find out if the training performance is acceptable. Low training performance - > you are not exploiting the available data well. Increase model capacity: more layers or more units (Hyperparameters).
  • Measure test performance ‣ If it is good, you are done ‣ If it is not, try to decrease model capacity ‣ Reduce the size of the model (Hyperparameters) ‣ Add regularization ‣ If the generalization gap is still high, gather more data if possible Baseline models: Baselines are simple Neural networks chosen to provide a first estimation of the achievable level of performance. Hyperparameter selection: Deep learning models are sensitive to hyperparameters. A hyperparameter is a parameter whose value is used to control the learning process. Parameters are different from hyperparameters. Parameters are learned automatically; hyperparameters are set manually to help guide the learning process. Learning rate can be tuned on the training set while all the others on the validation set. Usually the performance follows a U-shaped curve for each hyperparameter. We can use an automatic hyper-parameter selection: GridSearch or RandomSearch.
  • Grid search: Define a search space as a grid of hyperparameter values and evaluate every position in the grid. Test many different pre-defined options
  • Random search: Define a search space as a bounded domain of hyperparameter values and randomly sample points in that domain. Usually just some of the hyperparameters have a significant impact in performance. It can be more efficient that grid search.