id
int64
0
25.6k
text
stringlengths
0
4.59k
15,500
introduction to pytorch tensor([[ ][ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] gather( ,din [ ] out[ ]tensor([[ ][ ][ ][ ]]in [ ] shape out[ ]torch size([ ]similarlythe scatter method can be used to put values into tensor along given dimensions at given positions listing - illustrates augmenting tensor' values with scatter listing - augmenting tensor' values using the scatter method in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ][ ]]
15,501
introduction to pytorch in [ ] shape out[ ]torch size([ ]in [ ]index torch longtensor([[ , , , ]]in [ ]index out[ ]tensor([[ ]]in [ ]index shape out[ ]torch size([ ]in [ ]values torch zeros( , in [ ]values out[ ]tensor([[ ]]in [ ]values shape out[ ]torch size([ ]in [ ]result scatter( indexvaluesin [ ]result out[ ]tensor([[ ][ ][ ][ ]]in [ ]result shape out[ ]torch size([ ]in [ ] out[ ]tensor([[ ][ ][ ][ ]]
15,502
introduction to pytorch athematical operations the allclose method allows us to check whether the values in two tensors are the same given an absolute or relative tolerance level the methodwhich helps us to compare two tensors based on margin of errorcan come in quite handy while writing unit tests listing - illustrates validating tensors within tolerance level listing - validating whether given tensors are within tolerance level in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] - in [ ] out[ ]tensor([[ ][ ][ ]]in [ ]torch allclose( , ,rtol= - out[ ]true in [ ]torch allclose( , ,rtol= - out[ ]true in [ ]torch allclose( , ,rtol= - out[ ]true
15,503
introduction to pytorch in [ ]torch allclose( , ,rtol= - out[ ]false in [ ]torch allclose( , ,atol= - out[ ]true in [ ]torch allclose( , ,atol= - out[ ]true in [ ]torch allclose( , ,atol= - out[ ]true in [ ]torch allclose( , ,atol= - out[ ]false the argmax and argmin methods allow you to get the index of the maximum and minimum value along given dimension listing - illustrates extracting dimensions of minimum and maximum values in tensor listing - extracting dimensions of minimum and maximum values in given tensor in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ]torch argmax(adim= out[ ]tensor([ ]
15,504
introduction to pytorch in [ ]torch argmax(adim= out[ ]tensor([ ]in [ ]torch argmin(adim= out[ ]tensor([ ]in [ ]torch argmin(adim= out[ ]tensor([ ]similarlythe argsort functionillustrated in listing - gives the indices of sorted values along given dimension listing - extracting the indices of sorted values of tensor in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ]torch argsort(adim= out[ ]tensor([[ ][ ][ ]]in [ ]torch argsort(adim= out[ ]tensor([[ ][ ][ ]]
15,505
introduction to pytorch the cumsum methodillustrated in listing - allows you to compute the cumulative sum along given dimension listing - computing the cumulative sum along dimension of the tensor in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch cumsum(adim= in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch cumsum(adim= in [ ] out[ ]tensor([[ ][ ][ ]]
15,506
introduction to pytorch in [ ] shape out[ ]torch size([ ]similarlythe cumprod method allows you to compute the cumulative product along given dimension listing - illustrates the computation of the cumulative product listing - computing the cumulative product along dimension of the tensor in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch cumprod(adim= in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch cumprod(adim= in [ ] out[ ]
15,507
introduction to pytorch tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]the abs method allows you to compute the absolute value of the elements of given tensor listing - illustrates computing absolute value of the elements of tensor listing - computing the absolute value of the elements of tensor in [ ] torch tensor([[ ,- , ],[ ,- , ],[ ,- , ]]in [ ] out[ ]tensor([ - ] - ] - ]]in [ ] torch abs(ain [ ] out[ ]tensor([[ ][ ][ ]]the clamp function allows you to restrict elements between given minimum and maximum listing - illustrates clamping values within tensor
15,508
introduction to pytorch listing - clamping values within tensor in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] torch clamp(amin= max= in [ ] out[ ]tensor([[ ][ ][ ]]the ceil and floor functions allow you to round-up or round-down the elements of given tensoras illustrated in listing - listing - ceil and floor operations within tensor in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] torch floor(ain [ ] out[ ]tensor([[ ]
15,509
introduction to pytorch [ ][ ]]in [ ] torch ceil(ain [ ] out[ ]tensor([[ ][ ][ ]]element-wise mathematical operations let us now take look at number of element-wise mathematical operations these operations are called element-wise mathematical operations because an identical operation being performed on each of the elements of the tensor the mul function allows you to perform element-wise multiplicationas illustrated in listing - listing - element-wise multiplication in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] torch floattensor([[ ],[ , , ],[ , , ]]in [ ] out[ ]
15,510
introduction to pytorch tensor([[ ][ ][ ]]in [ ] torch mul( ,bin [ ] out[ ]tensor([[ ][ ][ ]]similarlywe have the div method for element-wise division listing - demonstrates element-wise division for tensors listing - element-wise division in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] torch floattensor([[ ],[ , , ],[ , , ]]in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] torch div( ,
15,511
introduction to pytorch in [ ] out[ ]tensor([[ ][ ][ ]]trigonometric operations in tensors within deep learningwe will also perform several trigonometric operations over tensors in the process of training them in this sectionwe will take brief look at few important functions frequently used in pytorch listing - illustrates the basic trigonometric operations listing - basic trigonometric operations for tensors in [ ] torch linspace(- steps= in [ ] out[ ]tensor([- - - - - ]in [ ]torch sin(aout[ ]tensor([- - - - - ]in [ ]torch cos(aout[ ]tensor([ ]
15,512
introduction to pytorch in [ ]torch tan(aout[ ]tensor([- - - - - ]in [ ]torch asin(aout[ ]tensor([- - - - - ]in [ ]torch acos(aout[ ]tensor([ ]in [ ]torch atan(aout[ ]tensor([- - - - - ]listing - illustrates few functions that are frequently used in machine learning--namelysigmoidtanhlog (which computes log( + ))erf (gaussian error function)and erfinv (inverse gaussian error functionlisting - additional trigonometric operations for tensors in [ ] torch linspace(- steps= in [ ] out[ ]tensor([- - - - - ]
15,513
introduction to pytorch in [ ]torch sigmoid(aout[ ]tensor([ ]in [ ]torch tanh(aout[ ]tensor([- - - - - ]in [ ]torch log (aout[ ]tensor(-inf- - - - ]in [ ]torch erf(aout[ ]tensor([- - - - - ]in [ ]torch erfinv(aout[ ]tensor(-inf- - - - inf]comparison operations for tensors let' now consider some operations that allow us to compare elements of the tensor--namelyge (greater than or equal)le (lesser than or equal)eq (equaland ne (not equallisting - illustrates comparison operations for tensors
15,514
introduction to pytorch listing - comparison operations for tensors in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ]torch ge( ,bout[ ]tensor([[ ][ ][ ]]dtype=torch uint in [ ]torch le( ,bout[ ]tensor([[ ][ ][ ]]dtype=torch uint in [ ]torch eq( ,bout[ ]tensor([[ ][ ][ ]]dtype=torch uint
15,515
introduction to pytorch in [ ]torch ne( ,bout[ ]tensor([[ ][ ][ ]]dtype=torch uint linear algebraic operations we will now dive deeper into number of linear algebraic operations using pytorch tensors the matmul function allows you to multiply two tensors listing - demonstrates matrix multiplication for tensors listing - matrix multiplication operations for tensors in [ ] torch ones( , in [ ] out[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch ones( , in [ ] out[ ]tensor([[ ][ ][ ]]
15,516
introduction to pytorch in [ ] shape out[ ]torch size([ ]in [ ]torch matmul( ,bout[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ]the addbmm function (where bmm stands for batch matrix-matrix productallows you to perform the computation [ ]where and are scalarsand ma and are tensors note that the addbmm function takes parameters and with default values equal to one and that tensors such as and are provided by stacking them along the first dimension listing - illustrates batch matrix-matrix addition of tensors listing - batch matrix-matrix addition of tensors in [ ] torch ones( in [ ] out[ ]tensor([[[ ][ ]][[ ][ ]]]in [ ] shape out[ ]torch size([ ]
15,517
introduction to pytorch in [ ] torch ones( in [ ] out[ ]tensor([[[ ][ ][ ]][[ ][ ][ ]]]in [ ] shape out[ ]torch size([ ]in [ ] torch ones( , in [ ] out[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ]torch addbmm( about[ ]tensor([[ ][ ]]in [ ]torch addbmm( about[ ]tensor([[ ][ ]]
15,518
introduction to pytorch in [ ]torch addbmm(mabout[ ]tensor([[ ][ ]]the addmm function is non-batch version of addbmm that allows you to perform the computation bwhere and are scalarsand maand are tensors note that the addmm function takes parameters and with default values equal to one listing - illustrates non-batch matrix--matrix addition of tensors listing - non batch matrix-matrix addition of tensors in [ ] torch ones( in [ ] out[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch ones( in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]
15,519
introduction to pytorch in [ ] torch ones( , in [ ] out[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ]torch addmm(mabout[ ]tensor([[ ][ ]]in [ ]torch addmm( about[ ]tensor([[ ][ ]]in [ ]torch addmm( about[ ]tensor([[ ][ ]]the addmv function (matrix-vectorallows you to perform the computation bwhere and are scalarsm and are matricesand is vector note that addmv takes parameters and with default values equal to one listing - illustrates matrix vector addition for tensors
15,520
introduction to pytorch listing - matrix vector addition of tensors in [ ] torch ones( in [ ] out[ ]tensor([[ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ] torch ones( in [ ] out[ ]tensor([ ]in [ ] shape out[ ]torch size([ ]in [ ] torch ones( in [ ] out[ ]tensor([ ]in [ ] shape out[ ]torch size([ ]in [ ]torch addmv( , , , ,bout[ ]tensor([ ]in [ ]torch addmv( , , , ,bout[ ]tensor([ ]in [ ]torch addmv( , ,bout[ ]tensor([ ]
15,521
introduction to pytorch the addr function allows you to perform an outer product of two vectors and add it to given matrix the outer product of two vectors in linear algebra is matrix for exampleif you have vector with elements ( dimensionand another vector with elements ( dimension)then the outer product of and will be matrix with shape [ vmu [ unv umv , umvnu vnu vnumin pytorchthe function expects the first argument as the matrix to which we need to add the resultant outer productfollowed by the vectors for which the outer product needs to be computed in listing - we create two vectors ( and bwith three elements eachand perform an outer product to create matrixwhich is then added to another matrix (mlisting - outer product of vectors in [ ] torch tensor([ ]in [ ] out[ ]tensor([ ]in [ ] shape out[ ]torch size([ ]in [ ] in [ ] torch ones( ,
15,522
introduction to pytorch in [ ] out[ ]tensor([[ ][ ][ ]]in [ ] shape out[ ]torch size([ ]in [ ]torch addr( , ,bout[ ]tensor([ ] ] ]]in [ ] torch zeros( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ]torch addr( , ,bout[ ]tensor([[ ][ ][ ]]the baddbmm function allows you to perform the computation [ ] [ ]where and are scalarsand mp and are tensors note that baddbmm takes parameters
15,523
introduction to pytorch and with default values equal to oneand that tensors such as and are provided by stacking them along the first dimension listing - illustrates the use of baddbmm function listing - the baddbmm function in [ ] torch ones( , , in [ ] out[ ]tensor([[[ ][ ]][[ ][ ]]]in [ ] shape out[ ]torch size([ ]in [ ] torch ones( , , in [ ] out[ ]tensor([[[ ][ ][ ]][[ ][ ][ ]]]in [ ] shape out[ ]torch size([ ]in [ ] torch ones(
15,524
introduction to pytorch in [ ] out[ ]tensor([[[ ][ ]][[ ][ ]]]in [ ] shape out[ ]torch size([ ]in [ ]torch baddbmm( , , , ,bout[ ]tensor([[[ ][ ]][[ ][ ]]]in [ ]torch baddbmm( , , , ,bout[ ]tensor([[[ ][ ]][[ ][ ]]]in [ ]torch baddbmm( , , , ,bout[ ]tensor([[[ ][ ]][[ ][ ]]]
15,525
introduction to pytorch the bmm function allows you perform batch-wise matrix multiplication for tensorsas illustrated in listing - listing - batch-wise matrix multiplication in [ ] torch ones( , , in [ ] out[ ]tensor([[[ ][ ]][[ ][ ]]]in [ ] shape out[ ]torch size([ ]in [ ] torch ones( , , in [ ] out[ ]tensor([[[ ][ ][ ]][[ ][ ][ ]]]in [ ] shape out[ ]torch size([ ]
15,526
introduction to pytorch in [ ]torch bmm( ,bout[ ]tensor([[[ ][ ]][[ ][ ]]]the dot function allows you to compute the dot product of tensorsas illustrated in listing - listing - computing the dot product of tensors in [ ] torch rand( in [ ] out[ ]tensor([ ]in [ ] torch rand( in [ ] out[ ]tensor([ ]in [ ]torch dot( ,bout[ ]tensor( the eig function allows you to compute eigenvalues and eigenvectors of given matrix listing - demonstrates computing eigenvalues for tensor we first compute the eigenvalues and then confirm that the results match note the use of the mm functionwhich allows you to multiply two matrices
15,527
introduction to pytorch listing - computing eigenvalues for tensor in [ ] torch rand( , in [ ] out[ ]tensor([[ ][ ][ ]]in [ ]valuesvectors torch eig(aeigenvectors=truein [ ]values out[ ]tensor([ ][- ][- - ]]in [ ]vectors out[ ]tensor([[- - ][- - ][- - ]]in [ ]values[ , vectors[:, reshape( , out[ ]tensor([[- ][- ][- ]]in [ ]torch mm(avectors[:, reshape( , )out[ ]tensor([[- ][- ][- ]]
15,528
introduction to pytorch the cross functionillustrated in listing - allows you to compute the cross product of two tensors listing - computing the cross product of two tensors in [ ] torch rand( in [ ] torch rand( in [ ] out[ ]tensor([ ]in [ ] out[ ]tensor([ ]in [ ]torch cross( ,bout[ ]tensor( - ]as shown in listing - the norm function allows you to compute the norm of the given tensor listing - computing the norm of tensor in [ ] torch ones( in [ ] out[ ]tensor([ ]in [ ]torch norm( , out[ ]tensor( in [ ]torch norm( , out[ ]tensor( in [ ]torch norm( , out[ ]tensor(
15,529
introduction to pytorch in [ ]torch norm( , out[ ]tensor( in [ ]torch norm( , out[ ]tensor( in [ ]torch norm( ,float('inf')out[ ]tensor( the renorm function allows you to normalize vector by dividing it by the norm listing - demonstrates normalizing operation on tensor listing - normalizing tensor in [ ] torch floattensor([[ , , , ]]in [ ] out[ ]tensor([[ ]]in [ ]torch renorm(adim= = maxnorm= out[ ]tensor([[ ]] ummary this offered brief introduction to pytorch with focus on tensors and tensor operations several of the tensor operations discussed in this will come handy in the next few you should spend quality time with tensors to improve you pytorch skills this will be immensely valuable for customizing deep learning networks and debugging the flow easily in the advent of an unaccounted error common tensor operations include view (to reshape tensors)size (to print the shape/size of the tensor)item (to extract data from single value tensor)squeeze (to reshape tensors)and cat (to concatenate tensorsmoreoverpytorch has two separate packages (torchvision and torchtext
15,530
introduction to pytorch that provide comprehensive set of functions for handling images (computer visionand text (natural language processingdatasets we will explore the essential utilities from these packages in "convolutional neural networks,and "recurrent neural networks as librarypytorch provides an excellent means for researchers and practitioners to develop and train deep learning experiments at scale while providing neat abstraction for several building blocks yet being flexible for deep customization in the next few while practically implementing deep learning modelsyou will see how pytorch takes cares of so many things in the background and thus equips the user with the speed and required agility for accelerated experiments at scale the next will focus on the foundations for basic feed-forward network--the first step towards deep learning
15,531
feed-forward neural networks feed-forward neural networks were the earliest implementations within deep learning these networks are called feed-forward because the information within them moves only in one direction (forward)--that isfrom the input nodes (unitstowards the output units in this we will cover some key concepts around feed-forward neural networks that serve as foundation for various topics within deep learning we will start by looking at the structure of neural networkfollowed by how they are trained and used for making predictions we will also take brief look at the loss functions that should be used in different settingsthe activation functions used within neuronand the different types of optimizers that could be used for training finallywe will stitch together each of these smaller components into full-fledged feed-forward neural network with pytorch let' get started what is neural networkat an abstract levela neural network can be thought of as function (cnikhil ketkarjojo moolayil ketkar and moolayildeep learning with python
15,532
feed-forward neural networks which takes an input rn and produces an output rmand the behavior of which is parameterized by th rp sofor instancefth could be simply fth(xth figure - shows the architecture of neuron (or unit within neural networkfigure - unit in feed-forward network unit unit (also known as node or neuronis the basic building block of neural networkrefer to figure - and figure - unit/node/neuron is function that takes as input vector rn and produces scalar unit is parameterized by weight vector rn and bias term denoted by the output of the unit can be described as xi *wi
15,533
feed-forward neural networks where is referred to as an activation function although variety of activation functions can be usedas we shall see later in the non-linear function is generally used figure - shows detailed look at the unit figure - unit in neural network the overall structure of neural network neural networks are constructed using the unit as basic building block these units are organized as layerswith every layer containing one or more units the last layer is referred to as the output layer all layers before the output layers are referred to as hidden layers the first layerusually referred as the th layeris the input layer each layer connects to the next successive layer with weightswhich are trained/updated in an iterative way
15,534
feed-forward neural networks the number of units in layer is referred to as the width of the layer the width of each layer need not be the samebut the dimension should be alignedas we shall see later in the the number of layers is referred to as the depth of the network this is where the notion of "deep(as in "deep learning"comes from every layer takes as input the output produced by the previous layerexcept for the first layerwhich consumes the input the output of the last layer is the output of the network and is the prediction generated based on the input as previously mentioneda neural network can be seen as function fth ywhich takes as input rn and produces as output rmand the behavior of which is parameterized by th rp we can now be more precise about th it is simply collection of all the weights for all the units in the network designing neural network involvesamong other thingsdefining the overall structure of the networkincluding the number of layers (depthand the width of these layers figure - shows the overall structure of neural network
15,535
feed-forward neural networks figure - the structure of neural network expressing neural network in vector form let' take look at the layers of neural network and their dimensions in bit more detail (refer to figure - if we assume that the dimensionality of the input is rn and the first layer has unitsthen each unit has
15,536
feed-forward neural networks rn weights associated with it that isthe weights associated with the first layer are matrix of the form while this is not shown in the figure - each unit also has bias term associated with it the first layer produces an output where oi xk *wk bi note that the index corresponds to each of the inputs/weights (going from )and the index corresponds to the units in the first layer (going from let' now look at the output of first layer in vectorized notation by vectorized notationwe simply mean linear algebraic operationssuch as vector matrix multiplications and computation of the activation function on vector producing vector (rather than scalar to scalarthe output of the first layer can be represented as ( herewe are treating the input rn to be of dimensionality nthe weight matrix to be of dimensionality and the bias term to be vector of dimensionality noticethenthat produces vector of dimensionality and the function simply transforms each element of the vector to produce similar process follows for the second layer that goes from to this can be written in vectorized form as ( we can also write the entire computation up to layer in vectorized form as ( figure - illustrates neural network in vector form
15,537
feed-forward neural networks figure - neural network in vector form evaluating the output of neural network now that we have looked at the structure of neural networklet' look at how the output of neural network can be evaluated against labeled data refer to figure -
15,538
feed-forward neural networks for single data pointwe can compute the output of neural networkwhich we denote as now we need to compute how good the prediction of our neural network is as compared to here comes the notion of loss function loss function measures the disagreement between and ywhich we denote by number of loss functions are appropriate for the task at handsay binary classificationmulti-class classificationor regression which we shall cover later in the (typically derived using maximum likelihooda probabilistic framework that aims to increase the likelihood of finding the probability distribution that best explains the dataa loss function typically computes the disagreement between and over number of data points rather than single data point figure - demonstrates the flow for computing the disagreement between and figure - loss/cost function and the computation of cost/loss
15,539
feed-forward neural networks training neural network let' now look at how neural network is trained figure - illustrates training neural network assuming the same notation as earlierwe denote by th the collection of all the weights and bias terms of all the layers of the network let us assume that th has been initialized with random values we denote by fnn the overall function representing the neural network as previously mentionedwe can take single data point and compute the output of the neural network as we can also compute the disagreement with the actual output using the loss function yy that islfnn(xth)ylet' now compute the gradient of this loss function and denote it by lfnn(xth)ywe can now update th using steepest descent as ths ths lfnn(xth) )where denotes single step note that we can take many such steps over different data points in our training set over and over again until we have reasonably good value for lfnn(xth)ynote for nowwe will stay away from the computation of gradients of loss functions (fnn(xth)ythese can be generated using automatic differentiation (covered elsewhere in the bookquite easily (even for arbitrary complicated loss functionsand need not be derived manually
15,540
feed-forward neural networks figure - training neural network eriving cost functions using maximum likelihood as discussed earlierthe cost functions (aka loss functionshelp to determine the disagreement between the predictions and the actual targets with quantified metric based on specific use case and the nature of the target variablethere are several ways to define loss function loss function is derived by leveraging framework (saymaximum likelihoodwhere we maximize or minimize set of parameters for an outcome of interest the quantified value of disagreement is calculated using the loss function thereforeit gives the model' training framework tangible way to estimate the level of disagreement and
15,541
feed-forward neural networks thereby update the weight parameters so as to reduce the disagreement and thus improve model performance we will now look into how various loss functions are derived using maximum likelihood specificallywe will see how commonly used loss functions in deep learning--such as binary cross-entropycross-entropy (for non-binary outcomes)and squared error--can be derived using the maximum likelihood principle binary cross-entropy binary cross-entropyor log lossmeasures the performance of classification models where the outcomes are binary and is represented in the forms of probability value between and the log loss value increases as the model performance tarnishes and produces predictions away from the desired value the ideal model would have binary cross-entropy value of let' consider simple example to understand the concept of binary cross entropy and also get fundamental intuition of maximum likelihood we have some data consisting of {( )( )(xnyn)}where rn and { which is the target of interest also known as the criterion variable let' assume that we have generated model that predicts the probability of given we denote this model by (xth)where th represents the parameters of the model the idea behind maximum likelihood is to find th that maximizes (dthassuming bernoulli distributionand given that each of the examples {( )( )(xnyn)is independentwe have the following expressionn xi xi yi
15,542
feed-forward neural networks we can take logarithm operation on both sides to arrive at the followingn log log xi xi yi which simplifies to the following expressionn log yi log xi yi log xi instead of maximizing the rhswe minimize its negative value as followsn yi log xi yi log xi this leads us to the following binary cross-entropy functionn yi log xi yi log xi  thusthe idea of maximum likelihood enables us to derive the binary cross-entropy functionwhich can be used as loss function in the context of binary classification cross-entropy building on the idea of binary cross-entropylet' now consider deriving the cross-entropy loss function to be used in the context of multiclassification let' assume that { }where { kare the classes we also denote nk to be the observed counts of each of the classes observe that ni in this casetoolet us assume that we
15,543
feed-forward neural networks have somehow generated model that predicts the probability of given we denote this model by (xth)where th represents the parameters of the model let us again use the idea behind maximum likelihoodwhich is to find th that maximizes (dthassuming multinomial distributionand given that each example {( )( )(xnyn)is independentwe have the following expressionp ny xi nk we can take logarithm operation on both sides to arrive at the followingn log log log !nk log xi this can be simplified to the followingn log log log !nk yi log xi the terms log nand log nkare not parameterized by th and can be safely ignored as we try to find th that maximizes (dththuswe have the followingn log yi log xi as beforeinstead of maximizing the rhswe minimize its negative valueas followsn yi log xi
15,544
feed-forward neural networks this leads to the following binary cross-entropy functionn yi log xi thusthe idea of maximum likelihood enables us to derive the crossentropy functionwhich can be used as loss function in the context of multi-classification squared error let us now discuss deriving the squared error to be used in the context of regression using maximum likelihood let us assume that unlike the previous caseswhere we assumed that we had model that predicted probabilitywe will assume that we have model that predicts the value of to apply the maximum likelihood ideawe assume that the difference between the actual and the predicted has gaussian distribution with zero mean and variance of thenit can be shown that minimizing = leads to the minimization of (thsummary of loss functions we now summarize three key points with respect to loss functions and the appropriateness of particular loss function given the problem at hand the binary cross-entropy given by the expression yi log xi yi log xi 
15,545
feed-forward neural networks is the recommended loss function for binary classification this loss function should typically be used when the neural network is designed to predict the probability of the outcome in such casesthe output layer has single unit with suitable sigmoid as the activation function the cross-entropy function given by the expression yi log xi is the recommended loss function for multiclassification this loss function should typically be used with the neural network designed to predict the probability of the outcomes of each of the classes in such casesthe output layer has softmax units (one for each class the squared loss function given by = should be used for regression problems the output layer in this case will have single unit several other loss functions could be used for classification and regressioncovering the exhaustive list would be beyond the scope of the few notable loss functions are huber loss (regressionand hinge loss (classification
15,546
feed-forward neural networks types of activation functions we will now look at number of activation functions commonly used for neural networks let' start by enumerating few properties of interest for activation functions in theorywhen an activation function is non-lineara two-layer neural network can approximate any function (given sufficient number of units in the hidden layerthereforewe would always use nonlinear activation functions for solving problems within the realm of deep learning function that is continuously differentiable allows for gradients to be computed and gradient-based methods (optimizersto be used for finding the parameters that minimize our loss function over the data if function is not continuously differentiablegradient-based methods would make no progress in the training of network with gradient-based methodswe can achieve stable performance from function the range of which is finite (as opposed to infinitesmooth functions are preferred (empirical evidenceand monolithic functions for single layer lead to convex error surfaces (this is typically not consideration regarding deep learning alsowe prefer activation functions that are mostly expected to be symmetric around the origin and behave like identity functions near the origin (with thatlet' take brief look at notable options within activation functions
15,547
feed-forward neural networks linear unit the linear unit is simplest unit that transforms the input as as the name indicatesthe unit does not have non-linear behavior and is typically used to generate the mean of conditional gaussian distribution linear units make gradient-based learning fairly straightforward task (figure - figure - linear unit in neural network igmoid activation the sigmoid activation transforms the input as followsy wx the underlying activation function (figure - is given by ex
15,548
feed-forward neural networks sigmoid units can be used in the output layer in conjunction with binary cross-entropy for binary classification problems the output of this unit can model bernoulli distribution over the output conditioned over figure - sigmoid function oftmax activation the softmax layer is typically used only within the output layer for multiclassification tasks in conjunction with the cross-entropy loss function refer to figure - the softmax layer normalizes outputs of the previous layer so that they sum up to one typicallythe units of the previous layer model an unnormalized score of how likely the input is to belong to particular class the softmax layer normalized this so that the output represents the probability for every class
15,549
feed-forward neural networks figure - softmax layer rectified linear unit rectified linear unit (reluused in conjunction with linear transformation transforms the input as max ,wx the underlying activation function is (xmax ( xrecentlythe relu is more commonly used as hidden unit results show that relus lead to large and consistent gradientswhich helps gradient-based learning (figure - although relu looks like linear unitit has derivative function and thus allows for computing the gradient of the losses in recent timesthe relu has been the most popular choice for hidden network activation in most casesa relu can be default choice that would lead into desirable results within timely manner
15,550
feed-forward neural networks figure - rectified linear unit there are few disadvantages with reluhowever when inputs approach near zerothe gradient of the function becomes zero and thus gets stuck within the training steps with no progress in the training this is commonly known as the dying relu problem yperbolic tangent the hyperbolic tangent unit transforms the input (used in conjunction with linear transformationas followsy tanh wx the underlying activation function (figure - is given by tanh the hyperbolic tangent unit is also commonly used as hidden unit figure - covers only handful of the available options in activation functions for deep learning
15,551
feed-forward neural networks figure - the tanh activation function there are many more that can be used for tailored benefits in specified setting or use case notable examples include leaky reluparametric reluand swish good starting point to explore additional activation functions is ackpropagation the most fundamental building block of deep learning is backpropagationshort for backward propagation of errorsan algorithm used for training neural networks in supervised learning though backpropagation was invented in sit was popularized several years laterin by rumelharthintonand williams in their paper "learning representations by back-propagating errors earlierwe studied loss functions that measure the disagreement between the predicted output and the actuals the weights of the network are at first randomly initialized in order for the network to learn (train)the next logical step would be to align the weights such that the
15,552
feed-forward neural networks disagreement would be the least (ideallyzerothis is where we interface with backpropagationan intuitive algorithm that enables the computation of gradients of the loss with respect to the weights using chain rule in the forward passthe network computes the prediction for given input sampleand the loss function measures the disagreement between the actual target value and network' prediction backpropagation computes the gradient of the loss with respect to the weights and biases and thus provides us with fair overall picture of how small change in the weight impacts the overall loss we would then need to update the weights iteratively and with small increments (in the opposite direction of the gradientto reach the local minima this process is called the gradient descent-- reducing the loss function to reach the minimum the network therefore learns (iterative and incremental updates on weightsthe patterns that can correctly predict for given input sample with the least disagreement there are several variants to update the weights in gradient descent for neural networks the next section explores few of them in the next we will take brief look at automatic differentiation that enables the idea of backpropagation programmatically gradient descent variants there are primarily three variants of gradient descent techniques each of them differs in its approach by the amount of data used to compute the gradient of the loss depending on the amount of data usedwe make trade-off between the accuracy of the parameter update and the time it takes to perform an update belowwe discuss three different variants used in training deep learning networks and later (in the following sectionwe study few popular gradient descent optimization algorithms
15,553
feed-forward neural networks batch gradient descent the original gradient descent is referred to as the batch gradient descent (bgdtechnique the name is derived from the amount of data used to compute the gradient--in this casethe entire batch the bgd technique essentially leverages the entire dataset available to compute the gradient of the cost function with respect to the parameters (weightsthis results in inherently slow andin most casesa non-viable optionas we might run out of memory to load the entire batch in most common scenarioswe would mostly tend to avoid the bgd approachsparring small datasets (which is rare phenomenon in deep learningstochastic gradient descent to overcome the issues from bgdwe have stochastic gradient descent (sgdwith sgdwe compute the gradient and update the weights for each sample in the dataset this process results in far less use of memory in the deep learning hardware and achieves results faster howeverthe updates are far more frequent than desired with more frequent updates to the weightsthe cost function fluctuates heavily sgdhoweverresults in bigger problems when the goal is to converge the updates towards the exact minima given the far more frequent updatesthe possibility of overshooting an update is very high to overcome these tradeoffswe might need to slowly reduce the learning rate over period of time in order to help the network converge to local or global minima mini-batch gradient descent mini-batch gradient descent (mbgdcombines the best of sgd and bgd instead of using the entire dataset (batchor just single sample from the dataset to compute the gradient of the cost function with respect to the parametersmbgd leverages smaller batchwhich
15,554
feed-forward neural networks is greater than but smaller than the entire dataset common batch sizes are etc number in the range of powers of is recommended (but not necessary)as it suits best from computation perspective with mbgdthe updates are less frequent than sgd but more frequent than bgdand leverage small batch instead of individual samples or the entire dataset in this waythe variance reduces to greater extent and we achieve better trade-off on the speed gradient-based optimization techniques in the following sectionwe will discuss in brief few popular optimization techniques commonly used in deep learning the details of the math used in each technique are beyond the scope of this book gradient descent with momentum the problems we discussed earlier between sgd and bgd are fairly smoothed using mbgd howevereven with the use of mbgdthe direction of the update still fluctuates (though less than with sgd but more than with mgdgradient descent with momentum leverages the past gradients to calculate an exponentially weighted average of the gradients to further smoothen the parameter updates figure - illustrates the update process figure - gradient descent with momentum
15,555
feed-forward neural networks the update process can be simplified using the following equations firstwe compute an exponentially weighted average of the past gradients as ntwhere nt gnt ethj(thand th th nt the here is hyperparameter that takes values between and nextwe use this exponentially weighted average in the updates of weights instead of the gradients directly by leveraging the exponentially weighted averages of the gradientsinstead of directly using the gradientsthe incremental steps are smoother and faster and thus overcome the problems with oscillating around the minima rmsprop rmsprop is an unpublished optimization algorithm proposed by geoffry hinton in lecture of the online course "neural networks for machine learningon coursera at the corermsprop computes the moving average of the squared gradients for each weight and divides the gradient by the square root of the mean square this complex process should help in decoding the name root mean square prop leveraging exponential average here helps in giving recent updates more preferences than less recent ones the rmsprop can be represented as followsfor each weight in thwe have   gt and gt  to update the weight wt wt
15,556
feed-forward neural networks where is hyperparameter that defines the initial learning rateand gt is the gradient at time for parameter/weight in th we add to the denominator to avoid divide by zero situations adam simplified name for adaptive moment estimationadam is the most popular choice recently for optimizers in deep learning in simple wayadam combines the best of rmsprop and stochastic gradient descent with momentum from rmspropit borrows the idea of using squared gradients to scale the learning rateand it takes the idea of moving averages of the gradient instead of directly using the gradient when compared to sgd with momentum herefor each weight in thwe have   gt and st st gt which then is used to compute  gt st andfinallythe weight is updated as wt wt the preceding three types of optimization algorithms represent just few from the breadth of available options for different types of use cases within deep learning we have definitely not covered the detailed depths and math in each of these topicsso readers are highly recommended to
15,557
feed-forward neural networks explore the preceding optimization techniquesand othersin greater detail adagrad and adadelta are popular and highly recommended choices practical implementation with pytorch so farwe have provided brief overview of the essential topics of feedforward neural network we will now implement simple network using pytorch the idea of introducing all the building blocks necessary for the first network makes the process of lazy learning (learning constructs as and when necessaryin pytorch more effective listing - imports the essential python packages for the exercise listing - importing the necessary python packages #import required libraries import torch as tch import torch nn as nn import numpy as np from sklearn datasets import make_blobs from matplotlib import pyplot we will need torch and its neural network modulealong with numpymatplotlib (for visualizationand sklearn (for creating dummy datasetsalthough there are million ways to create dummy datasetswe will leverage simple function provided within sklearn note in this bookwe are using couple of popular python packages relevant to machine learning most of these packages come installed with an anaconda distribution additional packagesif requiredwill be specifically called out
15,558
feed-forward neural networks nextlet' create dummy dataset for our neural network listing - illustrates the creation of toy (dummydataset for the exercise listing - creating toy dataset samples #let' divide the toy dataset into training ( %and rest for validation train_split int(samples* #create dummy classification dataset xy make_blobs(n_samples=samplescenters= n_features= cluster_std= random_state= reshape(- , #convert the numpy datasets to torch tensors , tch from_numpy( ),tch from_numpy(yx, = float(), float(#split the datasets inot train and test(validationx_trainx_test [:train_split] [train_split:y_trainy_test [:train_split] [train_split:#print shapes of each dataset print("x_train shape:",x_train shapeprint("x_test shape:",x_test shapeprint("y_train shape:",y_train shapeprint("y_test shape:",y_test shapeprint(" dtype", dtypeprint(" dtype", dtypeoutput[x_train shapetorch size([ ]x_test shapetorch size([ ]
15,559
feed-forward neural networks y_train shapetorch size([ ]y_test shapetorch size([ ] dtype torch float dtype torch float the toy datasetwith , samples each having featuresis divided into train and test let' create class that defines the neural network using pytorch' nn module listing - defines the creation of neural network for the purpose of this exercise listing - defining feed forward neural network #define neural network with hidden layers and output layer #hidden layers will have , and neurons #output layers will have neuron class neuralnetwork(nn module)def __init__(self)super(__init__(tch manual_seed( self fc nn linear( self relu nn relu(self fc nn linear( self relu nn relu(self out nn linear( self final nn sigmoid(def forward(selfx)op self fc (xop self relu (opop self fc (opop self relu (op
15,560
feed-forward neural networks op self out(opy self final(opreturn the torch nn module provides the essential means to define and train neural networks it contains all the necessary building blocks for creating neural networks of various kindssizesand complexity we will create class for our neural network by inheriting this module and create an initializing method as well as forward pass method the __init__ method creates the different pieces of the network and keeps it ready for us every time we create an object with this class essentiallywe used the initialization method to create the hidden layersthe output layerand the activation for each layer the nn linear( , function creates layer with input features and output features the next layernaturallywill have input featuresand so on the nn relu(and nn sigmoid(functions add the activation function when connected to layer each of the individual components created within the initialization function is connected in the forward(method in the forward methodwe connect the individual components of the neural network the first hidden layerfc accepts input data and produces outputs for the next layer the fc layer is passed to the relu activation layerwhich then passes the activated output to the next layerfc which repeats the same processto create the final output layerwhich has the sigmoid activation function (since our toy dataset is crafted for binary classificationon creating an object of the class neuralnetworkand calling the forward methodwe get outputs from the networkwhich are computed by multiplying the input matrix with randomly initialized weight matrix passed through an activation function and repeated for the number of hidden layers until the final output layer at firstthe network would obviously generate junk outputs-- predictions (which would add no value to our classification problemat least not now
15,561
feed-forward neural networks to get more accurate predictions for our given problemwe would need to train the network-- to backpropagate the loss and update the weights with respect to the loss function fortunatelypytorch provides these essential building blocks in an extremely easy to use and intuitive way listing - illustrates defining the lossoptimizerand training loop for the neural network listing - defining the lossoptimizerand training function for the neural network #define function for training network def train_network(model,optimizer,loss_function ,num_epochs,batch_size,x_train,y_train)#explicitly start model training model train(loss_across_epochs [for epoch in range(num_epochs)train_loss for in range( ,x_train shape[ ],batch_size)#extract train batch from and input_data x_train[ :min(x_train shape[ ], +batch_size)labels y_train[ :min(x_train shape[ ], +batch_ size)#set the gradients to zero before starting to do backpropragation optimizer zero_grad(#forward pass output_data model(input_data
15,562
feed-forward neural networks #caculate loss loss loss_function(output_datalabels#backpropogate loss backward(#update weights optimizer step(train_loss +loss item(batch_size print("epoch{loss:{ }format(epoch+ ,train_ loss )loss_across_epochs extend([train_loss]#predict y_test_pred model(x_testa =np where(y_test_pred> , , return(loss_across_epochs###end of function#create an object of the neural network class model neuralnetwork(#define loss function loss_function nn bceloss(#binary crosss entropy loss #define optimizer adam_optimizer tch optim adam(model parameters(),lr #define epochs and batch size num_epochs batch_size= #calling the function for training and pass modeloptimizerloss and related paramters
15,563
feed-forward neural networks adam_loss train_network(model,adam_optimizer ,loss_function,num_epochs,batch_ size,x_train,y_trainbefore we get into the specifics of listing - let' look at the individual components we defined leveraging pytorch' readily provided building blocks we need to define loss function that will be used to measure the difference between our predictions and actual labels pytorch provides comprehensive list of loss functions for different outcomes these loss functions are available under torch nn examples include mseloss (mean squared error loss)crossentropyloss (for multi-class classification)and bceloss (binary cross-entropy loss)which is used for binary classification for our use casewe will leverage binary crossentropy loss this is defined as loss_function torch nn bceloss(nextwe define an optimizer for our network earlier in the we explored the sgdadamand rmsprop optimizers pytorch provides comprehensive list of optimizers that can be used for building various kinds of neural networks all optimizers are organized under torch optim ( torch optim sgdfor sgd optimizerfor our use casewe are using the adam optimizer (the most recommended optimizer for the majority of use caseswhile defining the optimizerwe also need to define the parameters for which the gradient needs to be computed during backpropagation for the neural networkthis list would be all the weights in the feed-forward network we can easily denote the entire list of model weights to the optimizer by using model parameters(within the definition of the optimizer we can then additionally define hyperparameters for the selected optimizer by defaultpytorch provides fairly good values for all necessary hyperparameters howeverwe can further override them to tailor optimizers for our use case adam_optimizer tch optim adam(model parameters(),lr
15,564
feed-forward neural networks lastlywe need to define the batch size and the number of epochs required to train our model batch size refers to the number of samples within batch in mini-batch update one forward and backward pass for all the batches that cover all samples once is called an epoch finallywe pass all these constructs to our function to train our model let' take detailed look at the constructs within the function in our training functionwe define structure to train our network with the provided optimizerloss functionmodel objectand training data over batches for the defined number of epochs firstwe initiate our model for training mode with model train(setting the model object to train mode explicitly is essentialthe same would be essential while leveraging the model for evaluation-- explicitly setting the model to evaluate mode with model eval(this ensures that the model is aware of the time when it is expected to update the parameters and when to not in the preceding examplewe did not add the evaluation loop because it is tiny toy dataset in later examples with large datasetshoweverwe will use separate function for evaluation we will train the network over mini-batches the for loop divides the training data into batches with our defined size the training dataalong with the corresponding labelsis extracted for batch using the following codeinput_data x_train[ :min(x_train shape[ ], +batch_size)labels y_train[ :min(x_train shape[ ], +batch_size)we then need to set the gradients to zero before starting to do backpropagation using optimizer zero_grad(missing this step will accumulate the gradients on subsequent backward passes and lead to undesirable effects this behavior is by design in pytorch thenwe calculate the forward pass using output_data model(input_datathe forward pass is the execution of the forward(function in our class definition it connects the different layers we defined for the networkwhich finally outputs the prediction for each sample once we have the
15,565
feed-forward neural networks predictionswe can calculate its deviation from the actual label using the loss function-- loss loss_function(output_datalabelsto backpropagate our losspytorch provides built-in module that does the heavy lifting for computing gradients for the loss with respect to the weights we simply call the loss backward(methodand the entire backpropagation is taken care of "automatic differentiation in deep learning,explores the autograd modulewhich takes care of backpropagation in pytorchin more detail once the gradients are computedit is time to update our model weights this is done in the step optimizer step(the optimizer step is aware of the parameters that need to be updated with the gradientas we provided them while defining our optimizer calling the optimizer step(function updates the weights for the networkautomatically taking into account the hyperparameters defined within the optimizer--in our casethe learning rate we repeat this process over batches for the entire training sample the training process is repeated for multiple epochsand with each iteration we expect the losses to reduce and the weights to align in order to achieve better accuracy for predictions listing - uses different optimizers to illustrate the training process for the preceding neural network since the network was trained for toy datasetwe will plot the total losses after each epoch for different optimizersinstead of plotting the validation accuracy we can study the outputs loss across epochs for each optimization variant showcased in figure - listing - training model with various optimizers #define loss function loss_function nn bceloss(#binary crosss entropy loss num_epochs batch_size= #define model object from the class defined earlier model neuralnetwork(
15,566
feed-forward neural networks #train network using rmsprop optimizer rmsprp_optimizer tch optim rmsprop(model parameters(lr= alpha= eps= - weight_decay= momentum= centered=trueprint("rmsprop "rmsprop_loss train_network(model,rmsprp_optimizer,loss_ function ,num_epochs,batch_size,x_train,y_train#train network using adam optimizer model neuralnetwork(adam_optimizer tch optim adam(model parameters(),lr print("adam "adam_loss train_network(model,adam_optimizer,loss_function ,num_epochs,batch_size,x_train,y_train#train network using sgd optimizer model neuralnetwork(sgd_optimizer tch optim sgd(model parameters()lr= momentum= print("sgd "sgd_loss train_network(model,sgd_optimizer,loss_function ,num_epochs,batch_size,x_train,y_train#plot the losses for each optimizer across epochs import matplotlib pyplot as plt %matplotlib inline epochs range( ,
15,567
feed-forward neural networks ax plt subplot( ax plot(adam_loss,label="adam"ax plot(sgd_loss,label="sgd"ax plot(rmsprop_loss,label="rmsprop"ax legend(plt xlabel("epochs"plt ylabel("overall loss"plt title("loss across epochs for different optimizers"plt show(output[rmsprop epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: adam epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: epoch loss:
15,568
feed-forward neural networks epoch loss: epoch loss: epoch loss: sgd epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: epoch loss: figure - distribution loss across epochs for the network
15,569
feed-forward neural networks summary the content in this about feed-forward neural networks will serve as the conceptual foundation for the remainder of the book the key concepts we covered were the overall structure of the neural networkthe inputhiddenand output layersand cost functions and their basis on the principle of maximum likelihood we also explored pytorch as means for practically implementing neural network in the last exercisewe experimented with training the network with various optimizers over toy dataset in order to study how the losses reduced over epochs in the next we will explore automatic differentiation in deep learning
15,570
automatic differentiation in deep learning while exploring stochastic gradient descent in we treated the computation of gradients of the loss function xl(xas black box in this we open the black box and cover the theory and practice of automatic differentiationas well as explore pytorch' autograd module that implements the same automatic differentiation is mature method that allows for the effortless and efficient computation of gradients of arbitrarily complicated loss functions this is critical when it comes to minimizing loss functions of interestat the heart of building any deep learning model lies an optimization problem that is invariably solved using stochastic gradient descentwhichin turnrequires one to compute gradients automatic differentiation is distinct from both numerical and symbolic differentiation we start by covering enough about both of these so that distinction becomes clear for the purposes of illustrationassume that our function of interest is and we intend to find the derivative of fdenoted by '( (cnikhil ketkarjojo moolayil ketkar and moolayildeep learning with python
15,571
automatic differentiation in deep learning numerical differentiation numerical differentiationin its basic formfollows from the definition of derivative/gradient it used to estimate the derivative of mathematical function derivate of with respect to more specifically defines the rate of change of with respect to simple way would be to compute the slope of the function through the line xf(xand +hf( +hsogiven that df  dx we can compute the '(xusing the forward difference method as dh setting suitably small value for similarlywe can compute '(xusing the backward difference method as againby setting suitably small value for more symmetric form is the central difference approachwhich computes as extrapolation is process of using known values to project value outside of the intended existing known range richardson extrapolation
15,572
automatic differentiation in deep learning is technique that helps in achieving for estimating very high order integration using only few series of values the approximation errors for forward and backward differences are in the order of hthat iso( )--whereas those for central difference and richardson extrapolation are ( and ( )respectively the key problems with numerical differentiation are the computational costswhich grow with the number of parameters in the loss functionthe truncation errorsand the round off errors the truncation error is the inaccuracy we have in the computation of '(xdue to not being zero the round off error is inherent to using floatingpoint numbers and floating-point arithmetic (as opposed to using infinite precision numberswhich would be prohibitively expensivenumerical differentiation is thus not feasible approach for computing gradients while building deep learning models the only place where numerical differentiation comes in handy is quickly checking whether gradients are being computed correctly this is highly recommended when you have computed gradients manually or with new/unknown automatic differentiation library ideallythis check should be put in as an automated check/assertion before starting sgd note numerical differentiation is implemented in python package called scipy we do not cover it hereas it is not directly relevant to deep learning
15,573
automatic differentiation in deep learning symbolic differentiation symbolic differentiation in its basic form is set of symbol rewriting rules applied to the loss function to arrive at the derivatives/gradients consider two of such simple rules dx dx dx and nx dx given function such as ( we can successively apply the the symbol writing rules to first arrive at dx dx by applying the first rewriting ruleand by applying the second rule symbolic differentiation is thus automating what we do when we derive gradients manually of coursethe number of such rules can be largeand more sophisticated algorithms can be leveraged to make this symbol rewriting more efficient in its essencehoweversymbolic differentiation is simply the application of set of symbol rewriting rules the key advantage of symbolic differentiation is that it generates legible mathematical expression for the derivative/gradient that can be understood and analyzed the key problem with symbolic differentiation is that it is limited to the symbolic differentiation rules already definedwhich can cause us to hit roadblocks when trying to minimize complicated loss functions
15,574
automatic differentiation in deep learning an example of this is when your loss function involves an if-else clause or for/while loop in sensesymbolic differentiation is differentiating (closed formmathematical expressionit is not differentiating given computational procedure another problem with symbolic differentiation is that naive application of symbol rewriting rulesin some casescan lead to an explosion of symbolic terms (expression swelland make the process computationally unfeasible typicallya fair amount of compute effort is required to simplify such expressions and produce closed form expression of the derivative note symbolic differentiation is implemented in python package called sympy we do not cover it hereas it is not directly relevant to deep learning automatic differentiation fundamentals the first key intuition behind automatic differentiation is that all functions of interest (which we intend to differentiatecan be expressed as compositions of elementary functions for which corresponding derivative functions are known composite functions thus can be differentiated by applying the chain rule for derivatives this intuition is also at the basis of symbolic differentiation the second key intuition behind automatic differentiation is that rather than storing and manipulating intermediate symbolic forms of derivatives of primitive functionswe can simply evaluate them (for specific set of input valuesand thus address the issue of expression swell because intermediate symbolic forms are being evaluatedwe do not have the burden of simplifying the expression note that this prevents us from
15,575
automatic differentiation in deep learning getting closed form mathematical expression of the derivate like the one symbolic differentiation gives uswhat we get via automatic differentiation is the evaluation of the derivative for given set of values the third key intuition behind automatic differentiation is that because we are evaluating derivatives of primitive formswe can deal with arbitrary computational procedures and not just closed form mathematical expressions that isour function can contain if-else statementsfor loopsor even recursion the way automatic differentiation deals with any computational procedure is to treat single evaluation of the procedure (for given set of inputsas finite list of elementary function evaluations over the input variables to produce one or more output variables although there might be control flow statements (if-else statementsfor loopsetc )ultimatelythere is specific list of function evaluations that transform the given input to the output such list/evaluation trace is referred to as wengert list to understand how automatic differentiation specifically works for deep learning use caselet' take simple functionwhich we will compute manually using chain ruleand also look at the pytorch equivalent of implementing the same in deep learning networksthe entire flow is represented using computational graphwhich is directed graph where nodes represent mathematical operations this provide an easy to evaluate mathematical expression computational graphs can be translated into data structure to programmatically approach the problem using computer programming languagesthereby making solving larger problems more intuitive we will use relatively small and easy to compute function to work through our example assume that (xyz( )* and that we have values for the three variables as = =- and = we can represent this function using computational graphas shown in figure -
15,576
automatic differentiation in deep learning figure - computational graph along with the input variables (xyand )we will see the variable awhich is an intermediate variable that stores the computed value of ( )and the variable fwhich stores the final value of ( ) -- * in the forward passwe will substitute the values and arrive at the final value as =- then( ) ( ) - thereforef - we can visualize this using the computational graph shown in figure -
15,577
automatic differentiation in deep learning figure - computational graph with computed values nowwith automatic differentiationwe would want to find the gradients of with regard to the input variables (xyand zrepresented as and in the feed-forward networkessentiallywe find the gradients of the loss function with respect to the weights to solve thiswe can use the chain rule let' find the partial derivatives for the above equation we know that ( ) and thus az thereforef az ( ( - and az if we go one step furtherwe can find the partial derivatives of with regard to and and
15,578
automatic differentiation in deep learning nowcoming to our end objectiveto find the gradients of with regard to xy and we already have computed the required gradient with regard to for and ywe can leverage the previously computed values in chain rule as we now have computed all the values required - and essentiallywhat network would infer is that and positively influence the outcomewhereas negatively influences it (figure - this information is useful to reduce the loss and updates the weights of the network incrementally to reach the minima figure - computational graph with partial derivatives
15,579
automatic differentiation in deep learning implementing automatic differentiation let' now consider how automatic differentiation is implemented within pytorch the preceding example was very simplethings would be really complicated as we explore the approach on paper for large functions ( deep learning functionsin most common networksthe number of parameters that would be involved is very highmaking manually programming the computation of gradients herculean task pytorch provides the autograd packagewhich essentially simplifies the entire process for us recall the loss backward(function that we leveraged in for the toy neural network the network computes all the necessary gradients for the loss with respect to the weights let' explore this further what is autogradthe autograd package within pytorch provides automatic differentiation for all operations on tensors it performs the necessary computations within backpropagation for our neural network when the backward(function is calledthe module computes all the backpropagation gradients automatically we can also access individual gradients through variable' grad attribute the autograd module provides ready to use tools (functions/classesfor implementing automatic differentiation of arbitrary scalar valued functions to enable gradients to be computed for variablewe need only to set the value as true for the keyword requires_grad let' replicate the same example we used to manually implement automatic differentiation but using pytorch (listing -
15,580
automatic differentiation in deep learning listing - implementing automatic differentition (autogradin pytorch #import required libraries import torch #define ensors torch tensor([ ] torch tensor([- ]ztorch tensor([ ]print("default value for requires_grad for :", requires_grad#set the keyword requires_grad as true (default is falsex requires_grad=true requires_grad=true requires_grad=true print("updated value for requires_grad for :", requires_ grad#compute #finally define the function print("final value for function ", #compute gradients backward(#print the gradient value print("gradient value for :", gradprint("gradient value for :", gradprint("gradient value for :", grad
15,581
automatic differentiation in deep learning output[default value for requires_grad for xfalse updated value for requires_grad for xtrue final value for function tensor([- ]grad_ fn=gradient value for xtensor([ ]gradient value for ytensor([ ]gradient value for ztensor([- ]the gradient values here match exactly with what we computed manually earlier in the preceding examplewe first created tensor and then assigned the keyword for requires_grad as true we can also combine this along with our definition torch autograd variable(torch tensor([ ]),requires_ grad=truewhile we define network in pytorcha lot of these details are taken care of when we define network layerwith nn linear( (refer to the example)pytorch creates the weight and bias tensor with the necessary values (setting requires_grad as truethe input tensors did not need the gradientshencewe never set them in our example and used the default ( falses ummary this covered the basics of automatic differentiation backpropagation is special case of automatic differentiation used in training deep neural networks in modern deep learning literatureautomatic differentiation is analogous to backpropagationas it more
15,582
automatic differentiation in deep learning generalized term the key takeaway from this is that automatic differentiation enables the computation of gradients for arbitrarily complex loss functions and is one of the key enabling technologies for deep learning you should internalize the concepts of automatic differentiation and how it differs from both symbolic and numerical differentiation in the next we will study some additional topics related to deep learning in more detailincluding performance metrics and model evaluationanalyzing overfitting and underfittingregularizationand hyperparameter tuning finallywe will combine all the foundational bits about deep learning we've covered so far into practical example that implements feed-forward neural networks for real-world dataset
15,583
training deep leaning models so farwe have leveraged toy datasets to provide an overview of the earliest implementations of deep learning models in this we will explore few additional important topics around deep learning and implement them in practical example we will delve into the specifics of model performance and study the details of overfitting and underfittinghyperparameter tuningand regularization finallywe will combine what we've discussed so far with real dataset to illustrate practical example using pytorch erformance metrics in when we designed our toy neural networkwe defined loss functions that would measure the disagreement between the prediction and the actual label let' explore this topic in more meaningful way based on the type of target variable (continuous or discrete)we would need different types of performance metrics the upcoming sections discuss the metrics within each category (cnikhil ketkarjojo moolayil ketkar and moolayildeep learning with python
15,584
training deep leaning models classification metrics the model development process typically starts by formulating clear problem definition this basically involves defining the input and the output of the model and the impact (usefulnesssuch model can deliver an example of such problem definition is the categorization of product images into product categories--the input to such model being product images and the output being product categories such model might aid the automated categorization of products in an ecommerce or online marketplace setting having defined the problem definitionthe next task is to define the performance metrics the key purpose of performance metrics is to tell us how well our model is doing simple metric of performance may be accuracy (orequivalentlythe error)which simply measures the disagreements between the expected output and the output produced by the model accuracyhowevercan be poor measure of performance the two main reasons are class imbalance and unequal misclassification costs let' look at the class imbalance problem with an example as subproblem of the problem in our previous example of product classificationconsider the case of distinguishing between mobile phones and their accessories the number of examples for classes of mobile phones is lot smaller that the classes of mobile phone accessories iffor example of the examples are mobile phone accessories and are mobile phonesan accuracy of can be simply acquired by predicting the majority class thusaccuracy is poor choice of metric in this example let' now understand the problem of unequal misclassification costsagain by considering an example related to the problem of product classification consider the error associated with categorizing food products that are allergen-free (not containing the eight top allergens-namelymilkeggsfishcrustacean shellfishtree nutspeanutswheatand soybeanversus the rest (non-allergen-freefrom buyer' point of viewas well as business point of viewthe error associated with
15,585
training deep leaning models categorizing non-allergen-free product as an allergen-free product is significantly more as compared to categorizing an allergen-free product as non-allergen-free product accuracy does not capture this and hence would be poor choice in this case an alternative set of metrics is precision and recallwhich measure the fraction of predictions in the predicted class that were correctly recoveredand the fraction of the predicted class that were reportedrespectively (see figure - togetherprecision and recall are robust with respect to class imbalance figure - precision and recall
15,586
training deep leaning models precision and recall are often visualized using pr curvewhich plots precision on the axis and recall on the axis (see figure - different values of precision and recall can be obtained by varying the decision threshold on the score or the probability the model produces--for instance implying class aand implying class bwith higher value on one side indicating particular class this curve can be used to trade off precision for recall by varying the threshold figure - pr curve pr where denotes precision and denotes + recallcan be used to summarize the pr curve the receiver operating characteristic (roccurve is useful in cases of class imbalance and unequal misclassification costs in this settingexamples are said to belong to two classespositive and negative the -scoredefined as
15,587
training deep leaning models the true positive rate measures the fraction of true positives with respect to the actual positivesand the true negative rate measures the fraction of true negatives with respect to the actual negatives (see figure - the roc curve plots the true positive rate on the axis and the false positive rate on the axis (see figure - the area under the curve (aucis used to summarize the roc curve in many casesstandard metrics like accuracyprecisionrecalletc do not allow us to truly capture model performance for the business use case at hand in such casesmetrics appropriate to the business use case need to be formulatedkeeping in mind the nature of the problemthe class imbalanceand the misclassification costs for instancein our running example of product categorizationwe may choose to not use predictions with low confidence and have them categorized manually there is cost associated with having examples manually categorizedand there is different cost associated with showing wrong products in the wrong category on an ecommerce site the cost of misclassifying popular product is also different (typically higherfrom the cost of misclassifying rarely bought product in such casewe might choose to use only the high confidence predictions from the model possible choice of metrics to use would be the number of examples misclassified (with high confidenceand the coverage (the number of examples covered with high confidenceone may also factor in the misclassification cost in this setting by taking weighted average of the two (appropriate weights may be chosen based on the misclassification costs metric definition is critical step of the model-building process in an industry setting practitioners should deeply analyze the business domainto understand the misclassification costsand the datato understand the class distributionsand design performance metrics accordingly badly defined metric can lead project down an incorrect path
15,588
training deep leaning models figure - true positive and false positive rates
15,589
training deep leaning models figure - roc curve egression metrics performance metrics for regression are fairly straightforward when compared to metrics for classification the most common metric that can be universally applied to most use cases is the mean squared error (msedepending on the use casea few other metrics could be used for more favorable outcomes consider the problem of predicting the monthly sales for given storewhere store sales could range from $ , to $ , across months the following sections explore few popular choices mean squared error we have already explored the mean squared error (msein "feed-forward neural networks as the name suggeststhe mse is the mean of the squared differences between the actual values and the
15,590
training deep leaning models predicted values the end result is positive numberas we take square of the disagreement essentiallythe square operation is valuable because larger differences are penalized more in use cases where you wouldn' want the model to penalize large difference more heavilymse would not be the ideal choice the lower the mse for given modelthe better the performance for the model mathematicallywe can define mse as mse yi ^ = yrmse = mean absolute error the mean absolute error (maecomputes the mean of the absolute difference between predictions and target the outcomewhich is always positiveis much more interpretable performance metric than mse for regression use cases the lower the mae for model the better the performance mathematicallywe can define mae as mae yi ^ = mean absolute percentage error the mean absolute percentage error (mapeis the percentage equivalent of the mae given its relative natureit is by far the most interpretable performance metric for regression the lower the mape for modelthe better the performance for the model
15,591
training deep leaning models mathematicallywe can define mape as mape yi ^ = yi while being highly interpretablemape suffers when dealing with small differences the percentage differences of small deviations often result in large mapewhich could lead to misleading results supposefor examplethat we are predicting the number of days sales will be observed for given store and the target values range from to when the actual value is and the predicted value is the mape is %whereas when the actual value is and the predicted value is the mape is data procurement data procurement is the process of collecting data for building model according to problem statement data procurement can involve collecting old (already generateddata from production systemscollecting live data from production systemsandin many casescollecting data labeled by human operators (via crowdsourcing or internal operations teamsin our running example of product categorizationproduct titlesimagesdescriptionsetc would need to be collected from company catalogueand labeled data could be generated using crowdsourcing we might also want to collect click data and sales to determine the popular products (misclassification in these cases would be costly data procurement typically happens in conjunction with the process of defining the problem statement and success metrics it is imperative that practitioner play an active role in the data procurement process typicallyin an industry settingdata procurement is fairly time-consuming and painful process subtle errors in data procurement can derail project at later stage
15,592
training deep leaning models plitting data for trainingvalidations and testing once the data for building the model has been procuredit needs to be split into data for trainingparameter tuningand go-live testing conceptuallythe available data is to be used for three distinct purposes the first purpose is to train the model--that isthe model will try to fit this data the second purpose is to determine whether the model is overfitting the datathis dataset is called the validation set this data will not be used for training but will drive the decision-making on hyperparameter tuningregularization techniquesetc (we will discuss these topics in greater detail later in this the third purpose of the data is to determine whether the model is really good enough to take to production/go-live (referred to as the test setthe first key concept to internalize is that data cannot be shared for these three purposesa distinct portion of the data is required for each purpose if certain portion of the data has been used to train the modelit cannot be used to tune the hyperparameters of the model or serve as the final performance gate (production/go-livesimilarlyif certain portion of the data has been used for tuning parametersit cannot serve as the test data for production/go-live thusa practitioner needs to split data into three partstrainingparameter tuning and go-live while the idea that training data should be distinct from data used for parameter tuning is intuitivethe reasoning behind having distinct go-live set is not the key point to internalize is that if the model has seen the data or the modeler has seen the datathen this data has fundamentally driven some decisionmaking around the model and cannot be used for final go-live testing if we need the test to be truly blind truly blind implies never looking at the data (and the labelsor never using it for making any decision that goes into building the model one must not tune the model any further by looking at the results on the go-live testing set
15,593
training deep leaning models the second key point to internalize is that each of the three sets-traininghyperparameter tuningand go-live testing--need to be true representative of the underlying population of data splitting the datasets should take this into consideration for examplethe distribution of examples across the classes should be the same as the underlying population if the data is not true representation (that isif the data is biased in any way)then the performance of the model will not be achieved once the model goes to production the third key point to internalize is that more data is always better for any of the three purposes because the datasets cannot overlap and the overall dataset is limiteda practitioner needs to carefully choose the fraction of the data used of each purpose split or split across trainingvalidationand testing are reasonable choices establishing the achievable limit on the error rate having defined the problem and performance metricsand having procured and split the data into trainingparameter tuningand golive test setthe next step is to establish the achievable limit on the error rate conceptuallythis is the error rate one can hope to achieve given an infinite supply of data and is referred to as the bayes error establishing the limit on the error rate in ai tasks is typically done via proxy-like human labelling or variations on the theme appropriate to the business use case variations may include using an expert on the subject to label the dataa panel of human beingsor panel of experts establishing this limit is quite valuable and well worth the expenditure of human/expert help firstit establishes the best possible results that can be achievedwhichin certain casesmight not be good enough to satisfy the business use case (in which case the problem formulation needs to be rethoughtsecondit tells us how far our current model is from the best achievable results
15,594
training deep leaning models establishing the baseline with standard choices the best place to start the modelling process is with baseline model with standard choices (based on literature or part experienceof architecture and algorithms--for instanceusing convolutional neural networks (cnnsfor images or long short-term memory (lstmnetworks for sequences (both topics will be covered in upcoming using rectified linear units (relusas activation units and batch stochastic gradient descent (sgdare also good choices to start with basicallythe baseline model establishes straw man on which to improve based on an analysis of the shortcomings building an automatedend-to-end pipeline having decided upon baseline modelit is of critical importance to build an end-to-endfully automated pipeline that includes training the model on the training setmaking predictions on the parameter tuning setand computing the metrics on both sets automation is extremely importantas it enables the practitioner to iterate quickly on new models by tweaking the model architecture and hyperparameters orchestration for visibility while building the end-to-end pipelineit' also good idea to put in the orchestration to visualize histograms of activationsgradientsmetrics on training and validation setsetc visibility into the model trainingweightsand performance can be quite useful when it comes to debugging unexpected behavior the key point is to build the automation and orchestration for visibility to begin with this will save lot of time and energy in the future
15,595
training deep leaning models analysis of overfitting and underfitting the ideal goal of the iterative cycle of model improvement is to develop model where the performance over the training set and validation set is nearly equal to the established performance limit (proxy for bayes errorfigure - illustrates this final destination of the model improvement process while iteratively developing new modelshoweverthe practitioner will encounter underfitting and overfitting underfitting occurs when the model' performance over the training and validation set is nearly equal but the performance is below the desired level this is an outcome of poorly developed model in which the parameters have not appropriately captured the patterns within the training data on the other handoverfitting occurs when the model performance over the validation set is significantly lower than its performance over the training set this is direct outcome of model that has learned far too many complicated patterns that should have ideally been considered as noise such model (which accounted for noise in the data as valid patternsdelivers top performance on the training (seendata but performs poorly on unseen data underfitting and overfitting are not mutually exclusive in scenario where model is underfittingwe more formally define this situation as model with high bias similarlywhen model that has learned several complex patterns from noise delivers highly inconsistent performance on unseen datawe say the model has high variance ideallywe would need model that has low bias and low variance detecting whether the model is overfitting or underfitting is the first step after new model is trained in the case of underfittingthe key step is to increase the effective capacity of the modelwhich is typically done by modifying the architecture (increasing layerswidthsand so forthin the case of overfittingthe key steps are either regularization methods (covered later in this or increasing the dataset size an important visualization is learning curveswhich plot performance metrics on the axis and the training data made available to the model on the axis this is quite useful in determining whether an investment in procuring more labelled data makes sense
15,596
training deep leaning models figure - overfitting and underfitting hyperparameter tuning tuning the hyperparameters of the model (such as learning rate or momentumcan be done manuallyvia grid search (where in grid is defined over small set of values)or via random search (where the values of hyperparameters are drawn at random from distribution defined by the userin grid searchthe practitioner has to create small subset of potential values (since compute resources are finitefor each hyperparameter in the network the training process essentially loops
15,597
training deep leaning models through each possible combinationand the combination of the hyperparameters with the best performance is the final choice with grid searchthere is possibility of not having the best possible combination of hyperparametersas the permutations are limited to the provided grid or are computationally very expensiveif large number of choices are added to the grid random search usually tends to fair better with hyperparameter tuning with random searchthe possibilities of having the best combination of hyperparameters for the model are higher with fairly lower number of combinations (though not guaranteedtuning hyperparameters is often iterative and experimental odel capacity let' briefly revisit the notions of model capacityoverfittingand underfitting we will use the previous example of fitting regression model (refer to we have data of the form {( )( )(xnyn)}where rn and rand our task is to generate computational procedure that implements the function we measure performance over this task as the root mean squared error (rmseover unseen dataas follows yi xi du  given dataset of the form {( )( )(xnyn)}where rn and rwe use the least squares modelwhich takes the form bx where is vector such that is minimized herex is matrix where each row is an the value of can be derived using the closed form (xtx)- xty
15,598
training deep leaning models we can transform to be vector of values [ that isif it will be transformed to [ following this transformationwe can generate least squares model using the preceding formula under the hoodwe are approximating the given data with second order polynomial (degree equationand the least squares algorithm is simply curve fitting or generating the coefficients for each of [ similarlywe can generate another model with the least squares algorithmbut we will transform to [ that iswe are approximating the given data with polynomial with degree by increasing the degree of the polynomialwe can fit arbitrary data it is easy to see that if we have data pointsa polynomial of degree can perfectly fit the data it is also easy to see that such model is simply memorizing the data we can use this example to develop perspective on model capacityoverfittingand underfitting the degree of the polynomial we use to fit the data is basically proxy for the capacity of the model the greater the degreethe higher is the capacity of the model let us assume that the data were generated using polynomial of degree with some noise alsonote that while fitting the datawe do not know anything about the process that generated the data we have to produce model that best fits the data essentiallywe do not know how much of the data is the pattern and how much of the data is noise on such datasetif we use models with high enough capacity (degree of the polynomial greater than in the worst case equal to the number of data points)we can get perfect model when evaluated on the training datahoweverthis model will do very poorly on unseen databecause it has essentially fit the noise this is overfitting if we use model with low capacity (less than )it will fit neither the training data nor the unseen data well this is underfitting
15,599
training deep leaning models regularizing the model from the previous exampleis easy to see that while fitting modelsa central problem is to get the capacity of the model exactly right so that one neither overfits nor underfits the data regularization can be simply seen as any modification to the model (or its training processthat intends to improve the error on the unseen data (at the cost of the error on the training databy systematically limiting the capacity of the model this of process systematically limiting or regulating the capacity of the model is guided by portion of the labelled data that is not used of training this data is commonly referred to as the validation set in our running examplea regularized version of least squares takes the form bxwhere is vector such that is minimizedand is user-defined parameter that controls the complexity hereby introducing the term we are penalizing models with extra capacity to see why this is the caseconsider fitting least squares model using polynomial of degree but the values in the vector have zeros and non-zeros as opposed to thisconsider the case where all values in the vector are non-zeros for all practical purposesthe former model is model with degree and lower value of the term allows us to balance accuracy over the training data with the complexity of the model lower values of imply model with lower capacity one natural question to ask is why we do not simply use the validation set as guide and increase the degree of the polynomial in the previous example since the degree of the polynomial is proxy for the capacity of the modelwhy can' we use that to tune the model capacitywhy do we need to introduce the change in the model instead of previously)the answer is that we want to systematically limit the capacity of the model for which we need fine-grained control changing the model capacity by varying the degree of the model is very coarse-graineddiscrete knobwhile varying is very fine grained