1. Home
  2. Explore
  3. Computer Science
  4. Neural Network Training

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Neural Network Training

Speaker 1Speaker 2

Neural Network Training

19:37
0:00-19:37
  1. Michael

    Welcome back. Before we get into the technical material, a few course reminders: Assignment 1 is due today, Thursday, at 11:59 p.m. on Canvas. Assignment 2 is being released today, and project proposals are due Tuesday, April 25th. If you are still looking for a project idea, TA office hours and the project suggestions on Piazza are useful places to start.

  2. Maria

    And there are also notes linked to Lecture 4 covering backpropagation for a linear layer, along with vector and tensor derivatives. Those notes are especially helpful if the mechanics of backpropagation through vectors and matrices still feel unclear. Now, the main topic today is how to train neural networks effectively.

  3. Michael

    Let’s quickly review where we are. We can represent a function as a computational graph, and a neural network is a particular kind of graph that stacks linear layers with nonlinear activation functions between them. Convolutional neural networks use convolutional layers so that spatial structure is preserved through the hierarchy. Each filter slides across the spatial locations of the input and produces one activation map, so a layer with many filters produces an output whose depth equals the number of filters.

  4. Maria

    The values of those filters, weights, and other parameters have to be learned. We do that by optimization: we want to move through the loss landscape toward a region with low loss. The standard mini-batch stochastic gradient descent loop is: sample a mini-batch, forward-propagate it through the network, compute the loss, backpropagate to obtain gradients, and update the parameters using the negative gradient direction.

  5. Michael

    The next training topics include activation functions, data preprocessing, weight initialization, regularization, gradient checking, training dynamics, parameter-update rules, hyperparameter optimization, evaluation, and model ensembles. Today we are focusing on activation functions, preprocessing, initialization, batch normalization, monitoring training, and choosing hyperparameters.

  6. Maria

    Let’s begin with activation functions. After a linear or convolutional operation, the resulting values are passed through a nonlinearity. The choice matters because it affects both the forward activations and how easily gradients can flow backward through the network. We’ll compare sigmoid, tanh, ReLU, and several ReLU variants.

  7. Michael

    The sigmoid function is one over one plus e to the negative x. Applied elementwise, it squashes every input into the range from zero to one. Very negative inputs produce outputs close to zero, very positive inputs produce outputs close to one, and near zero the function behaves approximately linearly. Historically, that range was sometimes interpreted as a neuron’s firing rate.

  8. Maria

    The first major problem is saturation. When the input is around negative ten, the sigmoid is nearly flat, so its local derivative is close to zero. The same thing happens around positive ten, where the function has plateaued near one. During backpropagation, the upstream gradient is multiplied by this local derivative, so a nearly zero derivative can effectively kill the gradient passed to earlier layers.

  9. Michael

    Near zero, the sigmoid has a reasonable slope and gradient flow is much healthier. But the second problem is that sigmoid outputs are not zero-centered. To see why that matters, consider a linear unit whose inputs are all positive. The gradient with respect to a weight is the upstream gradient multiplied by the corresponding input. Since the input is always positive, each weight gradient tends to have the same sign as the upstream gradient.

  10. Maria

    That means the weights tend to update together in one coordinated direction: either many increase or many decrease. In a two-dimensional weight space, the optimizer may be restricted to updates where the coordinates have matching signs, even if the best direction points elsewhere. It can still reach a good solution, but it may need a zigzagging sequence of inefficient updates. This is one reason zero-mean data is generally desirable.

  11. Michael

    There is also a smaller computational issue: sigmoid requires an exponential calculation. In a large neural network, convolutions and dot products are usually more expensive, so this is not the main objection. Still, together with saturation and the lack of zero-centered outputs, it helps explain why sigmoid is rarely the default choice in modern deep networks.

  12. Maria

    Tanh looks similar but squashes values into the range from negative one to one. Its key improvement is that its outputs are zero-centered, so it avoids the particular sign problem of sigmoid. However, tanh still saturates for large positive and negative inputs. Once it saturates, its derivative becomes nearly zero and gradients can again disappear.

  13. Michael

    The basic ReLU, or rectified linear unit, is defined as the maximum of zero and x. Negative inputs are set to zero, while positive inputs pass through unchanged. ReLU does not saturate in the positive region, is computationally simple, and in practice often converges much faster than sigmoid or tanh. It also became especially prominent with networks such as AlexNet around 2012.

  14. Maria

    ReLU has its own limitations. Like sigmoid, its outputs are not zero-centered. More importantly, its gradient is zero for negative inputs. At x equal to negative ten, the unit is inactive and has zero gradient; at positive ten, it is in a healthy linear regime; and at exactly zero the derivative is technically undefined, though implementations use a practical convention such as zero.

  15. Michael

    This can produce dead ReLUs. Imagine the training data as a cloud of points and each ReLU as dividing the input space into an active half and an inactive half. If the unit’s weights place that dividing boundary so that all training examples fall in the inactive region, the unit never activates, receives no useful gradient, and does not update.

  16. Maria

    Dead units can result from unlucky initialization, but a more common cause is an overly large learning rate. A unit may begin in a useful position, then a large parameter update can move it away from the data cloud. Once it stays inactive, it can effectively stop learning. In trained networks, it is possible to find roughly ten to twenty percent dead ReLUs, although networks can still train successfully despite this issue.

  17. Michael

    A practical trick is to initialize ReLU biases with slightly positive values, which makes units more likely to be active at the beginning. Some practitioners report that this helps, while others do not consistently use it; zero biases are also common. The larger lesson is that initialization and learning rate strongly affect whether ReLU units remain useful.

  18. Maria

    Leaky ReLU modifies the negative side by giving it a small negative slope rather than setting it completely flat. That preserves much of ReLU’s computational efficiency and positive-region behavior while reducing the dying-unit problem. A parametric ReLU, or PReLU, goes one step further: its negative-region slope is controlled by an alpha parameter that can be learned through backpropagation rather than fixed in advance.

  19. Michael

    The exponential linear unit, or ELU, is another variant. It retains ReLU-like behavior in the positive region but has a negative-side shape that produces outputs closer to zero mean. Unlike leaky ReLU, ELU includes negative saturation, which has been argued to provide more robust deactivation behavior under noise. These variants involve trade-offs, so they are generally tested empirically.

  20. Maria

    Maxout takes a different approach. Instead of applying one fixed elementwise function to a dot product, it computes the maximum of two linear functions, such as W1 dot X plus b1 and W2 dot X plus b2. This generalizes the behavior of ReLU and leaky ReLU, remains in a linear regime without saturation or dying units, but doubles the number of parameters per neuron.

  21. Michael

    The practical rule of thumb is to start with ReLU. It is the standard choice and generally works well. You can experiment with leaky ReLU, PReLU, ELU, Maxout, or tanh when the problem suggests it, but these variants are more experimental. In general, sigmoid should not be the default for hidden layers because the alternatives usually train better.

  22. Maria

    Next is data preprocessing. A standard approach is to subtract the mean so the data is zero-centered, and, in many machine-learning problems, divide by the standard deviation so features are on comparable scales. Zero-centering helps avoid biased gradient directions, while normalization makes features with different numerical scales contribute more equally.

  23. Michael

    For images, we usually zero-center but do not always normalize each pixel by its standard deviation. Pixel locations already tend to have reasonably comparable scales and distributions, so additional normalization may not be necessary. We also typically avoid more complicated transformations such as PCA or whitening because convolutional networks are designed to operate on the original spatial structure of the image.

  24. Maria

    For image data, zero-centering can be done by computing a mean image over the training set and subtracting that same image from every training and test image. If an image is 32 by 32 by 3, the mean image has the same dimensions. Another common option is to compute one mean per channel, such as one value for red, one for green, and one for blue.

  25. Michael

    The mean is computed from the training data, usually once before training begins, rather than separately for every mini-batch. At test time, we use the mean estimated from the training data; we do not compute a new test-set mean. Zero-centering helps the first layer, but in a deep network, later layers can still develop nonzero-centered activations, so preprocessing alone does not solve the problem everywhere.

  26. Maria

    Now let’s discuss weight initialization. Setting every weight to zero is not a good strategy. The issue is not necessarily that every neuron immediately dies; the central problem is symmetry. Neurons with identical initial weights receive the same inputs, produce the same outputs, receive matching gradients, and continue making the same updates. They therefore learn the same feature instead of specializing.

  27. Michael

    A first improvement is to initialize weights as small random numbers, for example samples from a standard Gaussian scaled to have a standard deviation of 0.01. Randomness breaks the symmetry, and this can work for small networks. But in deep networks, repeatedly multiplying by small weights can cause activations and gradients to shrink layer after layer.

  28. Maria

    In a ten-layer network using tanh, for example, the activations may begin with a reasonable distribution but then their standard deviation rapidly collapses toward zero. On the backward pass, the gradient with respect to a weight includes the input activation, so tiny activations produce tiny weight gradients. The gradients passed from one layer to the previous layer also repeatedly multiply by the weights, causing backward signals to collapse as well.

  29. Michael

    Making the weights very large creates the opposite problem. Large pre-activation values push tanh into its positive or negative saturation regions, where the derivative is close to zero. Then the activations become concentrated near negative one or positive one, and the gradients again vanish. So initialization that is too small causes collapse toward zero, while initialization that is too large causes saturation.

  30. Maria

    Xavier initialization, associated with work by Glorot and colleagues, addresses this by scaling random weights according to the number of inputs. The goal is to make the variance of the outputs approximately match the variance of the inputs. If a unit has fewer inputs, it needs relatively larger weights to maintain the spread; if it has many inputs, it needs smaller weights.

  31. Michael

    The original reasoning assumes an appropriate linear or active regime. ReLU changes the calculation because it sets approximately half of its inputs to zero, which roughly halves the variance passing through the layer. Therefore, the initialization should account for that factor. Using an adjusted Xavier-style initialization often keeps the activation distributions much healthier through a deep ReLU network.

  32. Maria

    Proper initialization can determine whether a network trains at all, so it is not a minor implementation detail. A good starting rule is Xavier initialization, while recognizing that initialization remains an active research area. The next technique, batch normalization, attacks the same scaling problem during training rather than only at initialization.

  33. Michael

    Suppose a mini-batch produces a collection of activations at some layer. Batch normalization computes the empirical mean and variance for each feature across that mini-batch, subtracts the mean, and divides by the standard deviation, with the usual small numerical stabilizer implied in implementations. This forces the activations into a standardized range on each forward pass, and because the operation is differentiable, gradients can be backpropagated through it.

  34. Maria

    For a fully connected layer, the mean and variance are computed independently for each feature across the examples in the mini-batch. Batch normalization is usually inserted after fully connected or convolutional layers. For a convolutional layer, normalization is performed jointly across the training examples and spatial locations for each activation map, giving one mean and one standard deviation per activation map.

  35. Michael

    That convolutional treatment preserves the convolutional structure: corresponding locations within an activation map are normalized consistently. Batch normalization is not changing the weights themselves; it is normalizing the inputs or activations passed to later operations. It improves gradient flow, makes training more robust to different learning rates and initializations, and generally makes optimization easier.

  36. Maria

    There is an important refinement. We do not necessarily want to force every input to every nonlinearity to be exactly unit Gaussian, because that might restrict a tanh unit to a particular operating regime. So after normalization, batch normalization applies a learned scale gamma and a learned shift beta. These parameters let the network choose how much scaling and shifting it wants, including, in principle, recovering an identity mapping.

  37. Michael

    Batch normalization also has a regularizing effect. An example’s normalized activation depends not only on that example but also on the other examples in its mini-batch. The representation is therefore slightly jittered by the batch composition rather than being completely deterministic for that example, which can act like a form of regularization.

  38. Maria

    Small batch sizes can make the estimates of means and variances less accurate, and normalization for recurrent or reinforcement-learning settings may require different considerations. For typical convolutional networks, however, batch normalization generally works well. At test time, we do not use the statistics of the current test batch; instead, we use statistics estimated during training, often maintained as running averages.

  39. Michael

    Now let’s shift to babysitting the learning process. Before tuning lots of parameters, preprocess the data, choose an initial architecture, and initialize the network. Then perform a forward pass and check whether the initial loss is sensible. For a ten-class softmax classifier with small weights and nearly uniform class probabilities, the expected loss is approximately negative log of one tenth, or about 2.3.

  40. Maria

    That check is valuable because an unexpected initial loss can reveal an implementation problem. Begin with regularization turned off so that the loss reflects only the data term. Then increase regularization and verify that the loss rises, because the additional regularization term should increase the total objective.

  41. Michael

    A powerful next sanity check is to train on a very small subset of the data with regularization disabled. The network should be able to overfit that tiny set, driving the training loss close to zero and the training accuracy close to one. If it cannot memorize a small dataset, something is probably wrong with the implementation, gradients, architecture, or optimization settings.

  42. Maria

    Once those checks pass, use the full training set and begin tuning the learning rate, one of the most important hyperparameters. If the loss barely changes, the learning rate is probably too small, so parameter updates are not having enough effect. Accuracy can still jump even when the loss changes little because softmax probabilities may remain diffuse while a small shift makes the correct class the largest-probability class.

  43. Michael

    If the loss becomes NaN or explodes, the learning rate is usually too large. A rough range to explore in the example is from about 10 to the negative five through 10 to the negative three, though the appropriate range depends on the problem. The point is to use loss behavior to decide whether updates are too weak, too aggressive, or unstable.

  44. Maria

    Hyperparameter optimization is typically done with cross-validation: train using the training set and evaluate the result on a validation set. Search in stages. First, sample values that are widely separated and train for only a few epochs. This quickly identifies values that produce NaNs, no learning, or promising progress. Then search more finely around the promising region for longer.

  45. Michael

    When checking for instability, monitor the loss during training and stop a trial if it becomes much larger than the initial loss, such as several times larger. Learning rates should usually be sampled in log space rather than uniformly. Because the learning rate multiplies the gradient update, values differing by factors or orders of magnitude are more meaningful than values separated by equal additive intervals.

  46. Maria

    It is also generally better to use random search rather than a rigid grid search. If performance depends strongly on one hyperparameter and only weakly on another, a grid may waste many trials repeating uninformative values. Random sampling gives more distinct values for the important dimension and can discover useful regions more efficiently.

  47. Michael

    Other hyperparameters include learning-rate decay schedules, the update rule, regularization strength, network depth, the number of hidden units, and other architectural choices. Training neural networks involves monitoring many experiments and adjusting these controls based on the loss and accuracy curves.

  48. Maria

    The shape of a loss curve provides clues. An exploding curve suggests the learning rate is too high. A nearly flat curve suggests it is too low. A steep initial decrease followed by an early plateau can also indicate overly large steps that prevent the optimizer from settling well. A good curve often drops substantially and continues improving rather than immediately becoming unstable or flat.

  49. Michael

    A curve that stays flat for a while and then suddenly begins improving may indicate poor initialization. The gradients may initially be ineffective, and later an update may move the network into a region where learning can proceed. Monitoring both training and validation accuracy is also essential. A large gap between them usually indicates overfitting and suggests stronger regularization, while no gap may mean the model still has capacity to improve.

  50. Maria

    Finally, track the ratio between the size of parameter updates and the size of the parameters themselves. You can compare the norm of an update with the norm of the corresponding weights. A rough target is around 0.001, although there is considerable variation. The purpose is diagnostic: updates should not overwhelm the parameters, but they should not be so tiny that they have no practical effect.

  51. Michael

    So the main takeaways are straightforward. Use ReLU as a strong default activation, subtract the mean from image data, initialize weights with a variance-aware method such as Xavier initialization, use batch normalization when appropriate, and search hyperparameters randomly, especially in log space for learning rates.

  52. Maria

    And keep the full training loop in mind: preprocess the data, choose and initialize the network, check the initial loss, verify that a tiny dataset can be overfit, tune the learning rate and other hyperparameters through validation, and continuously inspect loss, accuracy, and update statistics. Those habits turn neural-network training from guesswork into a process you can diagnose and improve.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent