Neural Networks and Backpropagation


Neural Networks and Backpropagation

Corey
Today we're focusing on neural networks and back propagation—the process that lets a neural network learn from its mistakes in a structured, mathematical way. This is foundational because essentially every algorithm we'll discuss later uses some form of back propagation, even when it is not explicitly mentioned.

Maria
Before building neural networks, let's connect this to the earlier material. We defined pairs of inputs and labels, used a scoring function to produce class scores, and then defined a loss function to measure how wrong those scores were. We also introduced regularization, which adds a penalty involving the weights so the model does not become unnecessarily complex.

Corey
And softmax is not the only possible loss function. It is widely used in deep learning, especially for classification, but other tasks and settings call for other choices. One important alternative is hinge loss, also called SVM loss in some of the earlier material.

Maria
The key difference is that hinge loss does not convert scores into probabilities. Instead, it encourages the score of the correct class, written as s sub y i, to be higher than every incorrect score s sub j by at least a margin. If that condition is satisfied, the contribution can be zero; if it is violated, the loss increases in proportion to how far the scores are from the desired margin.

Corey
So hinge loss penalizes cases where irrelevant classes receive scores that are too high. Softmax and hinge loss solve related classification problems, but they express the desired behavior differently.

Maria
Next comes optimization. We can imagine the loss as a landscape, where every point represents a different set of weight parameters and the height represents the loss. Our goal is to find weights at a low point in that landscape.

Corey
The gradient tells us which direction increases the loss most rapidly. Therefore, gradient descent takes a step in the negative direction of the gradient, with the step size controlled by the learning rate. Repeating those updates gradually moves the weights toward a minimum.

Maria
There are numerical and analytical gradients. In practice, analytical gradients are used to train the model because they are efficient, while numerical gradients are useful for checking whether an analytical-gradient implementation is correct.

Corey
Computing the loss and gradient over an entire large data set can be expensive. That is why we use mini-batches—often sizes such as 32, 64, 128, or 256—to estimate the gradient from a sample and then take an optimization step.

Maria
The basic mini-batch approach is stochastic gradient descent, or SGD. We can improve it with methods such as SGD with momentum, RMSProp, and Adam. The learning rate is also important: many optimizers begin with a larger value and then reduce it according to a schedule, although Adam and related optimizers often incorporate this kind of adjustment internally.

Corey
Now let's build beyond a single linear layer. A basic neural network can calculate a linear transformation, essentially a weight matrix multiplied by the input. If the input has D features and we need C output classes, the weight dimensions have to map from D inputs to C outputs.

Maria
To add a hidden layer, introduce another weight matrix, often called W1, that maps the input into H hidden neurons. Then a second matrix, W2, maps those H hidden values to the C outputs. In practice, biases are included as well, even if they are omitted from a simplified equation.

Corey
The crucial ingredient between the layers is a nonlinear activation function. Without it, the network would reduce to W2 multiplied by W1 multiplied by X. Since the product of two matrices is just another matrix, the entire multi-layer network would still be equivalent to one linear transformation.

Maria
That would prevent the model from solving problems that cannot be separated by a single straight line in the original feature space. A nonlinear transformation can map the data into a new space where the classes become separable. Polar coordinates, which map values into radius and angle, are one example of a nonlinear transformation that can change the geometry of a problem.

Corey
Networks made from these layers and weight-based transformations are often called fully connected networks or multilayer perceptrons, abbreviated MLPs. We can stack additional layers, as long as the dimensions match from one layer to the next.

Maria
The hidden layers also increase the kinds of patterns the network can represent. A linear classifier might learn templates corresponding directly to the output classes, while a hidden layer with many neurons can learn templates for parts or combinations of objects. For images of birds, cats, deer, dogs, frogs, and horses, some hidden templates might represent shared parts such as eyes, while later layers combine those parts into class-level evidence.

Corey
The most common activation discussed here is ReLU, the rectified linear unit. It applies the maximum of zero and its input, so positive values pass through while nonpositive values become zero. This creates the nonlinearity that gives the network its expressive power.

Maria
ReLU can, however, create dead neurons because an input that is not positive produces zero. Leaky ReLU and ELU are alternatives intended to reduce that issue, with ELU also offering a more zero-centered behavior. Other variants include GELU, sometimes pronounced 'jello' or 'yellow,' and SiLU, also called Swish; these appear in some modern architectures, including transformer and certain convolutional architectures.

Corey
Sigmoid and tanh are also activation functions, but they squash values into narrower ranges. That can contribute to vanishing gradients, so they are generally not preferred in the middle of a neural network. They may still be used in later layers when the output needs behavior such as binarization.

Maria
There is no universal rule for choosing an activation function in a brand-new problem. The choice is largely empirical, although people often begin with ReLU or use an activation commonly tested for the architecture they are building. Differentiability, gradient behavior, smoothness, and whether the function is zero-centered all influence the choice.

Corey
A simple two-layer implementation has a forward pass and a backward pass. In the forward pass, we initialize the weights, apply each weight matrix and bias layer by layer, calculate the prediction, and then calculate the loss. In the backward pass, we calculate analytical gradients and use them to update W1, W2, and the other parameters.

Maria
Adding more hidden neurons usually gives the model more capacity to learn complex boundaries. But too much capacity can lead to overfitting: the network may memorize the training data and fail to generalize to unseen examples.

Corey
The suggested strategy is not to treat network size as the main regularizer. Instead, we often start with a somewhat larger network than seems necessary and use regularization to control it. The regularization strength, commonly represented by lambda, determines how much the weight penalty contributes to the total loss.

Maria
A larger lambda constrains the weights more strongly, giving the model less freedom to create highly detailed decision boundaries. That can reduce overfitting, but if the regularization is too strong, the model may underfit and fail to predict the training outputs well. Regularization creates a balance; more is not automatically better.

Corey
There is also no fixed prescription for how many neurons or layers a problem requires. We look at related research and networks trained on similar data, start in a reasonable range, and run experiments to increase or decrease complexity. The same empirical approach applies to many hyperparameters.

Maria
Neural networks have loose biological inspiration, but the analogy should be handled carefully. A biological neuron has a cell body that aggregates signals arriving through dendrites, and axons that carry signals onward. A neural-network unit similarly combines activations from a previous layer, applies a function, and passes an activation to the next layer.

Corey
But biological neurons are much more complex than the regular computational units used in these networks. Regular patterns are often chosen in artificial networks because they improve computational efficiency. More complex arrangements have been researched, but the regular networks discussed here can produce comparable results in many settings.

Maria
Putting the pieces together, the network produces scores from inputs and weights. A loss function—such as softmax loss, hinge loss, or another option—measures the prediction error. A regularizer contributes an additional weight penalty, and the total loss is the data loss plus the regularization term.

Corey
To optimize that total loss, we need derivatives with respect to all the weights, including W1 and W2. Writing one giant derivative by hand becomes tedious for a deep network, especially when there are many matrix operations or when the loss changes. That is why computational graphs and back propagation are so important.

Maria
A computational graph breaks a complicated calculation into smaller operations. It starts with inputs and parameters, applies operations such as additions and multiplications, produces scores, computes the loss, and adds the regularizer. Back propagation then moves information backward through this graph to calculate the derivatives needed for optimization.

Corey
Let's use the simple function f of x, y, and z equal to x plus y, multiplied by z. With x equal to negative 2, y equal to 5, and z equal to negative 4, first define q as x plus y. The forward pass gives q equal to 3, and then f equals q times z, which is negative 12.

Maria
For the addition operation, the local derivatives are partial q over partial x equal to 1 and partial q over partial y equal to 1. For the multiplication operation, partial f over partial q equals z, and partial f over partial z equals q. These local derivatives are easy to calculate because they depend only on the operation at that node.

