Lecture 2 — Neural Networks and Approximation
Project connection. Project Step 2 asks you to wire a one-hidden-layer ReLU network from explicit matrices. Four hidden units build the nonlinear feature ; two output logits and softmax turn it into a classifier with a diamond-shaped decision boundary.
Chapter overview. Lecture 1 described a language model as a map from contexts to probability distributions. We now replace an explicit matrix of probabilities by a parametrized function. We begin with binary logistic regression, because every calculation fits on one line, and then pass to softmax regression and neural networks. The final sections ask what such networks can represent, why depth can help, and what those representation theorems do—and do not—say about training a useful model.
0. The sigmoid function and logistic regression
We begin with a new type of model. We will connect this with language models (from the last lecture) later in this lecture.
A classification problem asks us to predict which of several categories an observation belongs to.
Let be a finite set whose members are called classes or labels. In binary classification there are two possible classes, typically . Let be the probability simplex on , i.e. the set of probability distributions on .
The input space is a set whose elements are called feature vectors. Each of the standard coordinates of is called a feature, so that a feature vector
has a value for the -th feature.
For a classification problem, we use the same notation as for a language model. Let be the parameter space. A probabilistic classifier for and is a function
that is differentiable in for each fixed . Fixing gives a trained classifier . We write for the probability it assigns to class on input .
In the binary classification case, we can give the output probability distribution on as a single number :
Both a classification model and a language model are instances of a more general conditional probabilistic model: something that maps an input to a probability distribution on possible outputs.
Analogously to the last lecture, we will discuss training and maximum likelihood in this new context. In the case of a training set, we need to train the model on feature vectors which are accompanied by the “correct” labels. For example, many pictures of cats labelled as cats and many other pictures labelled as non-cats.
For a classification model, the training set consists of pairs called training samples. In the context of the training set, the feature vector is called the training observation and is the gold label. The value is the supposed “correct answer,” recorded along with the observation (perhaps is derived from an image, and the label was assigned by a human being who knows how to recognise cats well). The term comes from “gold standard.”
It will be convenient to have a function that turns an arbitrary real number into a probability. The first useful elementary example is the sigmoid.
Definition 0.1 (sigmoid and logit). The sigmoid, or logistic function, is
For , its logit is
The two functions are inverses: and . Indeed,
and taking logarithms gives the first identity. The second follows in the same way.
Suppose an event has probability . Then the ratio is called the odds of the event. A probability of corresponds to odds . This is more commonly written in gambling, which may be the more familiar form for “odds”. The logit of is . Thus a logit is a log-odds ratio, which supposedly explains the terminology.
Now we introduce a simple binary classification model which we will use as a building block for a neural network.
Definition 0.2 (binary logistic regression). A binary logistic regression model is a binary classification model
with parameter
given by
where
The entries of are the weights, is the bias, and is the logit (so named because it will be fed into a sigmoid).
Aside (why “regression”?). The adjective “regression” is historical. In statistics, regression refers to fitting a function to data. The name descended from Galton’s nineteenth-century studies of “regression toward the mean” in heredity. Logistic regression earns the name because it is linear regression of the log-odds.
A model produces a probability distribution. We typically want to turn the probability into a label prediction (a “yes” or “no”). One common rule is to predict exactly when its probability is at least . Since and is increasing, this is equivalent to
The map is affine: it is a linear map plus a constant. Its zero set is an affine hyperplane, and we define this set to be the decision boundary:
where the prediction switches from one label to the other. The equation above describes a translated hyperplane normal to . As the parameters vary, the decision boundary can translate and rotate, but it is always a hyperplane. This flatness is the limitation that hidden layers will remove in Section 4.
As a summary of binary logistic regression, here is a schematic:
Example 0.3 (a tiny delay model). Think back to our example about predicting train delay. Suppose two standardized features are
and consider
In other words, with and . For a journey with , the logit is
The estimated probability of a delay is therefore
The odds are (recall that the logit is log odds), so the model regards a delay as about times as likely as no delay. The decision boundary is the line
ChatGPT helpfully points out: “This is a toy model, not a claim that two features adequately describe a railway.”
Now, how to train our model (choose a good )? For a binary classification model, the training set consists of pairs called training samples
Compare the following definition to the likelihood and average negative log likelihood of Lecture 1, Section 3: it is the same recipe, with the (context, next-token) pairs of a language model replaced by (feature vector, label) pairs.
Definition 0.4 (likelihood and cross-entropy loss). Consider a training set consisting of pairs ; here is the gold label for observation . The likelihood of for this training set is
We wish to think of this as a function of , with the training set fixed:
The average negative log likelihood (also cross-entropy loss or log loss or cost; in the case of a training set specifically, also the empirical loss or training loss; in the case of binary regression specifically the binary loss; depending who you are talking to, hair loss or memory loss; in terms of what you’d rather be doing, caber toss) is
The individual terms
are called the pair-level log loss or log loss for the pair.
Minimizing is the same as maximizing the likelihood . A maximum likelihood estimator, typically denoted , is a choice of minimizer of , i.e. an input at which attains its minimum (equivalently, at which attains its maximum). There may be more than one, or there may be none.
Let us apply this to the binary classification model. From its definition, our model with parameter returns a probability typically denoted
This is a compact way to describe the probability distribution, since
(a Bernoulli distribution with parameter ).
Therefore the log loss for an individual training pair is
When , the second term vanishes and . When , the first term vanishes and . We use the convention in formulas of this kind.
Notationally, is typically used for a model prediction (here, the predicted probability of label ), and for gold labels. Training involves comparing these two, and loss is a measure of how badly the model predicted reality.
Example 0.5 (the loss of one prediction). For the journey in Example 0.3, the model regarded a delay as about times as likely as no delay. In other words, the model predicts a delay is most probable. If a delay actually occurs, then
If the train is instead on time, the same prediction incurs
In short: correct predictions correspond to smaller losses. Falsely assigning a small probability to the gold label incurs a large loss. In particular, the loss diverges as the probability assigned to the observed label tends to zero.
1. Gradient descent for logistic regression
The definition of the maximum likelihood estimator (Definition 0.4) tells us what we want, but not how to find it. For a differentiable function , its gradient at is the vector of partial derivatives
The directional derivative in direction is
Proposition 1.1 (direction of steepest descent). Let be differentiable at , with . Among all unit vectors , the directional derivative is smallest precisely when
Thus is the direction of steepest infinitesimal decrease.
Proof
Recall a classical fact from linear algebra, the Cauchy–Schwarz inequality:
For all ,
with equality if and only if and are linearly dependent.
Apply this with . For any unit vector ,
and by the equality case of Cauchy–Schwarz, the lower bound is attained only when is a scalar multiple of — for a unit vector, only when . Trying both sign cases, we find that among unit vectors , the directional derivative is smallest when points opposite the gradient.
For one logistic-regression training sample , we consider the log loss of our model as a function of . Recall that our goal is to choose to result in small loss. The method of gradient descent will be defined formally below, but in brief, the idea is this. We will compute the gradient of at the position , and use the result to estimate an improved by taking a step in the direction of decrease of loss. In equations:
where is a small fixed number called the learning rate.
Picture the graph of a function of two variables as a landscape over the -plane. At any point, the negative gradient points steepest downhill. Gradient descent repeatedly takes a small step in that downhill direction, recomputing the direction after every step. The two pictures below show the same descent. In the contour picture, each step crosses the level curves at right angles, heading for lower and lower values of .
Definition 1.2 (gradient descent). Let be differentiable, . Let , which we call the learning rate. We write where are indices, not exponents. Let , which we call the initial vector. Define a sequence for by the recurrence
We call the process of computing , as an algorithm, gradient descent.
For logistic regression we take , the average cross-entropy loss, as a function on ; here , viewing as a single vector.
We now demonstrate one step of gradient descent explicitly for logistic regression. Let us assume we have a single training sample . The method of gradient descent views the log loss as a function of , for our fixed training sample. So and are constants, while are the variables. Recall that we write
for the logit and for the probability, as in Section 0, both functions of . One step of gradient descent is
Proposition 1.3 (gradient of the log loss). In this setup,
Proof
Recall from Definition 0.4 that is the log loss of our training sample,
where is the probability the model assigns to the label .
We wish to compute the vector
The loss depends on only through the logit , so the chain rule expresses every one of these partial derivatives in terms of the single scalar :
From we read off and , so
It remains to compute the scalar . The loss depends on through the probability , so we apply the chain rule once more:
Differentiating the binary cross-entropy with respect to gives
and the sigmoid has the pleasant derivative
Multiplying the two,
Assembling the pieces gives the boxed formula.
Let us pause to interpret our computation. Recall that is the predicted probability of our model, as a function of . And is the gold label for our training sample (a constant). The factor is called the prediction error. If and the model assigns too small a probability , then : the negative-gradient update increases the logit. If the target is , then : the update decreases it.
Now suppose we have a larger training set . Let have row , and let
If and are the vectors of probabilities and gold labels, and denotes the all-ones vector, then
Writing this out in matrix form, with the two blocks stacked into a single vector,
where denotes the th coordinate of , so that the first rows of the matrix form and the final row of ones collects the bias derivatives.
This is the same calculation for every observation, collected into two matrix operations. The choice of transposes is simply further evidence that machine learning has a tendency to strange conventions. As before, the vector is the prediction error.
Another way to present these formulas is as an average. The log loss is an average of the per-sample log losses , and differentiation is linear, so the gradient of the log loss is the average of the per-sample gradients:
A gradient descent step
that uses this average over the whole training set (all samples) is called a full-batch step. The training set, used all at once in this way, is called the batch.
One run of gradient descent on the full training set is called an epoch of training. An alternative way to perform an epoch is minibatch, which averages over a small subset of the training set at each step, because for large training sets the full batch is too expensive to revisit at every training step. Note that different batch sizes do result in different gradient descent paths, hence different training outcomes.
The gradient descent algorithm for binary logistic regression becomes the following.
Algorithm 1.4 (gradient descent for logistic regression).
Input: data , assembled into the matrix whose th row is and the label vector ; learning rate ; number of steps ; and initial weights , .
For :
-
Compute the logits and probabilities of all samples at once:
where is applied to each coordinate separately.
-
Compute the two blocks of the gradient:
-
Update:
Output: .
Example 1.5 (one complete gradient step). Take the two one-dimensional training samples
so that
and initialize . Both logits are , so both probabilities are : in step 1 of Algorithm 1.4,
Each sample therefore contributes log loss , and the average loss at initialization is
The vector of prediction errors is
so step 2 gives the two coordinates of the full-batch gradient:
With learning rate , the update of step 3 gives
Consider the probability the updated model assigns to the gold label of each sample. On the second sample, the gold label is , which receives probability
On the first sample, the gold label is , which receives probability
as well.
The single gradient step has reduced the average loss on this training set: it has fallen from to
Now we turn to asking whether gradient descent is well-behaved. If the function we are minimizing is convex, every local minimum is a global minimum, so we can hope that gradient descent will get us to a global minimum. Gradient descent is nice in this way in the case of logistic regression.
Definition 1.6 (convex function). A function is convex if for all and all ,
Geometrically: the chord joining any two points of the graph lies on or above the graph. A convex function has no separate valleys for gradient descent to get trapped in.
Example 1.7 (the one-dimensional picture). Before we begin, we record a useful equivalent form for the loss, written in terms of the logit rather than the probability. The model assigns probability
to the outcome , and hence probability to the outcome . Taking logarithms,
Substituting these into the log loss gives
The function is sometimes called softplus. This softplus form of the loss makes the computation in the next example quick, and Exercise 3 uses it to prove that the loss is convex; its multiclass analog, log-sum-exp, appears in Section 3.
Now, in the case of one-dimensional feature vectors, where we freeze , we can draw a graph of the loss we are minimizing. The only parameter is . For the two-point dataset of Example 1.5 the loss works out to . This follows from the softplus form above, where the sample contributes and the sample contributes , which is the same number. This function is convex, but strictly decreasing, with infimum that is never attained. If we instead use the three samples , , , the loss becomes a convex bowl with a unique minimizer at .
Notice that our three-sample set of training data has a contradiction: different gold labels are assigned to the same feature vector. But real world data is like this! (A caution for later: the bowl in this picture depends on our having frozen . We return to this dataset after Theorem 1.11.)
How do we check that a function is convex? For a twice-differentiable function of one variable, convexity is equivalent to everywhere: the slope never decreases. In variables, the role of the second derivative is played by a matrix.
Definition 1.8 (Hessian). Let be twice differentiable. The Hessian of at is the matrix of second partial derivatives
Theorem 1.9 (second-order test for convexity). Let be twice continuously differentiable. Then is convex if and only if the Hessian is positive semidefinite at every point, i.e.
The quadratic form is the second derivative of along the line through in direction , so the theorem says exactly that is convex if and only if its restriction to every line has nonnegative second derivative.
Let us apply this test to the logistic-regression loss.
Theorem 1.10 (convexity and smoothness of the logistic loss). Let . Then the logistic-regression loss is convex. Moreover, its curvature is bounded: for every and every direction ,
Proof
We recap the setting from above: the parameter is , the training samples are , and the probabilities are . In the gradient we computed in Section 1, the parameter and each feature vector appear with one extra coordinate appended, the bias in one case and the constant in the other, so it is worth naming the stacked vectors. Write
so that , , and the gradient reads
Differentiate the gradient once more. The only dependence on on the right side of the gradient formula is through , so by the chain rule and the sigmoid derivative ,
The th summand of the gradient is the fixed vector scaled by , so its derivative in is times the row vector , that is, the outer product . Averaging the summands,
For any ,
Thus the Hessian is positive semidefinite at every , and by the second-order test, is convex.
For the upper bound, we estimate each summand twice over. First, the function on attains its maximum at , so . Second, by the Cauchy–Schwarz inequality,
Each summand is therefore at most , and so is their average.
Recall from the discussion of the second-order test that is the second derivative of along the line through in direction . The upper bound in the theorem therefore says that the gradient cannot change arbitrarily fast: along any unit direction, the second derivative of the loss is at most .
Theorem 1.11 (a baby gradient-descent guarantee). Consider a logistic regression model. Set , with as above, and suppose has a finite minimizer (Definition 0.4). If the learning rate satisfies , then gradient descent (Definition 1.2, applied to ) satisfies
for every . In particular, the loss values converge to the global minimum.
Proof sketch
A differentiable convex function with Hessian bounded above by satisfies the standard smooth-convex inequality
Insert the update into . Expanding the square and using the displayed inequality, together with , gives
Apply this at iterations and sum. The right side telescopes. The loss is non-increasing for this step size, so its final gap is at most the average of the preceding gaps, which gives the claimed bound.
Let us make a few notes on the hypotheses.
First, the restriction is necessary: a learning rate that is too large can overshoot. For a simple example, consider linear regression (not logistic regression). In that case, the loss looks like a parabola . One gradient step looks like
In this example, if , the factor has absolute value less than and the iterates converge to the minimum at ; but if , the factor has absolute value greater than , and each step jumps past the minimum to a point farther away than where it started. The iterates oscillate in sign with growing amplitude, and the loss diverges.
Second, the theorem assumes that a finite minimizer exists. This can fail. Call a training pair a positive sample if its gold label is , and a negative sample if . A binary dataset is linearly separable if some affine hyperplane places the feature vector of every positive sample strictly on one side and the feature vector of every negative sample strictly on the other. It turns out that if the data are separable, the infimum is never attained by any finite parameter, and the theorem does not apply. The converse is nearly true: a classical dichotomy of Albert and Anderson says that a finite minimizer exists if and only if the data cannot even be weakly separated, i.e. there is no nonzero with for every positive sample and for every negative sample. In particular, strictly separable data never admit a finite minimizer.
Why does separability exhibit this behaviour? Imagine our training samples are very clearly delineated: imagine that the ones with gold label are in one cluster and the ones with gold label in another cluster, and the two clusters are nicely separated in space so that a hyperplane can pass between them. Suppose one such hyperplane is of the form for some and . Then is an excellent choice for the model parameters, since the logit will then take on positive values on one side of the hyperplane and negative values on the other. To get a good model (one which assigns high probabilities to the gold labels), we want the logit to take on positive values on the side with the cluster of positive samples; if we didn’t make the right choice, just replace with to fix it.
Under this setup, the model assigns probability exceeding to every gold label in the training set. But if we replace with , for some large positive , we do even better, because we assign probabilities closer to . As , we get on the positive samples and on the negative samples. And the probabilities assigned to the gold labels approach . So the best parameter choice, in some sense, is to let approach . In other words, there’s no global minimum to the loss: the loss looks something like the blue two-sample curve in Example 1.7.
The standard repair, when a finite minimizer is wanted, is to add a penalty, or regularizer: an extra term, added to the loss, that grows as the parameters grow, so that large parameters are penalized. The most common choice is the penalty with — that is, we minimize instead of . This works because the penalized objective tends to as , so it attains a finite minimizer even on separable data, at the price of a small bias toward small weights. The penalty also improves the curvature. Its Hessian, as a function of , is , where denotes the identity matrix, so the penalized objective has Hessian bounded below by ; a function whose Hessian is bounded below by for some is called strongly convex. Strong convexity guarantees a unique minimizer, and for such objectives gradient descent converges geometrically — the error shrinks by a constant factor each step — rather than at the slower rate of Theorem 1.11.
2. Softmax and the simplex
Binary logistic regression produces a distribution on two labels. A language model needs a distribution on an entire vocabulary (Lecture 1, Section 0). Therefore, let , so that the number of possible labels is , and write
This is the probability simplex from Lecture 1. Its relative interior is
It is called a relative interior because the simplex lies in the affine hyperplane , which has dimension rather than . So we are taking its interior with respect to this hyperplane.
Definition 2.1 (softmax). For a vector , define
For , write . The second softmax coordinate is a sigmoid of the logit difference:
The first coordinate is , which carries the same information. Thus two-class softmax gives exactly the binary distribution of Section 0 if one uses as the binary logit and discards the redundant first coordinate in favour of the second one.
Each coordinate is positive, and the coordinates sum to , so softmax does land in , as the stated codomain asserts. The entries of the input vector are called logits, extending the terminology of Definition 0.2.
Recall from Definition 0.1 that for an event of probability , the odds are and the logit is the log-odds . With labels, the natural analogue compares two labels at a time: given a distribution , the ratio is the odds of label against label , and is their pairwise log-odds. For softmax the pairwise log-odds have an extremely simple form:
Thus only differences between logits matter to the output distribution: the pairwise odds depend on only through the differences , and since a probability vector is determined by its coordinate ratios (the coordinates must sum to ), so does itself. In particular, adding the same constant to every logit leaves the output unchanged.
Example 2.2 (softmax by inspection). Take the logits
Then
and hence
The third label has three times the odds of the first because . Adding to all three logits changes the exponentials to and changes none of the probabilities.
The preceding example reveals that softmax has one redundant direction. We now describe the geometry precisely. Let , let
and for write
That is, is the kernel of the mean: those vectors whose mean is zero.
A diffeomorphism is a smooth bijection with a smooth inverse.
Proposition 2.3 (softmax as a diffeomorphism to the open simplex). Softmax has the following properties.
-
Its image is .
-
It is invariant under a common shift:
for every .
-
Its restriction
is a diffeomorphism. The inverse is
where logarithms are taken coordinatewise.
In other words, for the differential geometer, softmax restricted to the zero-mean logits is a global coordinate chart on the open simplex: every strictly positive probability vector has exactly one zero-mean logit vector as coordinates, and passing between the two descriptions is smooth in both directions.
Proof
We already observed that softmax has positive coordinates summing to , so its image is contained in the relative interior. In the other direction, take . Every logarithm is defined, and
This proves the first assertion.
For any scalar ,
This proves shift invariance. Every affine line contains exactly one zero-mean representative,
Indeed, , while has mean .
It remains to verify the inverse. For , the vector has mean zero. Shift invariance and the first calculation give
Conversely, take and set . Coordinatewise,
Since has mean zero, the mean of the vector on the right is . Subtracting this mean recovers , so
Softmax is smooth because it is built from exponentials with a positive denominator, and is smooth where every . The restricted map is therefore a diffeomorphism.
Restricting to zero-mean logits is one way to choose a unique representation. Fixing a specified logit to be zero is another.
The term identifiable means that different parameter values produce different modeled distributions. Unrestricted softmax logits are not identifiable: and represent the same distribution. Their differences are identifiable.
3. Multinomial logistic regression
We now repeat binary logistic regression with possible labels. The parallel is exact:
| binary classification | -class classification |
|---|---|
| one logit | a vector of logits |
| sigmoid | softmax |
| Bernoulli distribution | categorical distribution |
| scalar error | vector error |
| affine decision boundary | pairwise affine decision boundaries |
The logits will again be affine functions of the features.
Definition 3.1 (multinomial logistic regression). Let be a set of classes and let be the feature vector space. For a parameter
define the logit map
Writing for the th column of , its th coordinate is
Here the colon in means “all row indices,” so is a column; similarly, denotes the entire th row. The entries of are the weights, the entries of are the biases, and the coordinates are the logits.
The associated multinomial logistic regression model, or softmax regression model, is the probabilistic classifier
defined by
Thus, for ,
We also write for . When and are fixed, we abbreviate .
The most probable label is the one with largest logit. The decision boundary between labels and is
or equivalently
It is a hyperplane. The pairwise boundaries divide into polyhedral regions. Within each region, the ordering of the logits—and hence the ordering of the class probabilities—is fixed.
Aside 3.1a (the two-class case). Let , with logits , and identify class with the positive label of binary logistic regression. Then
The probability of class is . Therefore two-class softmax regression is precisely binary logistic regression with the single identifiable logit . Adding the same constant to both logits changes neither probability.
For next-token prediction, take . The feature vector is a numerical representation of the context, and the observed class is the next token.
For a target class , let denote its one-hot vector: coordinate is and every other coordinate is (a pure mathematician would call this a standard basis vector 🙃). We will use the indicator notation
Thus .
Definition 3.2 (categorical cross-entropy). For logits , probabilities , and target , the one-sample categorical cross-entropy loss (also log loss) is
For training samples , the empirical loss (also average negative log likelihood or cost) is
These are the quantities of Definition 0.4, specialized to the softmax model. They follow the same maximum-likelihood recipe as Lecture 1, Section 3.
Example 3.3 (one three-class prediction). Suppose
and the observed class is . Example 2.2 gives
The loss is
If the observed class were , the loss would instead be . The probability vector is unchanged; only the observed coordinate changes.
Fix one sample . We next differentiate through the logits .
Proposition 3.4 (gradient of the multinomial log loss). In this setup,
The three gradients lie in , , and , respectively.
Proof
The loss depends on only through the logits . As a function of ,
For each ,
Hence . Since and ,
Assembling the weight derivatives column by column gives .
The logit-gradient coordinates sum to zero:
where . This had to happen: the loss is unchanged when every logit receives a common shift, so its directional derivative along vanishes.
The weight gradient is an outer product. Its th column is : prediction error for class , times the feature vector. In the two-class setting of Aside 3.1a, the two coordinates are opposites. If and the target is class , then
which is the binary derivative expressed in the redundant two-logit coordinates.
For Example 3.3,
A negative-gradient step raises the target logit relative to the other two: it adds to while subtracting from and from .
Over a training set, the empirical gradient is the average of the per-sample gradients. We can compute all samples at once by collecting them row by row.
Algorithm 3.5 (gradient descent for softmax regression).
Input: a feature matrix whose th row is ; a one-hot label matrix whose th row is ; a learning rate ; a number of steps ; and initial parameters and . Let .
For :
-
Compute the logit matrix and probability matrix
where softmax acts on each row. Row of is , and row of is .
-
Form the error matrix
Its th row is .
-
Compute the two gradient blocks:
-
Update within the same parameter spaces:
Output: and .
A minibatch is a small randomly chosen subset of the training samples. Minibatch methods use the same formulas with the average over a fresh minibatch in place of the average over all samples. Each step becomes much cheaper, at the price of a noisy estimate of the full gradient.
Proposition 3.6 (convexity of softmax regression). For fixed features, the empirical cross-entropy loss is convex in . The one-sample Hessian with respect to the logits is the matrix
which is positive semidefinite.
Proof
Differentiating gives
This is the entry of . For every ,
Thus the loss is convex in . Since is affine in , composition with this affine map preserves convexity, as does averaging over samples.
4. From individual units to feedforward networks
To increase expressiveness, we can combine “units” of logistic regression into networks.
4.1 Artificial neurons
Definition 4.1 (unit). A unit, or artificial neuron, is a function taking a feature vector to a value:
where is a fixed function called the activation function, the vector contains the weights , and the scalar is the bias. The intermediate value is the preactivation, and the output value is the activation of the unit.
We have already met a unit: binary logistic regression (Definition 0.2) computes exactly one unit, with the sigmoid as its activation function. The activation function is ; the weights and bias of the unit are the weights and bias of the logistic regression model; the preactivation is the logit ; and the activation is the predicted probability .
(Softmax regression is close to being a collection of units, one per logit, but not quite: the softmax is applied jointly to the whole logit vector, rather than to each preactivation separately.)
One historically important activation is the step function
A unit , i.e. a unit using the step function activation, is called a perceptron. It makes a hard binary decision separated by a hyperplane in .
The first question to ask is how expressive such units are. This is the question of what space of possible functions they represent.
The Boolean exclusive-or function, or XOR, is the function given by
Theorem 4.2 (one perceptron cannot compute XOR). There are no such that
at all four points of .
Proof
Correct classification at requires
Correct classification at and requires
Adding these two inequalities gives . Since ,
But correct classification at requires , a contradiction.
A line cannot separate the two positive XOR points from the two negative points . The convex hull of each pair is the diagonal segment joining it, and the two segments cross at . A hyperplane separator would have to put their convex hulls on opposite sides, which is impossible.
The obstruction is not that XOR is somehow mysterious. It is that one affine decision boundary has the wrong geometry. The AND and OR functions are linearly separable (you can check this).
4.2 Combining units into networks
The rectified linear unit is
Unlike the perceptron, it retains the size of a positive preactivation. Consider two units
and a third unit, taking as its input:
We will now string these together. The diagram below shows how the units should be imagined as being arranged in layers. The final unit(s) are the output unit(s) — those whose results are not fed into further units. Units whose outputs do feed into other units are called hidden units. Here, and are hidden units and is the single output unit.
On the four possible inputs, is , , or , and
The complete calculation is
(The output unit’s ReLU changes nothing here, since is already nonnegative at all four inputs.)
Building a network with hidden units has changed the expressivity: now we can express XOR.
A scalar activation acts on vectors coordinatewise:
Definition 4.3 (feedforward network). A feedforward neural network, or multilayer perceptron (MLP), with layer widths
is a map defined recursively by
and
Here and for , while for . Each is an activation function applied coordinatewise. The vectors are the preactivations, and the vectors are the activations. When the final output is fed to softmax, its coordinates are the logits.
The parameter collects every weight and bias entry. The intermediate vectors are the hidden layers; is the number of affine layers, or depth, and is the width.
A feedforward network is a deterministic function, not by itself a probabilistic model. When , softmax gives the associated classifier
Some authors count depth differently, for example by counting only hidden layers. Any depth statement should therefore declare its convention. We will care mainly about whether depth grows linearly or stays fixed, so a difference of one is harmless.
At a hidden unit in layer , the node-and-arrow calculation is
Writing all units at once gives . The diagram and the matrix formula are two views of exactly the same computation.
In fact, if we use the identity function as the activation, and zero biases, then the fancy diagram above is literally a diagram of matrix multiplication 🙃.
Proposition 4.4 (without nonlinearities, depth collapses). If every activation is the identity map, then a feedforward network is affine, regardless of its depth.
Proof
The composition of two affine maps is affine:
Applying this identity repeatedly collapses all layers to one map
Here “eff” abbreviates effective: and are the single weight matrix and bias vector obtained after all the affine layers have been composed.
Thus additional linear layers may change the parametrization, but not the set of functions represented.
The nonlinear activation is what allows a network to bend decision boundaries and build new features. Matrix multiplication supplies rich linear mixing; activation functions prevent all of those matrices from collapsing into one.
4.3 Common activation functions
The following plots use the same horizontal scale. Their vertical scales are chosen to show the characteristic shape rather than to compare numerical magnitudes exactly.
| activation | formula | strengths, limitations, and common use |
|---|---|---|
| step | It is discontinuous and has derivative away from the threshold, so ordinary gradient descent cannot train it effectively. | |
| sigmoid | Smooth, bounded. It can saturate: for large , its derivative is near , weakening gradients. | |
| hyperbolic tangent | Smooth, bounded, centered at . Historically common and used in Project Step 3; it also saturates. | |
| ReLU | Cheap, non-saturating on the positive half-line, piecewise linear. It is not differentiable at , and a unit stuck on the negative side can receive zero gradient. | |
| GELU | A smooth version of ReLU. Common in transformers, used in Project Step 5; it costs more to evaluate than ReLU. Here denotes the cumulative distribution function of a standard | |
| normal random variable. |
Replacing the step function by a smooth or piecewise-linear activation lets a unit retain how far its preactivation lies from zero. Differentiability matters for training (next lecture), although an isolated corner such as ReLU’s at zero is easily handled. For a single unit, changing the activation does not by itself bend the level sets of the preactivation; the nonlinear geometry comes from combining units.
An activation saturates where changing its input has almost no effect on its output, equivalently where its derivative is close to zero. Sigmoid and saturate in both tails. During backpropagation, derivatives from successive layers are multiplied, so many saturated units can make a gradient very small before it reaches an early layer. ReLU does not saturate on its positive half-line, but on its negative half-line its derivative is zero; a ReLU that remains there on all relevant inputs is sometimes called a dead unit.
Softmax is different from every entry in the table. It acts on a whole vector, not coordinatewise, and its coordinates must interact so that they sum to . For this reason it is commonly used in the output (last) layer (where we are trying to classify something), while ReLU, GELU, or is used in hidden layers.
Consider the example of a neural network classification model for hand-written digits. Perhaps the input values (the original feature vector) are just the darkness of each pixel in a small image file. That’s a design choice. At a hidden layer, one might expect that the activations represent more useful distinguishing features, something like “how dark is the upper half” or “how round is the bottom”. These would be human expectations, however: the model, through training, finds its own best hidden activations, which may not have an easily human-understandable meaning.
You can watch this happen in Adam Harley’s interactive visualization of small networks trained on hand-written digits: draw a digit and see every hidden activation light up, layer by layer. Working out what, if anything, a hidden unit has learned to detect is the research field of interpretability; the Distill article Feature Visualization shows images of the inputs that most excite individual hidden units of an image classifier.
4.4 Neural language models
We can now put the pieces together. A context must first be represented by numbers, a feedforward network turns those numbers into one logit per vocabulary token, and softmax turns the logits into probabilities.
Definition 4.5 (feedforward neural language model). Let be a vocabulary of size . Suppose an encoder
represents a context by the feature vector . The encoder may be fixed or may have trainable parameters . Let
be a feedforward network. With , the associated conditional language model is
The vector contains one next-token logit for each vocabulary token.
Example 4.6 (Project Step 2: a hand-wired diamond classifier). Let . The hidden layer
has four units:
Since , summing these activations produces
Choose a confidence parameter and define two output logits, ordered as “outside” and “inside,” by
Thus
With , the classifier is
By Aside 3.1a,
The two logits are equal exactly when . This is a diamond, not a hyperplane. Four hidden units first build the nonlinear feature ; the output layer then makes an ordinary affine decision in that new feature. Project Step 2 asks you to assemble these units as matrices, inspect their activations, and modify the geometry.
Example 4.7 (Project Step 3: “Bengio-style” neural -gram). Let be an embedding matrix, and write for its th row. The token map
turns each token into a feature vector. For a context of tokens , concatenate those rows:
A one-hidden-layer network of width computes
For , the associated language model is
With , , , , and , the parameter count is
This grows linearly with context length . An unrestricted conditional-probability matrix (that is to say, a basic -gram model) would need entries, exponentially many in .
5. Universal approximation
The XOR network is one exact construction. The main result of this section says that such examples are not isolated: even a network with only one hidden layer can approximate every continuous function on a compact set, provided its activation is not a polynomial.
Let be compact, and let denote the real-valued continuous functions on . For , define the uniform norm
We use this norm because it controls the worst error anywhere on . An average-error norm could hide a large mistake on a small part of the domain; a uniform bound cannot. Compactness ensures that a continuous function is bounded and attains its maximum error, so the displayed quantity is finite.
A family is dense in under the uniform norm if, for every and every , some satisfies
Here is the principal theorem.
Theorem 5.1 (universal approximation). Let be continuous and not a polynomial. For every compact , the one-hidden-layer networks
where the width may vary, are dense in under the uniform norm.
ReLU, sigmoid, , and GELU are all continuous and non-polynomial, so each meets the hypothesis. The theorem permits vector outputs as well: place finitely many scalar networks side by side, one for each output coordinate.
Read the quantifiers carefully. For every target and tolerance , the theorem promises that some finite width and some parameters exist. It does not give a useful width, construct the parameters, show that gradient descent finds them, or show that finitely many training observations determine the target. In the worst case even an -Lipschitz function on may require resolution on the scale in every coordinate—roughly
local regions. Thus existence alone does not make the network economical, trainable, or likely to generalize.
5.1 Examples covered by the theorem
Example 5.2 (absolute value). The absolute-value function is already a tiny ReLU network:
In the notation of Definition 4.3, its widths are , , and , with
Each hidden ReLU supplies one linear half of the graph.
The same idea constructs every continuous piecewise-linear function on an interval: a ReLU placed at a breakpoint changes the slope from that point onward.
Proposition 5.3 (ReLU approximation on an interval). Let be continuous. For every , there is a one-hidden-layer ReLU network such that
The theorem also applies directly to probabilistic models.
Corollary 5.4 (approximating continuous probability maps). Suppose is compact and
is continuous. For every , a one-hidden-layer network with output logits can be chosen so that its softmax output satisfies
Compactness keeps the target uniformly away from the boundary: each continuous coordinate has a positive minimum on . If a target allows exact zero probabilities, it can first be moved by an arbitrarily small amount toward the uniform distribution.
5.2 Why the theorem is true
We first prove the interval result explicitly.
Proof of Proposition 5.3
A continuous function on a compact interval is uniformly continuous. Choose a partition
fine enough that whenever and lie in the same subinterval. Let be the polygonal interpolant through the points . On , the value is a convex combination of and . Both endpoint values differ from by less than , so their convex combination does too. Hence .
Let
be the slope of on the th subinterval. For ,
The first ReLU supplies the initial slope; the unit at changes that slope by . Thus a one-hidden-layer ReLU network realizes exactly.
For higher-dimensional compact sets there is no equally short polygonal formula. The following outline records the functional-analytic mechanism behind Theorem 5.1; the full projection argument is proved by Leshno, Lin, Pinkus, and Schocken (1993).
Proof outline of Theorem 5.1
A ridge function has the form : it varies through one scalar projection of . Suppose the closed linear span of all such ridge functions were a proper subspace of . The Hahn—Banach theorem would give a nonzero continuous linear functional that vanishes on that span. By the Riesz representation theorem, this functional is integration against a nonzero finite signed measure on . Consequently,
for every and .
Varying and probes every one-dimensional projection of . The projection argument in the cited paper shows that a continuous activation can admit such a nonzero annihilating measure only if it is a polynomial. Since is not a polynomial, must be zero, a contradiction. Therefore the ridge functions have dense linear span.
The non-polynomial condition is essentially necessary for shallow networks. If is a polynomial of degree , every displayed one-hidden-layer sum is a polynomial of degree at most . On a compact set with nonempty interior, that fixed finite-dimensional space is not dense in .
Background aside 5.5. Hahn—Banach separates a point from a closed linear subspace by a continuous linear functional. The Riesz representation theorem identifies continuous linear functionals on with integration against finite signed measures. These standard results from functional analysis are not prerequisites for using the theorem.
Proof of Corollary 5.4
By Proposition 2.3, the centered logit map
is continuous. Approximate each coordinate uniformly by a shallow network, and combine all their hidden units into one network with outputs. Softmax is uniformly continuous on a compact neighborhood of , so sufficiently accurate logits give the required uniform probability approximation.
Example 5.6 (depth can save width). Universal approximation allows one hidden layer to become arbitrarily wide. A simple family shows that composition can sometimes represent the same function much more efficiently.
Define the triangle map
On it rises linearly from to and then falls linearly back to . Let be its -fold composition.
One copy of is a width-three ReLU block. Stacking copies therefore computes exactly with width and depth at most . In contrast, suppose a one-hidden-layer ReLU network satisfies
At the dyadic points , the values of alternate between and . On each of the disjoint “teeth,” the two endpoints are near while the midpoint is near . No affine function can do that on the whole tooth, because its midpoint value is the average of its endpoint values. Thus needs a breakpoint inside every tooth. A width- shallow ReLU network has at most breakpoints, so necessarily
This is a depth separation: constant width and depth proportional to compete with exponential shallow width. It is an expressivity statement for a specially constructed compositional family. It does not say that every task benefits from depth, or that training will discover the short deep representation.
The preceding results concern representation. They do not settle optimization or generalization, which we separate next.
6. Approximation, optimization, and generalization
Three logically different questions are often compressed into the vague claim that a model “works.”
Distinguishing them requires one piece of vocabulary. The population is modeled as a probability distribution on input–label pairs : an idealized, inexhaustible source of input–label pairs, of which the training set is one finite sample and future data are further samples. A loss penalizes the model’s prediction on a single pair; a risk is an average of losses over many pairs. Averaging over the whole distribution gives the population risk (also called the population loss), while averaging over the training sample gives the empirical risk (the training loss). Both are defined precisely below.
| question | mathematical form | what could go wrong |
|---|---|---|
| Approximation | Does some parameter in the model family have small population risk? | The architecture may be incapable of representing the target economically. |
| Optimization | Does the training algorithm find a parameter with small empirical risk? | The objective may be nonconvex, ill-conditioned, noisy, or approached only at infinite norm. |
| Generalization | Does performance on the training sample persist on new data? | The fitted model may exploit accidental features or memorize the sample. |
To make the distinction precise, let be the population distribution on input–label pairs , and let be a loss. The population risk is
whereas the empirical risk on training observations is
Let denote the best risk attainable without restricting to the chosen model family. Then
is an approximation error. For the output of a training algorithm,
is an optimization error. The difference is one generalization gap.
Adding and subtracting these quantities gives the exact bookkeeping identity
The last line contains two sample-to-population discrepancies. Individual terms can have either sign, but the identity shows where distinct kinds of reasoning enter.
Example 6.1. The ReLU network in Section 4 represents XOR exactly, so its approximation error on the four Boolean inputs can be zero. That fact alone does not show that a particular random initialization and optimizer find the displayed weights. If training data omit , even perfect optimization on the three observed points does not determine the missing label; a fitted network can have zero training error and still fail to generalize.
Remark 6.2 (a theoretical scorecard). Universal approximation and depth separation are rigorous approximation results. Logistic and softmax regression have unusually clean convex optimization theory. Deep-network losses are generally nonconvex. Optimization guarantees exist in special regimes, including some infinite-width neural-tangent-kernel limits, but those regimes do not capture every form of feature learning. Classical VC-dimension and Rademacher-complexity bounds control generalization through the size of a function class, yet can be loose or vacuous for heavily overparametrized networks. Why ordinary gradient methods so often find useful representations that generalize remains only partially understood.
7. The Project Step 2 diamond classifier
Example 4.6 defined the small network used in Project Step 2. We now collect its computation in one place. The point is not to train the network yet, but to see exactly how scalar units become matrix layers and how a hidden layer changes the geometry of a classifier.
Let . The forward pass is
The matrices are
where . The output coordinates are ordered as outside, inside.
Theorem 7.1 (geometry of the diamond network). For the network above,
Consequently:
- the two class probabilities are equal exactly on ;
- points with are classified as inside;
- points with are classified as outside.
Thus the decision boundary is the diamond with vertices , , , and .
Proof
The first affine layer gives
so the hidden activation is
Therefore
The output logits are and . Their difference is
The two-class softmax identity from Aside 3.1a now gives the probability formula. Since sigmoid is increasing and , the three geometric claims follow.
For , a few forward passes are:
| | hidden sum | | | |---|---:|---:|---:| | | | | | | | | | | | | | | | | | | | |
The parameter changes confidence but not the decision boundary. As , both logits approach zero and the output approaches the uniform distribution. As grows, probabilities approach on the predicted class away from the boundary. This is the two-class version of changing softmax temperature.
Summary
-
Binary logistic regression makes the log-odds an affine function of the features. Sigmoid converts the scalar logit to a Bernoulli probability, and binary cross-entropy is its negative log-likelihood.
-
The logistic-regression gradient is prediction minus target, multiplied by the input. Its loss is convex, and suitably small-step full-batch gradient descent has a global convergence guarantee when a finite minimizer exists.
-
Softmax converts logits into a strictly positive categorical distribution. It parametrizes the relative interior of the simplex with one redundant common-shift direction, and logit differences are pairwise log-odds.
-
Multinomial logistic regression is the direct multiclass analogue of binary logistic regression. Its logit gradient is , and its fixed-feature cross-entropy is convex.
-
A perceptron has one affine boundary and cannot compute XOR. A width-two ReLU hidden layer computes XOR exactly. More generally, nonlinear activations prevent a stack of affine maps from collapsing to one affine map.
-
A continuous non-polynomial activation gives one-hidden-layer universal approximation on compact sets. This establishes existence, not an efficient width, a successful optimization method, or generalization from finite data.
-
Depth can express repeated composition exponentially more efficiently than a shallow network for particular function families. This is a representation theorem, not a claim about every task.
-
Project Step 2 hand-wires a genuine hidden-layer network. Four ReLU units construct ; an affine output layer and softmax turn that feature into a diamond classifier. The parameter changes confidence without changing the boundary.
Exercises (paired with Step 2)
A star marks a Project Step 2 task.
-
Odds and boundaries. For the delay model in Example 0.3, find the probability, odds, and predicted class at . Sketch its decision boundary and indicate which side is classified as a delay.
-
A gradient step by hand. Repeat Example 1.5 with learning rate and initial values , . Compute all logits, probabilities, gradients, updated parameters, and the loss before and after the step.
-
Prove directly from that binary logistic loss is convex in . Determine when its second derivative is largest.
-
★ Trace the diamond network. For each of , , , and , compute , , , and at . Verify Theorem 7.1 and explain the geometric role of each hidden unit.
-
★ Move and stretch the diamond. Construct for a classifier whose boundary is
State every matrix dimension. Check that your network reduces to the Project Step 2 network when and .
-
Temperature. For , analyze . Prove that it tends to the uniform distribution as and, as , to the uniform distribution on the set of maximizers of . Include the unique maximum as a special case.
-
Perceptrons. Find perceptron weights and biases that compute AND and OR on . Use either the inequalities in Theorem 4.2 or a geometric argument to reprove that XOR is impossible.
-
A second XOR network. Verify the weights in the XOR diagram by writing its two weight matrices and two bias vectors. Modify only the output affine map to compute XNOR on .
-
Why activation matters. Derive explicit formulas for and when three affine layers are composed without activations. Identify the rank constraints imposed by bottleneck widths. Explain why widening those bottlenecks can remove the rank constraints but still cannot introduce nonlinearity.
-
Prove that a one-hidden-layer ReLU network of width on has at most distinct breakpoints and at most affine pieces. When can it have fewer?
-
Triangle-map depth. Verify the three-ReLU formula for . Prove by induction that takes alternating values at and has affine pieces.
-
Redundancy and regularization. Show that every rowwise softmax equivalence class contains a unique zero-mean logit vector, and that this vector has the smallest Euclidean norm in its class. Then explain why adding does more than choose representatives: it also changes the optimal probability distributions. Compare this shrinkage qualitatively with Laplace smoothing.
-
From logits to probabilities. Supply the uniform-continuity details in Corollary 5.4. Show also that for a continuous with compact , there is a single such that for every and .
-
Three different failures. Give one small classification example exhibiting each of the following: approximation error despite perfect optimization; optimization error despite a sufficiently expressive model; zero training loss but positive test loss. State clearly which model family, training procedure, and data distribution you use.
Pointers
Bengio, Ducharme, Vincent, and Jauvin, A Neural Probabilistic Language Model (2003); Cybenko (1989); Hornik (1991); Leshno—Lin—Pinkus—Schocken (1993); Pinkus, Approximation Theory of the MLP Model in Neural Networks (1999); Telgarsky, Representation Benefits of Deep Feedforward Networks (2015) and Benefits of Depth in Neural Networks (2016); Higham and Higham, Deep Learning: An Introduction for Applied Mathematicians. See the resources page, Project Step 2, and Project Step 3.