Unit 9, lesson 62

Neural Networks and Forward Propagation

How a feed-forward neural network computes its output by forward propagation through hidden layers with ReLU activations, how tensor shapes and the output layer fit the task, and what universal approximation promises.

  • Video 62
  • Forward and Backward Computation

Two normalized sensor readings describe a machine, and a score decides whether to send it to inspection. Suppose a machine should be inspected when the two readings disagree by a lot, whichever of them is larger. A linear score with a threshold splits the plane of readings along one straight line, so it cannot flag both sides of the diagonal while passing the middle. This lesson builds a small neural network that does, computes its forward pass by hand with the shape of every array, matches the output layer to the task, and states what the universal approximation theorem promises and what it leaves open. The readings and weights are constructed for teaching and do not come from a real inspection system.

Key terms

Neural network and hidden layer

Definition A feed-forward neural network maps an input x\mathbf{x} in Rp\mathbb{R}^p to an output through a fixed sequence of layers. Set h(0)=x\mathbf{h}^{(0)} = \mathbf{x} and d0=pd_0 = p. For l=1,…,L−1l = 1, \dots, L - 1, layer ll computes

z(l)=W(l)h(l−1)+b(l),h(l)=ϕ(z(l)),\begin{aligned} \mathbf{z}^{(l)} &= W^{(l)}\mathbf{h}^{(l-1)} + \mathbf{b}^{(l)}, \\[0.4em] \mathbf{h}^{(l)} &= \phi\bigl(\mathbf{z}^{(l)}\bigr), \end{aligned}

where the weight matrix W(l)W^{(l)} is dl×dl−1d_l \times d_{l-1}, the bias b(l)\mathbf{b}^{(l)} lies in Rdl\mathbb{R}^{d_l}, and the activation function ϕ\phi acts on each entry of the preactivation z(l)\mathbf{z}^{(l)}. The output layer LL forms z(L)=W(L)h(L−1)+b(L)\mathbf{z}^{(L)} = W^{(L)}\mathbf{h}^{(L-1)} + \mathbf{b}^{(L)} and applies an output function chosen for the task. Layers 11 to L−1L - 1 are the hidden layers, each entry of h(l)\mathbf{h}^{(l)} is a unit, and dld_l is the width of layer ll. Every unit receives every value of the previous layer, so these layers are called fully connected. The parameters θ\boldsymbol{\theta} are all the weights and biases, so the architecture defines a family of functions fθf_{\boldsymbol{\theta}}, and training picks θ\boldsymbol{\theta} by minimizing a loss on training data. A hidden layer is hidden because the data contain no target values for its units. The loss is computed from the output alone.

In plain words Each hidden unit forms a weighted sum of the previous layer’s values, adds its bias and passes the result through the activation. A hidden layer therefore builds new features from the inputs, and the output layer combines them. Unlike features designed by hand, these features are set by parameters, and training decides what they become.

Example The network of this lesson reads two dimensionless readings x=(x1,x2)⊤\mathbf{x} = (x_1, x_2)^{\top}, has one hidden layer of width 22 with ReLU activation, and returns one score. Its parameters were chosen by hand to make the geometry visible, not fitted to data,

W=[1−1−11],b=[00],v=[11],c=−0.5.\begin{gathered} W = \begin{bmatrix} 1 & -1 \\ -1 & 1 \end{bmatrix}, \quad \mathbf{b} = \begin{bmatrix} 0 \\ 0 \end{bmatrix}, \\[0.4em] \mathbf{v} = \begin{bmatrix} 1 \\ 1 \end{bmatrix}, \quad c = -0.5 . \end{gathered}

The hidden layer computes h=ReLU⁡(Wx+b)\mathbf{h} = \operatorname{ReLU}(W\mathbf{x} + \mathbf{b}) and the output layer computes the score s=v⊤h+cs = \mathbf{v}^{\top}\mathbf{h} + c. The hidden layer has 44 weights and 22 biases and the output layer 22 weights and 11 bias, so the network has 99 parameters.

