






































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!







































Tutto Deep learning
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 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):
An Artificial Neural Network is a system consisting of interconnected units that compute nonlinear (numerical) functions:
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:
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.
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.
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.
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:
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).
Weights Initialization:
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.
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:
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.
General methodology: