Neural Network Gradients
Transcript
So let's say we have a neural network of some complexity. It doesn't have to be enormous, but it's a bit more than just a simple logistic regression. It has a bunch of weights, it's got some hidden layers, some nonlinear activation functions. The question is, how do we train such a network? For previous examples like linear SVMs, logistic regression itself, lasso, and so on, we found that gradient descent and similar methods was an effective way of doing things. But all of those
have relatively simple gradients or subgradients that we can calculate. For a big compound function like a neural network, how are we supposed to figure out what effect some arbitrary weight, buried right in the middle of the network, is having on our ultimate loss, all the way down at the end? So, one way we could do this is to calculate a numerical gradient at each case. So if you think back to how the derivative is defined, as the limit of this expression - where we're looking
at the change in the output of our function f with a small increment, divided by the size of that increment. If we just dispense with the limit and calculate this at some appropriately small value of delta, we can get a numerical approximation of what the limit might be if you take it all the way to zero. This approach to finding the gradient is extremely straightforward, it's easy to understand, and it's easy to implement. It's also very widely applicable. It
places almost no constraints on the kind of functions that you can use it with. All that's required is that the function behaves vaguely coherently, that it is defined both that x and x plus delta. And we have to be able to assume that the line between those two points is somewhere close to what the function actually does in between. The problem with this approach is that it is incredibly slow. For all of the parameters or weights in your network, you have to twiddle
that one individually, and then run the entire network to see what kind of effect it has on the output. If you've got a network with a large number of different weights, then evaluating it is going to take quite a long time and doing it as many times as there are weights is just going to take forever. So in general, this is not really a practical approach to training big neural networks. In previous cases, like logistic regression, we have derived the gradients analytically. Where
it's feasible to do this, this is the smart and principled and efficient choice. It gives us a direct analytic expression for the gradients that we can easily evaluate. However, it's kind of fiddly, even in the best examples. And for very large complicated compound functions, it becomes almost completely intractable to figure out all that algebra by hand. It's also extremely error prone. It's very, very easy to make some minor mistake in the algebra somewhere way over there. And
then that just throws everything out throughout your entire model. And yet, as mentioned back in week two, most of this is based on the chain rule for differentiation. And the chain rule is pretty straightforward, and mechanical. So it seems like there ought to be a way to avoid or at least automate some of that algebra, and thereby get the analytic gradients more easily. So let's just recap what the chain rule says. It boils down to: gradients multiply. There are a number of different
ways of notating this, which don't always necessarily make things that much clearer. Here is the Leibniz notation, we would say, dy by dx is equal to dy by du multiplied by du by dx. Or in function composition notation, we might say that the derivative of the combined function, which is f compose g prime, is equal to the derivative of f composed with g, times by the derivative of g. In both of these cases, it's important to keep track of where each derivative is
evaluated. The output of one function becomes the input to the next. And so in each case, that's where the derivatives will be evaluated too. So we see, for example, that f of g of x the derivative of all that is equal to the derivative of f evaluated at g of x, multiplied by the derivative of g evaluated at x. This can be applied to sequences of any number of functions. So for example, the derivative of f of g of h of x is the derivative of f evaluated at g of h of x, multiplied by the
derivative of g evaluated h of x, multiplied by the derivative of h evaluated at x. Computationally or programmatically, we might think of this as just making a series of nested function calls. We could also unwrap this with intermediates at each point. So for example, here we have b is equal to f of a, c is equal to g of b, d is equal to h of c. In each case, the output of one function becomes the input to the next. One way of representing this kind of sequence of
operations is as a directed graph, where the nodes in the graph represent the operations and the edges represent the flows of data. So here is a simple example just with f and g, as before. Data flows through this graph, so x comes into f, f of x flows through to G, and out of the end we get g of f of x. Each of the operations in this graph has its own gradient, like this. So the gradient at f is just f prime of x, the gradient at g is g prime of f of x. The gradients also flow through the
graph, multiplying along the way. Now, multiplication is commutative. When we have the full symbolic expressions like this, there's no particular direction implied. But it will be useful later to consider that the gradients flow backwards from the end to the beginning. So we'll use that representation for now, too. We can see that the gradient of the entire graph is just this product of the gradients at each of the nodes, giving us f prime of x times g prime of f of x,
which is exactly what we'd expect from the symbolic representation of the chain rule. Let's try a couple of explicit simple examples of operations like this. Here's another two node graph, where the first node is a sine operation, the second node is an exponential. If we pass in x, then sin x flows to the exponential and x sin x comes out at the end. Again, these operations have known gradients. The derivative of sin is just cos, the derivative of exp is just the same
as the output. So in this case, it's exp of sin x. Once again, we can multiply this backwards through the graph and get that the overall derivative is cos x multiplied by exp of sine x. We can do this also for graphs with more than two nodes. Here is a simple sequence of four different operations. The first one is a negation, multiplication by minus one. The second one is exponentiation. The third one is an addition or an increment, the
addition of one. And then the last one is a reciprocal. Once again, passing some value x into this graph, after the first node, it becomes minus x, after the second node it becomes e to the minus x, after the third it becomes one plus e to the minus x, and after the fourth, it becomes one over one plus e to the minus x. You may recognise this as the sigmoid or logistic function from previous weeks. Once again, each node has its own local derivative. The derivative of multiplying by
minus one is minus one. The derivative of the exponential is again, the output of the exponential. The derivative of adding one is just one, it doesn't change the slope. And the derivative of the reciprocal is minus one over the input squared. So taking into account the inputs at each node, this gives us these expressions as the local gradients, and when we propagate this back, we get this value here, e to the minus x over one plus e to the minus x, all that squared. When we
calculated the derivative of the sigmoid, back in week 2 for logistic regression, we did a bunch of additional steps and simplifications to get a nice, elegant algebraic form of the derivative out at the end. In this case, we're not going to do that. We really don't care about the neat algebra, we just want an answer. So we've got a chain of multiplications here. Multiplication is associative, and we can bracket it however we like. In this case, we're going to bracket it as a series of
pairwise multiplications, starting from the end. When we separate these out, we get this kind of sequence of pairwise multiplications here. And note that this gives us the overall gradients with respect to the final output for each of the individual nodes along the sequence, as well as, right at the beginning, the derivative of the entire expression. So far, we've considered only simple sequences of operations. But you can do the same thing with graphs where there are branches.
So for example, here is a simple graph where the node takes multiple inputs. In this case, the first node is just a multiplication, it takes both of its inputs and multiplies them together. The second node is the sigmoid operation that we just looked at in the previous case. In that previous example, we broke the sigmoid up into its component operations. As it happens, we already know what the sigmoid derivative is. And so in this case, let's just consider it as a self contained
operation. When we run a couple of values into this small network, let's call them, for no particular reason, x and w, they both go into the multiplication node, their product xw goes into the sigmoid node, and the output of the whole network is the sigmoid of xw. The gradient at the sigmoid node is just the derivative of the sigmoid, operating on xw. For the first node, the multiplication node, there are two distinct gradients, there is the gradient with respect to x and gradient
with respect to w. It's just a multiplication, so the gradient of xw with respect to x is w, the gradient of xw with respect to w is x. Once again, we propagate the gradients back by multiplying along. And so the overall gradient of the expression with respect to x is the product of w and the gradient of the sigmoid of xw, and the gradient of the overall expression with respect to w is x times the sigmoid gradient. So so far, we've been considering this symbolically, and it's
still a bit clunky. We're sort of reiterating what we know about the chain rule, but we're still having to carry around a bunch of nested algebraic terms. However, gradients are just numbers. We don't need the full analytic expression for the gradient at each point, we only need its single numeric value for the particular case we are looking at. We need it, specifically, because we want to use it to update our model parameters. We don't care about its full algebraic expression.
So if we just treat everything as numbers at every stage, the whole thing actually becomes quite a bit cleaner. Let's revisit the previous examples. Here we have our sin going into exp. Let's arbitrarily pick an input value of 2. The sin of 2 is about 0.91, that passes into the exp. The exp of 0.91 is about 2.48. Calculating the local gradients for each operation, well, the gradient of the exponential is just the output of the exponential. So that local gradient is 2.48. The
derivative of sine is still cosine, the cosine of that input value 2 is about minus 0.42. If we multiply those together, then we find that the gradient of the entire expression given that the input is two is something around minus 1.04. Doing a similar kind of thing with our sequence of four operations that make up the sigmoid or logistic function. Let's throw in the value 1.5 as the input. The first node multiplies that by minus one, so minus 1.5 gets passed into the exponential.
The exponential of that is about 0.22. We add one to that to get 1.22, and take the reciprocal to get about 0.82. Once again, we can calculate the local gradients at each point, as numerical values, from the analytic expression of the local gradients. And so the gradient of the negation is still minus one, the gradient of the plus one is still plus one, the gradient of the exponential is still the output of the exponential so that's 0.22 or thereabouts, and the gradient
and the reciprocal is minus one over the square of the input, so that's about minus 0.67. Taking the product of all of these terms backwards, we find that the overall gradient of the entire expression is about 0.15. And if we once again bracket it pairwise, and evaluate all of those pairs, we also get numerical values for the gradients at each of the nodes. Finally, looking at our graph with two different inputs, and arbitrarily picking x equals minus 1.2 and w equals 0.3, we
find the output of the multiplication is minus 0.36. The output of the sigmoid is about 0.41. We have an analytic gradient for the sigmoid function, so if we just apply that to minus 0.36, the input, we get the gradient at the sigmoid node is about 0.24. For the multiplication, we know that the gradients will be w for x and x for w. And so we can just write those down here numerically. Taking the products back, we find that the overall gradient of the entire expression with
respect to the input of minus 1.2 is about 0.07. And similarly, the overall gradient with respect to the weight at 0.3 is about minus 0.29. If we again think about this programmatically, we might have a sequence of operations where the output of each one is kept as an intermediate variable. So we got out1 equals f1 of x, out2 equals f2 of out1, and so on. If we want to calculate the gradients, we can start at the end, let's say we know the local derivative of
each of those functions, f5, f4, f3, f2 and f1. So we calculate the local derivative of the function f5 at its input value out4 And that gives us the gradient of the output loss with respect to out4. Similarly, calculating the local gradient of f4, df4, for its input value out3, and multiplying that by the loss with respect to out4 - which we already calculated - gives us the loss with respect to out3. And we can keep doing that all the way down until we have the gradient of the output with
respect to the input. And we also have the gradients at each operation along the way. In each case, all we've needed is the local gradient and the gradient downstream. In this kind of graph representation, with calculating the gradients and passing them around just as numbers, we see that each node is a little locality all to itself. The node lives in a bubble, it keeps track of its own inputs and outputs, and it knows how to calculate its own local gradient. It propagates data
forwards to any number of downstream nodes that it doesn't need to know about or care about. And at some point in the future, it receives back a number, which is the gradient of whatever is happening in the rest of the network, which it just doesn't need to know about, and it can use that to calculate the gradient of whatever is happening in the rest of the network that it doesn't need to know about with respect to its own inputs. It can then propagate those gradients further back into the network. The node never needs to know what the whole rest of the network is doing. It only needs its local information and what it gets handed. One question you might reasonably ask at this point is what constitutes a node? Where does one operation begin and another end? In fact, we're free to choose to put node boundaries wherever we like, wherever it makes sense. You can, if you want, do as we did in the sigmoid example and break things down into extremely
simple arithmetic operations. Alternatively, if you have some compound function that has a known derivative, especially a nice easy, elegant one, like in the sigmoid example, then package all of that as a node and treat it as a single atomic operation. So far, we've considered only scalar operations in our network. But of course, in the case of neural networks, we will typically want to be doing vector operations on data vectors and weights vectors, and also matrices. In both
cases, the case with vector inputs is broadly the same as the case with scalar inputs, it's just important to keep track of what elements are where. The gradients in this case will always be passed around as vectors or possibly matrices of partial derivatives. Just as in the previous cases of vector gradients, as we've been using them all the way back to week two, the gradient vector or gradient matrix will be the same size and shape as the data or weights vector or matrix. And
all of the partial derivatives will be located in the same place. There are two important cases of vector inputs that we might particularly want to consider. One is the inner product of two vectors. This is the case for our fully connected or linear layer. The other one is an elementwise operation that acts independently on each of the elements of a vector. This is typically the case for an activation function. In the inner product or linear case, we might have a function like this,
where the output z is the dot product of two inputs, x and w. The gradient of z with respect to x is just w. And the gradient of z with respect to w is just x. You've seen this kind of thing before. If x is our input data, and w is our weights, then we will need both of these gradients. We need the gradient with respect to x to propagate backwards to the upstream nodes. And we will need the gradient with respect to w to update our own weights. In the element wise case, such as for an activation
function, where the output of the function is a vector where each of the elements is the particular scalar function applied to the individual element of the input vector. Then the gradient vector will just be the vector of the individual derivatives at each of those elements. So when building these kinds of networks, where you're passing around vectors and matrices, we try to define the layer boundaries or the node boundaries in order to reduce any really unnecessary complexity. Cast your mind back to the case of softmax regression in week two. The gradient of the softmax function requires the entire Jacobian, because it's a vector function of vector inputs, where each of the output elements depends on all of the input elements. However, when combined with a cross entropy loss, a lot of those extraneous elements disappear, and we get back to a nice, simple gradient vector.
In such a case, it would make sense to bundle the cross entropy and the softmax together into a single layer, so you don't have to pass around the Jacobian. When we have a layer with multiple outputs, the weights will be a matrix, and we need the gradient with respect to all of the elements of that matrix. And so the gradient needs to be a matrix of the same shape. When we're passing around the data as matrices, for example, in a batch or mini batch processing context, then
it's possible to pass around the full data matrix gradient, but also it might make sense to take the sum or the mean of all of those gradients and pass around only a gradient vector. In general, using the mean is a bit more stable for these cases, and it also means that the gradients are more comparable between different batch sizes. So we said that nodes or layers are self contained, they only need to care about local information and their inputs and outputs, but something needs to
keep track of the larger scale network structure. So that's usually a data structure or a class that keeps track of it all and manages the communications between the layers. Either you will have a function that traverses this data structure, or the class will have methods that do it internally. And doing so will populate all of the data at every stage along the way, and also all of the gradients. This occurs in two passes: a forward pass and a backward pass. The forward pass propagates the data
from the inputs all the way through to the end in a forward direction. The forward pass is processed in an input dependency order. That is to say, all of a node's inputs must have been calculated before that node itself can be called. Once this has happened, and you've got all the way through to the end of the network, the final stage will be a calculation of the loss. The backwards pass then starts at the end with this loss and propagates the loss gradients backwards through the
network. So it will calculate, for the very end of the network, the gradients of the loss with respect to the most recent element, and then that loss will be propagated as a number, or a vector of numbers, back to the upstream nodes. Each layer on the way will receive the downstream gradients, it will calculate its own loss, and it will propagate back the losses to earlier nodes. This continues back all the way to the inputs to the graph. At this point in the process, all of the
gradients in the network are known, and at this point, we can start thinking about learning. So backpropagation, which this whole process is called, is about calculating gradients, it is not the process of optimisation. What is then done with the gradients is up to the learning algorithm, or optimiser. This may make use of some vanilla gradient descent, or any of the variants that we have previously discussed. This optimisation policy is then used to update all of the weights in
all of the layers throughout the network according to their own individual gradients. And then the entire process can be started again, with another forward pass, another backward pass, and you keep iterating this process until some stopping criterion is reached. So one thing that we've mentioned in context of optimising many of the previous kinds of model is that their loss functions are convex. That is generally not the case for multi layer perceptrons. We've seen that
very simple neural networks without hidden layers can represent logistic regression or softmax regression, and these things do have convex losses. However, networks with hidden layers are almost always non convex. So when optimising these kinds of networks, there may well be a danger of getting stuck in local minima. How serious this is as a problem depends very much on the nature of the data and the network structure, and what the task is that you're trying to optimise
anyway. In practice, there is evidence that, at least for some kinds of network and some kinds of problem for which deep learning is commonly applied, that local minima don't actually pose a significant problem. A term that is used for some of these cases is "bad" local minima. And it turns out that for problems in computer vision, for example, it seems that although there are local minima, there are not bad ones - which is to say that any local minimum is in some way, not a bad approximation of the true global minimum.

Ask anything
We've read this whole study set, so questions about it get the best answers.