Activation function and ReLU

Definition An activation function is a fixed function ϕ\phi from R\mathbb{R} to R\mathbb{R} that a layer applies to each entry of its preactivation vector. The rectified linear unit, ReLU, is

ReLU⁡(z)=max⁡(0,z),\operatorname{ReLU}(z) = \max(0, z),

which equals zz for z≥0z \ge 0 and 00 for z<0z < 0. It is continuous and piecewise linear but not linear. Its derivative is 11 for z>0z > 0 and 00 for z<0z < 0, and at z=0z = 0 it has no derivative, so software uses a convention there, usually 00. Other common activations are the logistic sigmoid σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}) and tanh⁡(z)\tanh(z). Hidden layers add flexibility only through a nonlinear activation. With the identity in place of ϕ\phi, two layers compute

W(2)(W(1)x+b(1))+b(2)=W(2)W(1)x+W(2)b(1)+b(2),\begin{aligned} & W^{(2)}\bigl(W^{(1)}\mathbf{x} + \mathbf{b}^{(1)}\bigr) + \mathbf{b}^{(2)} \\[0.4em] &\quad = W^{(2)}W^{(1)}\mathbf{x} \\[0.4em] &\qquad + W^{(2)}\mathbf{b}^{(1)} + \mathbf{b}^{(2)} , \end{aligned}

which is again an affine function of x\mathbf{x}, and by induction any number of such layers computes a single affine map.

In plain words ReLU passes a positive signal unchanged and replaces a negative one by zero, so each hidden unit is switched on in one half of the input space and off in the other. The bends where units switch let a network build functions that are not linear. Without a nonlinear activation, extra layers change how the parameters are written but not the set of functions the model can compute.

Example In the network above the hidden units compute max⁡(0,x1−x2)\max(0, x_1 - x_2) and max⁡(0,x2−x1)\max(0, x_2 - x_1). For every real number aa the identity max⁡(0,a)+max⁡(0,−a)=∣a∣\max(0, a) + \max(0, -a) = \lvert a \rvert holds, so the score is

s=∣x1−x2∣−0.5.s = \lvert x_1 - x_2 \rvert - 0.5 .

With the declared rule “inspect when s≥0s \ge 0”, the network inspects exactly the inputs whose readings differ by at least 0.50.5. That region consists of two closed half-planes, one on each side of the band around the diagonal x1=x2x_1 = x_2. If both ReLUs are replaced by the identity, the hidden values x1−x2x_1 - x_2 and x2−x1x_2 - x_1 cancel in the output, the score is −0.5-0.5 for every input, and nothing is ever inspected.

Forward propagation

Definition Forward propagation, also called the forward pass, evaluates a network on a given input with fixed parameters. It computes each layer’s preactivation and activation in dependency order, from the input through the hidden layers to the output, using the layer equations above. It changes no parameters. Training code keeps the intermediate values z(l)\mathbf{z}^{(l)} and h(l)\mathbf{h}^{(l)}, because the backward pass that computes gradients reuses them.

In plain words Push the numbers through the network one layer at a time. Each layer needs only the output of the layer before it, and writing down every intermediate value makes an arithmetic or coding error easy to locate.

Example For the input x=(2,1)⊤\mathbf{x} = (2, 1)^{\top} the first unit computes 1⋅2−1⋅1=11 \cdot 2 - 1 \cdot 1 = 1 and the second −1⋅2+1⋅1=−1-1 \cdot 2 + 1 \cdot 1 = -1, so

z=Wx+b=[1−1],h=ReLU⁡(z)=[10],s=1+0−0.5=0.5.\begin{aligned} \mathbf{z} &= W\mathbf{x} + \mathbf{b} = \begin{bmatrix} 1 \\ -1 \end{bmatrix}, \\[0.4em] \mathbf{h} &= \operatorname{ReLU}(\mathbf{z}) = \begin{bmatrix} 1 \\ 0 \end{bmatrix}, \\[0.4em] s &= 1 + 0 - 0.5 = 0.5 . \end{aligned}

