










Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!











Manning, Richard Socher
dada, Richard Socher, Qiaojing Yan
Keyphrases: Neural networks. Forward computation. Backward propagation. Neuron Units. Max-margin Loss. Gradient checks. Xavier parameter initialization. Learning rates. Adagrad. This set of notes introduces single and multilayer neural networks, and how they can be used for classification purposes. We then dis- cuss how they can be trained using a distributed gradient descent technique known as backpropagation. We will see how the chain rule can be used to make parameter updates sequentially. After a rigorous mathematical discussion of neural networks, we will discuss some practical tips and tricks in training neural networks involving: neuron units (non-linearities), gradient checks, Xavier parameter ini- tialization, learning rates, Adagrad, etc. Lastly, we will motivate the use of recurrent neural networks as a language model.
Figure 1 : We see here how a non-linear decision boundary separates the data very well. This is the prowess of neural networks. Fun Fact: Neural networks are biologically in- spired classifiers which is why they are often called "artificial neural networks" to distinguish them from the organic kind. However, in reality human neural networks are so much more capable and complex from artificial neural net- works that it is usually better to not draw too many parallels between the two.
We established in our previous discussions the need for non-linear classifiers since most data are not linearly separable and thus, our classification performance on them is limited. Neural networks are a family of classifiers with non-linear decision boundary as seen in Figure 1. Now that we know the sort of decision boundaries neural networks create, let us see how they manage doing so.
A neuron is a generic computational unit that takes n inputs and produces a single output. What differentiates the outputs of different neurons is their parameters (also referred to as their weights). One of the most popular choices for neurons is the "sigmoid" or "binary lo- gistic regression" unit. This unit takes an n-dimensional input vector x and produces the scalar activation (output) a. This neuron is also associated with an n-dimensional weight vector, w, and a bias scalar, b. The output of this neuron is then:
a = 1 1 + exp(−(wT^ x + b)) We can also combine the weights and bias term above to equiva- Neuron: A neuron is the fundamental building block of neural networks. We will see that a neuron can be one of many functions that allows for non-linearities to accrue in the network.
lently formulate:
a = 1 1 + exp(−[wT^ b] · [x 1 ])
Figure 2 : This image captures how in a sigmoid neuron, the input vector x is first scaled, summed, added to a bias unit, and then passed to the squashing sigmoid function.
This formulation can be visualized in the manner shown in Fig- ure 2.
We extend the idea above to multiple neurons by considering the case where the input x is fed as an input to multiple such neurons as shown in Figure 3. If we refer to the different neurons’ weights as {w(^1 ), · · · , w(m)} and the biases as {b 1 , · · · , bm}, we can say the respective activations are {a 1 , · · · , am}:
a 1 = 1 1 + exp(w(^1 )T^ x + b 1 ) .. .
am =
1 + exp(w(m)T^ x + bm)
Let us define the following abstractions to keep the notation simple and useful for more complex networks:
σ (z) =
1 1 +exp(z 1 ) .. . 1 1 +exp(zm )
b =
b 1 .. . bm
m
− w(^1 )T^ − · · · − w(m)T^ −
∈^ R m×n
We can now write the output of scaling and biases as:
Figure 3 : This image captures how multiple sigmoid units are stacked on the right, all of which receive the same input x.
z = Wx + b
The activations of the sigmoid function can then be written as:
a(^1 ) .. . a(m)
=^ σ (z) =^ σ (Wx^ +^ b)
score computed for the "false" labeled window "Not all museums in Paris" as sc (subscripted as c to signify that the window is "corrupt"). Then, our objective function would be to maximize (s − sc) or to minimize (sc − s). However, we modify our objective to ensure that error is only computed if sc > s ⇒ (sc − s) > 0. The intuition behind doing this is that we only care the the "true" data point have a higher score than the "false" data point and that the rest does not matter. Thus, we want our error to be (sc − s) if sc > s else 0. Thus, our optimization objective is now:
minimize J = max(sc − s, 0)
However, the above optimization objective is risky in the sense that it does not attempt to create a margin of safety. We would want the "true" labeled data point to score higher than the "false" labeled data point by some positive margin ∆. In other words, we would want error to be calculated if (s − sc < ∆) and not just when (s − sc < 0 ). Thus, we modify the optimization objective:
minimize J = max(∆ + sc − s, 0)
We can scale this margin such that it is ∆ = 1 and let the other parameters in the optimization problem adapt to this without any change in performance. For more information on this, read about functional and geometric margins - a topic often covered in the study of Support Vector Machines. Finally, we define the following opti- The max-margin objective function is most commonly associated with mization objective which we optimize over all training windows: Support Vector Machines (SVMs)
minimize J = max( 1 + sc − s, 0)
In the above formulation sc = UT^ f (Wxc + b) and s = UT^ f (Wx + b).
In this section we discuss how we train the different parameters in the model when the cost J discussed in Section 1. 4 is positive. No parameter updates are necessary if the cost is 0. Since we typically update parameters using gradient descent (or a variant such as SGD), we typically need the gradient information for any parameter as required in the update equation:
θ (t+^1 )^ = θ (t)^ − α ∇ θ (t) J
Backpropagation is technique that allows us to use the chain rule of differentiation to calculate loss gradients for any parameter used in the feed-forward computation on the model. To understand this further, let us understand the toy network shown in Figure 5 for which we will perform backpropagation.
Figure 5 : This is a 4 - 2 - 1 neural network where neuron j on layer k receives input z( j k)and produces activation output a( j k).
Here, we use a neural network with a single hidden layer and a single unit output. Let us establish some notation that will make it easier to generalize this model later:
Let us begin: Suppose the cost J = ( 1 + sc − s) is positive and we want to perform the update of parameter W 14 (^1 ) (in Figure 5 and
Figure 6 ), we must realize that W 14 (^1 ) only contributes to z( 12 )and thus a( 12 ). This fact is crucial to understanding backpropagation – backpropagated gradients are only affected by values they contribute to. a( 12 )is consequently used in the forward computation of score by
multiplication with W 1 ( 2 ). We can see from the max-margin loss that:
∂ J ∂ s
∂ sc
Therefore we will work with (^) ∂ W ∂ s( 1 ) ij
here for simplicity. Thus,
∂ s ∂ W ij(^1 )
∂ W(^2 )^ a(^2 ) ∂ W ij(^1 )
∂ W i( 2 )a( i^2 ) ∂ W ij(^1 )
= W i(^2 )
∂ a( i^2 ) ∂ W ij(^1 )
⇒ W i(^2 ) ∂ a( i^2 ) ∂ W ij(^1 )
= W i(^2 ) ∂ a( i^2 ) ∂ z( i^2 )
∂ z( i^2 ) ∂ W ij(^1 )
= W i(^2 ) f (z( i 2 )) ∂ z( i^2 )
∂ z( i^2 ) ∂ W ij(^1 )
= W i( 2 )f ′(z( i 2 ))
∂ z( i^2 ) ∂ W ij(^1 )
Thus, we can calculate error gradients with respect to a parameter in the network using either the chain rule of differentiation or using an error sharing and distributed flow approach – both of these ap- proaches happen to do the exact same thing but it might be helpful to think about them one way or another.
Bias Updates: Bias terms (such as b( 11 )) are mathematically equivalent to other weights contributing to the neuron input (z( 12 )) as long as the input being forwarded is 1. As such, the bias gradients for neuron i on layer k is simply δ ( i k). For instance, if we were updating b( 11 )
instead of W 14 (^1 )above, the gradient would simply be f ′(z( 12 ))W 1 (^2 ).
Generalized steps to propagate δ (k)^ to δ (k−^1 ) :
Figure 7 : Propagating error from δ (k)^ to δ (k−^1 )
We have error δ ( i k)propagating backwards from z( i k), i.e. neuron i at layer k. See Figure 7.
We propagate this error backwards to a( j k−^1 )by multiplying δ ( i k)by
the path weight W ij(k −^1 ).
Thus, the error received at a( j k−^1 )is δ i( k)W ij(k −^1 ).
However, a( j k−^1 )may have been forwarded to multiple nodes in the next layer as shown in Figure 8. It should receive responsibility for errors propagating backward from node m in layer k too, using the exact same mechanism.
Thus, error received at a( j k−^1 )is δ ( i k)W ij(k −^1 )+ δ ( mk )W mj(k− 1 ).
In fact, we can generalize this to be (^) ∑i δ i( k)W ij(k −^1 ).
Now that we have the correct error at a( j k−^1 ), we move it across neuron j at layer k − 1 by multiplying with with the local gradient f ′(z( j k−^1 )).
Thus, the error that reaches z( jk −^1 ), called δ ( j k−^1 )is
f ′(z( j k−^1 )) ∑i δ ( i k)W ij(k−^1 )
Figure 8 : Propagating error from δ (k)^ to δ (k−^1 )
So far, we discussed how to calculate gradients for a given parameter in the model. Here we will generalize the approach above so that we update weight matrices and bias vectors all at once. Note that these are simply extensions of the above model that will help build intuition for the way error propagation can be done at a matrix- vector level. For a given parameter W ij(k ), we identified that the error gradient is
simply δ ( i k+^1 )· a( j k). As a reminder, W(k)^ is the matrix that maps a(k)
to z(k+^1 ). We can thus establish that the error gradient for the entire matrix W(k)^ is:
∇W(k) =
δ 1 (k +^1 )a( 1 k ) δ 1 (k +^1 )a( 2 k ) · · · δ 2 (k +^1 )a( 1 k ) δ 2 (k +^1 )a( 2 k ) · · · .. .
=^ δ
(k+ 1 ) (^) a(k)T
Error propagates from layer (k + 1 ) to (k) in the following manner: δ (k)^ = f ′^ (z(k)^ ) ◦ (W(k)T^ δ (k+^1 )^ ) Of course, this assumes that in the forward propagation the signal z(k)^ first goes through activation neurons f to generate activations a(k)^ and are then linearly combined to yield z(k+^1 )^ via transfer matrix W(k).
Thus, we can write an entire matrix gradient using the outer prod- uct of the error vector propagating into the matrix and the activations forwarded by the matrix. Now, we will see how we can calculate the error vector δ (k). We established earlier using Figure 8 that δ ( j k)= f ′(z( j k)) ∑i δ i( k+^1 )W ij(k ). This can easily generalize to matrices such that:
δ (k)^ = f ′(z(k)) ◦ (W(k)T^ δ (k+^1 ))
In the above formulation, the ◦ operator corresponds to an element wise product between elements of vectors (◦ : R N^ × R N^ → R N^ ).
Computational efficiency: Having explored element-wise updates as well as vector-wise updates, we must realize that the vectorized implementations run substantially faster in scientific computing environments such as MATLAB or Python (using NumPy/SciPy packages). Thus, we should use vectorized implementation in prac- tice. Furthermore, we should also reduce redundant calculations in backpropagation - for instance, notice that δ (k)^ depends directly on δ (k+^1 ). Thus, we should ensure that when we update W(k)^ using δ (k+^1 ), we save δ (k+^1 )^ to later derive δ (k)^ – and we then repeat this for (k − 1 )... ( 1 ). Such a recursive procedure is what makes backpropa- gation a computationally affordable procedure.
2 Neural Networks: Tips and Tricks
Having discussed the mathematical foundations of neural networks, we will now dive into some tips and tricks commonly employed
passes through the network, which will be computationally expen- sive. Furthermore, many large-scale neural networks can contain millions of parameters,and computing two passes per parameter is clearly not optimal. And, since in optimization techniques such as SGD, we must compute the gradients once per iteration for several thousands of iterations, it is obvious that this method quickly grows intractable. This inefficiency is why we only use gradient check to verify the correctness of our analytic gradients, which are much quicker to compute. A standard implementation of gradient check is shown below:
Snippet 2. 1 def eval_numerical_gradient(f, x): """ a naive implementation of numerical gradient of f at x
fx = f(x) # evaluate function value at original point grad = np.zeros(x.shape) h = 0.
it = np.nditer(x, flags=[’multi_index’], op_flags=[’readwrite’]) while not it.finished:
ix = it.multi_index old_value = x[ix] x[ix] = old_value + h # increment by h fxh_left = f(x) # evaluate f(x + h) x[ix] = old_value - h # decrement by h fxh_right = f(x) # evaluate f(x - h) x[ix] = old_value # restore to previous value (very important!)
grad[ix] = (fxh_left - fxh_right) / (2*h) # the slope it.iternext() # step to next dimension return grad
As with many machine learning models, neural networks are highly prone to overfitting, where a model is able to obtain near perfect per- formance on the training dataset, but loses the ability to generalize to unseen data. A common technique used to address overfitting (an issue also known as the “high-variance problem”) is the incorpora- tion of an L 2 regularization penalty. The idea is that we will simply append an extra term to our loss function J, so that the overall cost is now calculated as:
JR = J + λ
L
i= 1
∥W(i)
F The Frobenius Norm of a matrix U is defined as follows:
i
j
Uij 2
In the above formulation,
∥W(i)
∥F is the Frobenius norm of the
matrix W(i)^ (the i-th weight matrix in the network) and λ is the hyper-parameter controlling how much weight the regularization term has relative to the original cost function. Since we are trying to minimize JR, what regularization is essentially doing is penaliz- ing weights for being too large while optimizing over the original cost function. Due to the quadratic nature of the Frobenius norm (which computes the sum of the squared elements of a matrix), L 2 - regularization effectively reduces the flexibility of the model and thereby reduces the overfitting phenomenon. Imposing such a con- straint can also be interpreted as the prior Bayesian belief that the optimal weights are close to zero – how close depends on the value of λ. Choosing the right value of λ is critical, and must be chosen via hyperparameter-tuning. Too high a value of λ causes most of the weights to be set too close to 0, and the model does not learn anything meaningful from the training data, often obtaining poor ac- curacy on training, validation, and testing sets. Too low a value, and we fall into the domain of overfitting once again. It must be noted that the bias terms are not regularized and do not contribute to the cost term above – try thinking about why this is the case! There are indeed other types of regularization that are sometimes used, such as L 1 regularization, which sums over the absolute values (rather than squares) of parameter elements – however, this is less commonly applied in practice since it leads to sparsity of parameter weights. In the next section, we discuss dropout, which effectively acts as another form of regularization by randomly dropping (i.e. setting to zero) neurons in the forward pass.
where σ (z) ∈ (0, 1)
The gradient of σ (z) is:
σ ′(z) = − exp(−z) 1 + exp(−z) = σ (z)( 1 − σ (z))
Tanh: The tanh functionis an alternative to the sigmoid function that is often found to converge faster in practice. The primary difference between tanh and sigmoid is that tanh output ranges from −1 to 1 while the sigmoid ranges from 0 to 1.
Figure 10 : The response of a tanh nonlinearity
tanh(z) = exp(z)^ −^ exp(−z) exp(z) + exp(−z) = 2 σ ( 2 z) − 1
where tanh(z) ∈ (−1, 1)
The gradient of tanh(z) is:
tanh′(z) = 1 −
exp(z) − exp(−z) exp(z) + exp(−z)
= 1 − tanh^2 (z)
Hard tanh: The hard tanh function is sometimes preferred over the tanh function since it is computationally cheaper. It does however saturate for magnitudes of z greater than 1. The activation of the hard tanh is:
Figure 11 : The response of a hard tanh nonlinearity
hardtanh(z) =
− 1 : z < − 1 z : − 1 ≤ z ≤ 1 1 : z > 1
The derivative can also be expressed in a piecewise functional form:
hardtanh′(z) =
1 : − 1 ≤ z ≤ 1 0 : otherwise
Soft sign: The soft sign function is another nonlinearity which can be considered an alternative to tanh since it too does not saturate as easily as hard clipped functions:
Figure 12 : The response of a soft sign nonlinearity
softsign(z) = z 1 + |z|
The derivative is the expressed as:
softsign′(z) = sgn(z) ( 1 + z)^2
where sgn is the signum function which returns ± 1 depending on the sign of z
ReLU: The ReLU (Rectified Linear Unit) function is a popular choice of activation since it does not saturate even for larger values of z and has found much success in computer vision applications:
Figure 13 : The response of a ReLU nonlinearity
rect(z) = max(z, 0)
The derivative is then the piecewise function:
rect′(z) =
1 : z > 0 0 : otherwise
Leaky ReLU: Traditional ReLU units by design do not propagate any error for non-positive z – the leaky ReLU modifies this such that a small error is allowed to propagate backwards even when z is negative:
Figure 14 : The response of a leaky ReLU nonlinearity
leaky(z) = max(z, k · z) where 0 < k < 1
This way, the derivative is representable as:
leaky′(z) =
1 : z > 0 k : otherwise
As is the case with machine learning models generally, a key step to ensuring that your model obtains reasonable performance on the task at hand is to perform basic preprocessing on your data. Some common techniques are outlined below.
Mean Subtraction Given a set of input data X, it is customary to zero-center the data by subtracting the mean feature vector of X from X. An important point is that in practice, the mean is calculated only across the training set, and this mean is subtracted from the training, validation, and testing sets.
Normalization Another frequently used technique (though perhaps less so than mean subtraction) is to scale every input feature dimension to have similar ranges of magnitudes. This is useful since input features are often measured in different “units”, but we often want to initially consider all features as equally important. The way we accomplish this is by simply dividing the features by their respective standard deviation calculated across the training set.
You might think that for fast convergence rates, we should set α to larger values – however faster convergence is not guaranteed with larger convergence rates. In fact, with very large learning rates, we might experience that the loss function actually diverges because the parameters update causes the model to overshoot the convex minima as shown in Figure 15. In non-convex models (most of those we work with), the outcome of a large learning rate is unpredictable, but the chances of diverging loss functions are very high.
Figure 15 : Here we see that updating parameter w 2 with a large learning rate can lead to divergence of the error.
The simple solution to avoiding a diverging loss is to use a very small learning rate so that we carefully scan the parameter space – of course, if we use too small a learning rate, we might not converge in a reasonable amount of time, or might get caught in a local minima. Thus, as with any other hyperparameter, the learning rate must be tuned effectively. Since training is the most expensive phase in a deep learning system, some research has attempted to improve this naive approach to setting learning learning rates. For instance, Ronan Collobert scales the learning rate of a weight Wij (where W ∈ R n(l+^1 )^ ×n(l) ) by the inverse square root of the fan-in of the neuron (n(l)). There are several other techniques that have proven to be effective as well – one such method is annealing , where, after several itera- tions, the learning rate is reduced in some way – this method ensures that we start off with a high learning rate and approach a minima quickly; as we get closer to the minima, we start lowering our learn- ing rate so that we can find the optima under a more fine-grained scope. A common way to perform annealing is to reduce the learning rate α by a factor x after every n iterations of learning. Exponential decay is also common, where, the learning rate α at iteration t is given by α (t) = α 0 e−kt, where α 0 is the initial learning rate, and k is a hyperparameter. Another approach is to allow the learning rate to decrease over time such that:
α (t) = α 0 τ max(t, τ )
In the above scheme, α 0 is a tunable parameter and represents the starting learning rate. τ is also a tunable parameter and represents the time at which the learning rate should start reducing. In practice, this method has been found to work quite well. In the next section we discuss another method for adaptive gradient descent which does not require hand-set learning rates.
Momentum methods, a variant of gradient descent inspired by the study of dynamics and motion in physics, attempt to use the “veloc-
ity” of updates as a more effective update scheme. Pseudocode for momentum updates is shown below:
Snippet 2. 2
v = muv - alphagrad_x x += v
AdaGrad is an implementation of standard stochastic gradient de- scent (SGD) with one key difference: the learning rate can vary for each parameter. The learning rate for each parameter depends on the history of gradient updates of that parameter in a way such that parameters with a scarce history of updates are updated faster using a larger learning rate. In other words, parameters that have not been updated much in the past are likelier to have higher learning rates now. Formally:
θ t,i = θ t−1,i − α √ ∑t τ = 1 g^2 τ ,i
gt,i where gt,i =
∂θ it Jt( θ )
In this technique, we see that if the RMS of the history of gradients is extremely low, the learning rate is very high. A simple implemen- tation of this technique is:
Snippet 2. 3
cache += dx** x += - learning_rate (^) * dx / np.sqrt(cache + 1e-8)
Other common adaptive methods are RMSProp and Adam, whose update rules are shown below (courtesy of Andrej Karpathy):
Snippet 2. 4
cache = decay_rate (^) * cache + (1 - decay_rate) (^) * dx** x += - learning_rate (^) * dx / (np.sqrt(cache) + eps)
Snippet 2. 5