Multilayer Perceptrons and Backpropagation › Formula
Machine Learning from ScratchAll chapters Multilayer Perceptrons and Backpropagation › FormulaSection view · Sections in this chapter4 / 10 ↓
Reading tools Definitions, links & notes
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
With the motivation in place, the formula section answers a practical question: what exactly does the network compute, and how do we adjust every parameter so that its predictions improve? We will proceed in the same order as the implementation. First we define the forward pass and keep track of shapes. Then we define a numerically stable loss. Finally we differentiate that loss layer by layer. The order matters: backpropagation is not a separate learning algorithm, it is the chain rule applied to the forward computation we have just written down.
We begin with notation. Suppose we have training examples, each with input features. Let be the -th input and its binary label. We use a network with one hidden layer containing hidden units. The hidden layer has weight matrix and bias vector . The output layer has weight vector and bias .
where:
- : number of training examples, with one example per row when stored in the matrix
- : number of input features per example
- : the -th input vector, an element of
- : the binary label of the -th example, either or
- : number of hidden units in the single hidden layer
- : hidden-layer weight matrix, whose -th row holds the weights feeding hidden unit
- : hidden-layer bias vector, whose -th entry shifts hidden unit
- : output-layer weight vector, whose -th entry scales hidden activation in the output logit
- : output-layer bias, which shifts the logit before the sigmoid
The symbol means the set of real matrices with rows and columns. Each row of is the weight vector for one hidden unit. The bias shifts the -th hidden unit, just as the intercept shifts a regression line. One way to read the notation is as a contract: the input has numbers, the hidden layer is allowed to create new numbers, and the output layer must combine those numbers into one prediction. The rest of the derivation is about making that contract precise and keeping the dimensions consistent.
Affine layers, nonlinear activations, and shapes
We start with the simplest part: an affine transformation. For a single input , the hidden preactivation is
where:
- : a single input vector, so that applies the hidden weight matrix
- : the hidden preactivation vector, the affine output before the nonlinearity
The vector contains one number per hidden unit. The -th component is
where:
- : the preactivation of hidden unit
- : the weight connecting input feature to hidden unit , the entry in row and column of
- : the -th feature of the input
- : the bias of hidden unit
- : the number of input features
We read as “sum over the input features .” The entry is the weight connecting input feature to hidden unit . This is exactly the same weighted sum that appears in linear regression, repeated times with its own weights for each hidden unit. The hidden layer is a bank of learned affine projections, which can respond to different directions in the input space. The bias shifts the point at which the -th projection is centered.
Without a nonlinearity, stacking two affine layers would collapse into one affine layer:
which is still affine (linear plus a constant) in . A nonlinear activation allows the composition to represent functions that a single affine layer cannot. A common choice is the hyperbolic tangent,
where:
- : the activation of hidden unit
- : the preactivation of hidden unit entering the activation
The derivative of tanh is
Another common choice is the rectified linear unit,
where:
- : the activation of hidden unit
- : the preactivation of hidden unit entering the activation
The ReLU derivative is when and when . At exactly zero the derivative is not defined, and implementations choose a convention, usually . The sigmoid activation
where:
- : the logistic (sigmoid) function mapping any real input to
- : the input to the sigmoid, for example an output logit
The sigmoid is often used at the output for binary classification, and sometimes in hidden layers. Its derivative is . These derivatives tell us how a small change in a preactivation changes the activation. The backward pass multiplies them by the upstream loss gradient to obtain the gradient with respect to the preactivation. In a saturated region, tanh or sigmoid has a small derivative and attenuates a fixed upstream gradient. A ReLU has derivative zero on the negative side, so its local data-loss gradient is zero for that input.
The figure below makes the local exchange rates visible. Solid curves are the activations, and dashed curves are their derivatives. Where a derivative is near zero, the backward pass transmits very little gradient. The figure also shows that sigmoid and tanh flatten at large magnitudes, while ReLU stays linear on the positive side and becomes exactly zero on the negative side.
The hidden setup below makes the shared plotting module available and seeds the book plots once. Each plotting cell imports the style helpers it uses. The cell after it only prepares the data that the activation figure will display.
PythonIn [3]Expand
import numpy as np
z_grid = np.linspace(-4.0, 4.0, 401)
tanh_vals = np.tanh(z_grid)
sigmoid_vals = 1.0 / (1.0 + np.exp(-z_grid))
relu_vals = np.maximum(0.0, z_grid)
tanh_deriv = 1.0 - tanh_vals**2
sigmoid_deriv = sigmoid_vals * (1.0 - sigmoid_vals)
relu_deriv = (z_grid > 0.0).astype(float)VisualizationOut [4]Expand

For a mini-batch of examples, we store the inputs in a matrix , with one example per row, and use the same hidden-layer mapping as in the single-example derivation. The hidden preactivation matrix is
where:
- : the number of examples in the mini-batch
- : the input matrix, with one example per row
- : the transpose of the hidden weight matrix
- : a column vector of ones with length
- : the transpose of the hidden bias, broadcast across rows
- : the hidden preactivation matrix
The transpose appears because has examples as rows while has hidden units as rows. The product has shape : one row per example, one column per hidden unit. Broadcasting adds the same bias vector to every row. The activation matrix is , where is applied elementwise.
The output logit is
where:
- : the hidden activation matrix
- : the output weight vector
- : the output bias
- : the output logit vector of length
For binary classification we convert the logit to a probability with the sigmoid:
where:
- : the output logit of example
- : the predicted probability that example belongs to class
The shape chain is worth checking: is , is , and and are . In the column-vector notation used here, is and is . The NumPy implementation stores these vectors as one-dimensional arrays with shapes (h,) and (B,); the scalar formulas are the same. Writing each shape beside the corresponding operation helps find dimension mismatches before coding.
Forward passes and stable losses
The forward pass is the sequence of operations that turns inputs into predictions. For one mini-batch we compute , then , then , then . The forward pass stores , , and in a cache. This tanh backward pass reuses to compute the activation derivatives elementwise as ; it receives separately and does not read the cached . It is useful to think of the forward pass as building a cache: every quantity that will be needed later is stored now, so the backward pass can reuse it instead of recomputing it.
For binary labels, the negative log-likelihood of one example is
where:
- : the binary cross-entropy loss for example
- : the binary label, either or
- : the predicted probability of class for example
This is the binary cross-entropy loss. If , only remains; if , only remains. The loss is small when the predicted probability agrees with the label and large when it disagrees. In that sense the loss is a precise way of saying “how surprised should the model be by the observed label?”
For a very negative logit, a naive sigmoid calculation can overflow in and round the predicted probability to zero. Taking its logarithm then produces negative infinity even though the mathematical log probability is finite. We compute the loss from the logit instead. Since , we have
and
where:
- : the predicted probability for the example, equal to
- : the output logit for the example
Combining the two cases gives
where:
- : the binary cross-entropy loss for example , computed from the logit
- : the output logit of example
- : the binary label, either or
The expression is exactly , which is a log-sum-exp written in the form . Numerical libraries provide a stable function often called logaddexp, which computes without overflowing. Thus we compute
For label 1 the loss decreases as the logit grows; for label 0 it increases. The logaddexp calculation avoids forming an overflowing exponential directly. The plotted losses remain finite over the displayed logit range.
PythonIn [5]Expand
import numpy as np
s_curve = np.linspace(-5.0, 5.0, 401)
loss_label_one = np.logaddexp(0.0, s_curve) - 1.0 * s_curve
loss_label_zero = np.logaddexp(0.0, s_curve) - 0.0 * s_curveVisualizationOut [6]Expand