The score is nonnegative, so this machine is sent to inspection. For x=(1.2,1)⊤\mathbf{x} = (1.2, 1)^{\top} the preactivations are 0.20.2 and −0.2-0.2, the hidden vector is (0.2,0)⊤(0.2, 0)^{\top} and s=−0.3s = -0.3, so it is not inspected. For x=(1.5,1)⊤\mathbf{x} = (1.5, 1)^{\top} the score is exactly 00, and the declared rule s≥0s \ge 0 inspects it. A rule written with s>0s > 0 would decide this case the other way, so the comparison operator is part of the model’s specification.

Output layer

Definition The output layer maps the last hidden vector to the quantity the task needs. Its output function, the format of the labels and the training loss have to describe the same task.

  • A real-valued target uses an identity output, the prediction y^=z(L)\hat{y} = z^{(L)}, with a regression loss such as squared error.
  • A binary label in {0,1}\{0, 1\} uses one score zz, the modeled probability P(Y=1∣x)=σ(z)P(Y = 1 \mid \mathbf{x}) = \sigma(z) and binary cross-entropy. The score is then called a logit.
  • A task with KK mutually exclusive classes uses KK scores, the softmax of the score vector as the class probabilities and multiclass cross-entropy, with one class label per example.
  • A task where several of KK labels can hold at once uses KK sigmoids, one binary cross-entropy for each label, and probabilities that need not add to 11.

A number between 00 and 11 produced by a sigmoid or softmax is the model’s probability. Whether such numbers match observed frequencies on new data is calibration, a separate property that must be checked on held-out data.

In plain words The hidden layers build features, and the output layer decides what kind of answer comes out. A regression output, a single binary probability and a probability vector over classes need different output functions, different label formats and different losses, and mixing them up gives a model that trains on the wrong question.

Example If the score of the inspection network is read as a logit, the input (2,1)⊤(2, 1)^{\top} gets

σ(0.5)=11+e−0.5≈0.6225.\sigma(0.5) = \frac{1}{1 + e^{-0.5}} \approx 0.6225 .

The sigmoid is increasing with σ(0)=0.5\sigma(0) = 0.5, so the rule s≥0s \ge 0 is the same rule as σ(s)≥0.5\sigma(s) \ge 0.5, and the boundary input (1.5,1)⊤(1.5, 1)^{\top} gets exactly 0.50.5. These weights were set by hand and never trained with cross-entropy, so 0.62250.6225 is a score passed through the sigmoid, not an estimate of how often such machines actually need inspection.

Tensor shape

Definition In machine learning code a tensor is a multidimensional array, and its shape lists the length of each axis. For one input written as a column, x\mathbf{x} is p×1p \times 1, a first layer of width d1d_1 has W(1)W^{(1)} of shape d1×pd_1 \times p, the vectors z(1)\mathbf{z}^{(1)} and h(1)\mathbf{h}^{(1)} are d1×1d_1 \times 1, and a scalar output with weight vector v\mathbf{v} of shape d1×1d_1 \times 1 gives v⊤h(1)\mathbf{v}^{\top}\mathbf{h}^{(1)} of shape 1×11 \times 1. For a batch of nn examples stored as the rows of an n×pn \times p matrix XX, the same layer is

H=ϕ(XW(1)⊤+1b(1)⊤),H = \phi\bigl(XW^{(1)\top} + \mathbf{1}\mathbf{b}^{(1)\top}\bigr),

an n×d1n \times d_1 array whose row ii is the transposed hidden vector of example ii. Here 1\mathbf{1} is the n×1n \times 1 vector of ones, so 1b(1)⊤\mathbf{1}\mathbf{b}^{(1)\top} copies the bias into every row, and libraries make this copy implicitly by broadcasting. Each layer’s input axis must have the length of the previous layer’s output axis, and which axis holds examples, features or classes is part of the specification.