Corey
Back propagation starts at the end, where the derivative of f with respect to itself is 1. Moving to z gives a gradient of q, which is 3, and moving to q gives a gradient of z, which is negative 4. To reach x and y, we use the chain rule because neither is directly connected to f.

Maria
The chain rule says that partial f over partial y equals partial f over partial q multiplied by partial q over partial y. That is negative 4 times 1, or negative 4. The same calculation gives negative 4 for x. The important pattern is that every node receives an upstream gradient, multiplies it by its local gradient, and sends the resulting downstream gradient to earlier nodes.

Corey
This is the intuition behind back propagation: rather than derive one enormous expression for a hundred-layer network, we calculate small local derivatives and pass gradients backward one operation at a time. Those gradients tell us how changing each variable, especially each weight, would change the final loss.

Maria
The same method works for more complicated expressions, such as a sigmoid applied to a linear combination of inputs and weights. The forward pass computes each intermediate value, and the backward pass uses known derivative rules for addition, multiplication, exponentiation, and reciprocal operations.

Corey
It can also be useful to combine several operations into a single sigmoid node. If the sigmoid is written as sigma of x, its local derivative simplifies to sigma of x multiplied by one minus sigma of x. That makes the backward calculation compact because the function's own output can be used to compute its gradient.

Maria
Several recurring gate patterns are worth remembering. An addition gate distributes the same upstream gradient to its inputs. A multiplication gate swaps in the other input as the local multiplier: the derivative with respect to one input is the other input.

Corey
A copy gate combines repeated contributions by adding them together. A max gate routes the gradient toward whichever input achieved the maximum, much like the behavior of ReLU. These patterns let us implement neural-network operations modularly, with a forward method that computes values and a backward method that computes gradients.

Maria
The scalar examples are conceptually simple, but real neural networks use vectors, matrices, and tensors. If a scalar output depends on a vector input, the derivative with respect to that input is a vector. If a vector output depends on a vector input, the derivatives form a matrix called a Jacobian.

Corey
The loss is still a single scalar, so its derivative with respect to itself is still 1. The upstream gradient for an intermediate vector has the same shape as that vector. Local derivatives between vector quantities may be Jacobian matrices, and multiplying a local Jacobian by an upstream gradient produces the downstream gradient for the earlier variable.

Maria
For an elementwise ReLU applied to a vector, the Jacobian is sparse: it has values only on the main diagonal. Each diagonal entry is either 1 when the corresponding input passes through or 0 when ReLU replaces it with zero. In practice, we use this rule directly instead of constructing a large sparse Jacobian.

Corey
Matrix operations require the same reasoning, but explicitly forming every Jacobian can be impossible. For example, with a batch size of 64 and dimensions of 4,096, a Jacobian for just one matrix multiplication could require more than 256 gigabytes. Efficient implementations therefore derive matrix formulas that capture the same gradient relationships without storing that enormous matrix.

Maria
For matrix multiplication, the multiplication-gate swap intuition still applies. The gradient with respect to one input uses the other matrix, arranged through the appropriate matrix multiplication, and the gradient with respect to the weights uses the corresponding input. These compact formulas make back propagation practical for large networks.

Corey
Frameworks such as PyTorch organize operations in this modular way. Operators can save the values needed during the forward pass and use them during the backward pass to calculate gradients. The implementation may be located in lower-level C or C++ code, but the principle is the same.

Maria
So the full training loop is now clear: perform a forward pass through the fully connected network, compute the loss and regularization penalty, back-propagate gradients through the computational graph, and update the weights with an optimizer such as SGD or Adam.

Corey
Today we covered fully connected neural networks, the role of nonlinear activations, capacity and regularization, and the complete logic of forward and backward passes. Back propagation is the efficient chain-rule procedure that provides the gradients needed to learn every weight. Next, the discussion moves to convolutional neural networks.

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