where:
- : a numerically stable computation of
- : the output logit of example
- : the binary label, either or
For a batch we average:
where:
- : the mean binary cross-entropy over the examples
- : the number of examples in the batch
- : the binary cross-entropy loss for example
The same idea extends to multiclass classification. If the network produces logits for classes, the softmax probability of class is
where:
- : the predicted probability that example belongs to class
- : the logit for class on example
- : the number of classes
For this multiclass formula, let denote the true class index, replacing the earlier binary encoding. The multiclass cross-entropy is
where:
- : the cross-entropy loss for example
- : the number of classes
- : the logit for class on example
- : the logit for the true class on example
The second term is computed with a stable log-sum-exp operation. In this chapter we focus on the binary case, but the backward pass for softmax cross-entropy has the same clean form: the gradient with respect to the logits is predicted probability minus one-hot label.
Backpropagation and gradient checking
Backpropagation is the chain rule applied from the output backward. We first compute the derivative of the loss with respect to the output logit . A useful discipline is to derive the gradient for one scalar example first, then average over the batch; the only change is the factor , which appears in the delta defined below. For one example,
where:
- : the binary cross-entropy loss for one example
- : the output logit for that example
- : the predicted probability for that example
We read as the partial derivative of the loss with respect to the logit . The derivative of the binary cross-entropy with respect to is
where:
- : the binary cross-entropy loss for one example
- : the predicted probability for that example
- : the binary label of that example
The derivative of the sigmoid is . Multiplying gives
where:
- : the derivative of the loss with respect to the logit
- : the predicted probability
- : the binary label
This is a simple result: the gradient at the logit is the predicted probability minus the label. If the network predicts and the label is , the gradient is , so gradient descent increases the logit slightly. If the label is , the gradient is , a larger correction. The same pattern will reappear in multiclass classification, where the gradient is the predicted probability vector minus the one-hot label.
For a batch with mean loss, we divide by . Define
where:
- : the scaled output delta for example
- : the predicted probability for example
- : the binary label for example
- : the number of examples in the batch, so division by reflects the mean loss
The gradient with respect to the output weights is
where:
- : the mean loss over the batch
- : the -th output weight
- : the activation of hidden unit on example
This holds because , so . In matrix form,
where:
- : the gradient of the mean loss with respect to the output weight vector
- : the hidden activation matrix
- : the vector of values
The transpose is needed because is and is , so is , matching . The gradient with respect to the output bias is
where:
- : the output bias
- : the scaled output delta for example
Now we propagate backward into the hidden layer. For hidden unit and example , the logit depends on through , so
where:
- : the derivative of the mean loss with respect to the activation of hidden unit on example
- : the scaled output delta for example
- : the output weight for hidden unit
The activation contributes its local derivative:
where:
- : the derivative of the mean loss with respect to the preactivation of hidden unit on example
- : the scaled output delta for example
- : the output weight for hidden unit
- : the derivative of the hidden activation evaluated at the preactivation
For , . Define the hidden delta matrix
where:
- : the hidden delta for hidden unit on example
- : the scaled output delta for example
- : the output weight for hidden unit
- : the activation of hidden unit on example
In matrix notation,
where:
- : the hidden delta matrix
- : the vector of scaled output deltas
- : the output weight vector, so is a outer product
- : the hidden activation matrix
- : elementwise (Hadamard) multiplication
The outer product has shape , and has the same shape. The hidden preactivation is , so
where:
- : the derivative of the mean loss with respect to the hidden weight connecting input feature to hidden unit
- : the derivative of the mean loss with respect to the hidden bias of unit
- : the hidden delta for hidden unit on example
- : the -th feature of example
In matrix form,
where:
- : the gradient of the mean loss with respect to the hidden weight matrix
- : the gradient of the mean loss with respect to the hidden bias vector
- : the transpose of the hidden delta matrix
- : the input matrix
- : the column vector of ones
Again the shapes match: is , is , so is , the same shape as . The gradient with respect to is the column sum of . Notice how each matrix expression encodes a sum: the transpose aligns examples with the quantity being summed, and the matrix product performs the sum over examples in one operation.
If we add L2 regularization, the loss becomes
where:
- : the regularized mean loss
- : the unregularized mean binary cross-entropy
- : the L2 regularization strength, with
- : the hidden weight connecting input feature to hidden unit
- : the output weight for hidden unit
The factor makes the derivative of the penalty with respect to equal to , and similarly for . We do not regularize the biases by default, because they do not control the scale of the learned features in the same way.
Gradient checking verifies the backward pass by comparing analytic gradients with finite differences. It is the unit test of a hand-written backward pass. For a parameter ,
where:
- : the -th scalar parameter being checked
- : the loss with parameter increased by the perturbation size
- : the loss with parameter decreased by
- : the finite-difference step size
Perturb one parameter by in each direction, compute the two losses, and divide their difference by . For a sufficiently smooth loss, the centered formula has truncation error of order . Floating-point cancellation grows as the step becomes too small, so this is not a guarantee of greater accuracy for every step size. A relative error below about is a useful diagnostic for a smooth float64 example at a suitable step size, but near-zero gradients and activation kinks need separate inspection.
Mathematical Properties
With a sufficiently wide hidden layer, a suitable continuous sigmoidal activation, and a linear output, a network can approximate continuous functions on a compact input domain to arbitrary accuracy. This is an existence statement about a family of functions, not a guarantee that gradient descent will find the required parameters from finite data. Our binary classifier instead uses a sigmoid output to keep predictions between zero and one. Approximation capacity does not remove the need for regularization and validation.
The joint loss is generally nonconvex in , , , and . It also has a permutation symmetry: permuting hidden units and applying the same permutation to rows of , entries of , and entries of leaves the network output unchanged. Distinct parameter vectors can therefore represent the same function. Random initialization helps give hidden units different starting points. If every weight and bias in this tanh network starts at zero, hidden activations and output weights are zero; the hidden features cannot begin learning under the stated gradient updates.
The gradient with respect to contains the input factor . Holding the other gradient factors fixed, rescaling that feature rescales this gradient. Standardization brings marginal feature scales closer together, but it does not remove correlations or guarantee a well-conditioned loss. Saturating tanh and sigmoid activations have small local derivatives at large magnitudes. These multipliers can attenuate gradient flow; ReLU avoids positive-side saturation but has zero derivative on its negative side.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!