In plain words Writing the shape next to every array is a cheap check that catches most wiring mistakes before any number is computed. Matching shapes do not prove the code is right, though. A square weight matrix used in the wrong orientation passes every shape check, and broadcasting can silently combine arrays whose shapes differ.

Example Stack the inputs (2,1)(2, 1), (1.2,1)(1.2, 1), (1.5,1)(1.5, 1) and (0,2)(0, 2) as the rows of a 4×24 \times 2 matrix XX. Then XW⊤XW^{\top} and HH are 4×24 \times 2, and the scores Hv+c1H\mathbf{v} + c\mathbf{1} form a 4×14 \times 1 vector with entries 0.50.5, −0.3-0.3, 00 and 1.51.5, the same results as four separate forward passes. In NumPy, if the scores are stored with shape (4,) and the labels with shape (4, 1), their difference broadcasts to a 4×44 \times 4 array without any error, and a loss averaged over it is meaningless. Asserting the expected shape of each intermediate array catches this at once. Testing only the final decisions would not, since a wrong score can still fall on the right side of the threshold.

Universal approximation theorem

Definition Let ϕ\phi be a continuous function from R\mathbb{R} to R\mathbb{R} that is not a polynomial, such as ReLU, the sigmoid or tanh⁡\tanh. Let K⊆RpK \subseteq \mathbb{R}^p be compact, that is, closed and bounded, and let ff be a continuous real-valued function on KK. Then for every ε>0\varepsilon > 0 there are a width NN, weight vectors wj\mathbf{w}_j in Rp\mathbb{R}^p and numbers bjb_j, aja_j and cc such that the one-hidden-layer network

g(x)=c+∑j=1Naj ϕ(uj),g(\mathbf{x}) = c + \sum_{j=1}^{N} a_j\, \phi(u_j),

with the preactivations uj=wj⊤x+bju_j = \mathbf{w}_j^{\top}\mathbf{x} + b_j, satisfies

sup⁡x∈K∣f(x)−g(x)∣<ε.\sup_{\mathbf{x} \in K} \lvert f(\mathbf{x}) - g(\mathbf{x}) \rvert < \varepsilon .

If ϕ\phi is a polynomial of degree dd, every such gg is a polynomial of degree at most dd, and such polynomials cannot approximate every continuous function on the cube [0,1]p[0, 1]^p, so the condition on ϕ\phi cannot be dropped. A function with several outputs is approximated one output at a time. The theorem only asserts existence. It gives no practical bound on NN in general, no method that finds the parameters, no number of training examples, and no guarantee about accuracy on new data or outside KK. It also does not say that a network of some fixed width represents every function exactly.

In plain words With enough hidden units, a network with one hidden layer can stay within any chosen tolerance of a continuous target at every point of a bounded region, not only at the training points. That shows the family of functions is rich enough. Whether training finds such parameters from a finite, noisy sample, and whether they predict well on new cases, are separate questions answered by optimization and by evaluation on held-out data.

Example On K=[−1,1]K = [-1, 1] take f(x)=x2f(x) = x^2. The four-unit ReLU network

g(x)=1−1.5ReLU⁡(x+1)+ReLU⁡(x+0.5)+ReLU⁡(x)+ReLU⁡(x−0.5)\begin{aligned} g(x) &= 1 - 1.5\operatorname{ReLU}(x + 1) \\[0.4em] &\quad + \operatorname{ReLU}(x + 0.5) \\[0.4em] &\quad + \operatorname{ReLU}(x) \\[0.4em] &\quad + \operatorname{ReLU}(x - 0.5) \end{aligned}

equals x2x^2 at x=−1x = -1, −0.5-0.5, 00, 0.50.5 and 11 and is linear between these points. Its largest error on KK is 1/16=0.06251/16 = 0.0625, reached halfway between neighboring points, for example g(0.25)=0.125g(0.25) = 0.125 against f(0.25)=0.0625f(0.25) = 0.0625. Joining NN equal pieces in the same way takes NN units and has largest error 1/N21/N^2, so ten units bring it to 0.010.01. The guarantee stops at the edge of KK. For x>1x > 1 the network is linear with slope 1.51.5, so g(2)=2.5g(2) = 2.5 against f(2)=4f(2) = 4, and for x<−1x < -1 it is constant, so g(−2)=1g(-2) = 1 against f(−2)=4f(-2) = 4. These parameters were built from the known formula of ff, which is not how a network is fitted to data.

Check yourself

  1. Using the inspection network of this lesson, compute the hidden vector, the score and the decision for the input (0,2)⊤(0, 2)^{\top}. Then find the score when both activations are replaced by the identity.
Show the answer

The preactivations are 1⋅0−1⋅2=−21 \cdot 0 - 1 \cdot 2 = -2 and −1⋅0+1⋅2=2-1 \cdot 0 + 1 \cdot 2 = 2, so z=(−2,2)⊤\mathbf{z} = (-2, 2)^{\top} and h=ReLU⁡(z)=(0,2)⊤\mathbf{h} = \operatorname{ReLU}(\mathbf{z}) = (0, 2)^{\top}. The score is s=0+2−0.5=1.5s = 0 + 2 - 0.5 = 1.5, which is at least 00, so the machine is inspected. The formula ∣x1−x2∣−0.5=2−0.5\lvert x_1 - x_2 \rvert - 0.5 = 2 - 0.5 agrees. Read as a logit, the score gives σ(1.5)≈0.8176\sigma(1.5) \approx 0.8176.

With the identity, the hidden values −2-2 and 22 add to 00 and the score is −0.5-0.5. The same happens for every input, because the two hidden units have opposite weights and equal output weights, so the linear version of this network inspects nothing.

  1. A network for three mutually exclusive classes has p=3p = 3 features, one hidden layer of width 44, and a batch of n=32n = 32 examples stored as rows. Give the shapes of the two weight matrices, the hidden array, the score array and the output, count the parameters, and name a suitable output function and loss.
Show the answer

With the convention of this page the first weight matrix is 4×34 \times 3 with a bias of length 44, so the hidden array H=ϕ(XW(1)⊤+1b(1)⊤)H = \phi\bigl(XW^{(1)\top} + \mathbf{1}\mathbf{b}^{(1)\top}\bigr) is 32×432 \times 4. The output layer needs one score per class, so its weight matrix is 3×43 \times 4 with a bias of length 33, and the score array is 32×332 \times 3. Softmax applied to each row gives a 32×332 \times 3 output whose rows are probability vectors adding to 11, trained with multiclass cross-entropy against one class label per example. The parameter count is 12+4+12+3=3112 + 4 + 12 + 3 = 31.

A single sigmoid output would have the wrong shape. Three separate sigmoids would answer three separate yes or no questions whose probabilities need not add to 11, which does not describe classes that exclude each other.

  1. Show that no linear rule “inspect when w1x1+w2x2+b≥0w_1x_1 + w_2x_2 + b \ge 0” agrees with the network’s decisions at the three inputs (0,0)(0, 0), (1,0)(1, 0) and (−1,0)(-1, 0). Would a second linear layer without an activation help?
Show the answer

The network’s scores ∣x1−x2∣−0.5\lvert x_1 - x_2 \rvert - 0.5 are −0.5-0.5, 0.50.5 and 0.50.5, so it passes the first input and inspects the other two. A linear rule that agrees needs b<0b < 0, w1+b≥0w_1 + b \ge 0 and −w1+b≥0-w_1 + b \ge 0. Adding the last two inequalities gives 2b≥02b \ge 0, which contradicts b<0b < 0, so no weights work. Geometrically, the inspected set of a linear rule is a closed half-plane, the whole plane or empty, and each of these contains the midpoint of any two of its points. The network inspects (1,0)(1, 0) and (−1,0)(-1, 0) but not their midpoint (0,0)(0, 0).

A second linear layer does not help. A composition of affine maps is affine, so two linear layers without an activation compute one linear score and face the same contradiction. The ReLU between the layers is what makes the two-sided region possible.

How this lesson connects