From Regression to Neural Networks
A neural network is a regression with a more flexible shape. Like a linear regression, it predicts an outcome from some inputs by choosing parameters that make the prediction errors small on the data. Unlike a linear regression, it can bend to fit relations that are not straight lines. This chapter builds a network from the regression you already know, explains how its parameters are found, extends it from predicting numbers to choosing among categories, and then turns to the problem that dominates machine learning in finance: a flexible model fits the data it was trained on too well, and its performance on new data is what counts.
Regression as minimizing a loss
A linear regression predicts an outcome y_i from an input x_i with a straight line, \hat{y}_i = \beta_0 + \beta_1 x_i. Ordinary least squares chooses the intercept and slope that minimize the mean squared error, L(\beta_0, \beta_1) = \frac{1}{n} \sum_{i=1}^{n} \left( y_i - \beta_0 - \beta_1 x_i \right)^2. \tag{1} The function L is called the loss. For a straight line, calculus gives the minimizing \beta_0 and \beta_1 in closed form, which is the formula a statistics package uses. For the models in this chapter no such formula exists, and the loss has to be minimized numerically. Seeing linear regression as one case of “choose the parameters that minimize a loss” is the step that leads to everything else.
Gradient descent
The gradient of the loss, \nabla L, points in the direction in which the loss rises fastest. Gradient descent starts from a guess for the parameters \pmb{\theta} and repeatedly takes a small step in the opposite direction, \pmb{\theta}_{k+1} = \pmb{\theta}_{k} - \eta \, \nabla L(\pmb{\theta}_{k}), \tag{2} where \eta > 0 is the learning rate, the size of the step. Near a minimum the gradient is close to zero, so the steps shrink and the parameters settle.
Figure 1 shows both behaviors for the slope of a simple regression. Choosing the learning rate is part of the work: too small and training takes forever, too large and it never settles. Modern variants of gradient descent, such as the Adam method used in the notebooks, adapt the step size as they go, but the idea is the same.
With millions of observations, computing the gradient on the whole sample at every step is slow. Stochastic gradient descent computes it on a small random batch of observations instead, which gives a noisy but cheap estimate. One pass through all the batches is called an epoch, and training usually runs for many epochs.
A neural network
A linear model can only draw straight lines (or flat planes, with several inputs). Many relations are not straight. The chance that a borrower defaults may barely move with debt up to some level and then rise steeply, and whether an image shows a 3 or an 8 depends on combinations of pixels, not on any one pixel alone.
A neural network with one hidden layer builds a curve out of simple pieces. Suppose there are k inputs, collected in the vector \mathbf{x} = (x_1, \dots, x_k)'. The network has m hidden units, numbered j = 1, \dots, m. Unit j has its own intercept w_{j0} and its own vector of slopes \mathbf{w}_j = (w_{j1}, \dots, w_{jk})', and it first computes z_j = w_{j0} + \mathbf{w}_j' \mathbf{x} = w_{j0} + w_{j1} x_1 + \dots + w_{jk} x_k, \tag{3} a linear regression of its own. (The prime denotes a transpose, so \mathbf{w}_j' \mathbf{x} is the sum of the products.) It then passes z_j through a nonlinear function g, called the activation. The output of the network is a linear regression on the m values g(z_j), with intercept \beta_0 and slopes \beta_1, \dots, \beta_m: \hat{y} = \beta_0 + \sum_{j=1}^{m} \beta_j \, g\left( w_{j0} + \mathbf{w}_j' \mathbf{x} \right). \tag{4} The units are called hidden because they are not in the data: the inputs \mathbf{x} and the outcome y are observed, while z_j and g(z_j) exist only inside the model. Machine learning has its own names for familiar objects. The slopes w_{jk} and \beta_j are called weights, and the intercepts w_{j0} and \beta_0 are called biases (which have nothing to do with a biased estimator). A layer is a group of units computed at the same stage, so this network has one hidden layer between its inputs and its output. Together, the weights and biases are the network’s parameters \pmb{\theta}: (k + 1) m in the hidden layer and m + 1 in the output.
The most common activation today is the rectified linear unit, or ReLU, g(z) = \max(z, 0): zero when z is negative and equal to z when it is positive, a straight line with a single kink at zero. With one input x, unit j computes \max(w_{j0} + w_{j1} x, 0), which is zero on one side of the point x = -w_{j0}/w_{j1} and a straight line on the other: to the right of the kink if w_{j1} > 0 and to the left if w_{j1} < 0. The output adds up these kinked lines, each scaled by its weight \beta_j, which can be negative. A sum of enough kinked lines can follow any reasonable curve, the way a polygon with enough sides can follow a circle, and this is why networks can fit so many shapes.
Figure 2 draws both models as graphs. Linear regression is the special case with no hidden layer: the input is multiplied by \beta_1 and the intercept is added. The network inserts a column of hidden units between inputs and output. Every input feeds every hidden unit with its own weight, and every hidden unit feeds the output with its own weight, which is why the parameter count grows quickly with the number of units.
Figure 3 opens up one hidden unit. It does two things: it computes a linear regression of its own, z = w_{j0} + \mathbf{w}_j'\mathbf{x}, and it passes the result through the kink. Without the kink, the output would be a linear combination of linear combinations, which is again a straight line, and the hidden layer would add nothing. The activation is what lets the network bend.
Figure 4 fits both models to data generated from the wave \sin(2x) plus noise. The network has eight hidden units, so it has 8 \times 2 + 8 + 1 = 25 parameters, against two for the line.
Figure 5 shows how the network builds its curve. Each hidden unit with a positive weight on x is zero to the left of its kink and a straight line to the right of it; a unit with a negative weight is active to the left of its kink instead. The output weight \beta_j scales each piece and sets whether it slopes up or down. Training chose the kinks and the weights so that the intercept plus the sum of the pieces tracks the data. Here three units with kinks near -0.7, 0.4 and 1.0 trace the trough, the rise and the peak, and a fourth, with its kink at the right edge of the data, adds a gentle slope across the whole range. The other four units ended up zero for every x in the sample and contribute nothing, which is common: a network usually has more units than the shape requires. With four kinks the fit is a polygon, close to the wave but not smooth, and its mean squared error is 0.08 against 0.43 for the line; more units would give more and shorter pieces.
Deeper networks
The network in 4 has a single hidden layer. A deep network stacks several, and each layer takes the outputs of the layer before it as its inputs. Matrix notation keeps this compact. Stack the weight vectors \mathbf{w}_j' of a layer’s units as the rows of a matrix \mathbf{W}, so that \mathbf{W}\mathbf{x} is the vector of their linear combinations, collect their intercepts in a vector \mathbf{w}_0, and apply g to each element of a vector separately. A network with L hidden layers then computes \begin{gathered} \mathbf{h}^{(1)} = g\left( \mathbf{w}^{(1)}_0 + \mathbf{W}^{(1)} \mathbf{x} \right), \qquad \mathbf{h}^{(\ell)} = g\left( \mathbf{w}^{(\ell)}_0 + \mathbf{W}^{(\ell)} \mathbf{h}^{(\ell - 1)} \right) \quad \text{for } \ell = 2, \dots, L, \\ \hat{y} = \beta_0 + \pmb{\beta}' \mathbf{h}^{(L)}. \end{gathered} \tag{5} Here \mathbf{h}^{(\ell)} is the vector of the m_\ell values computed by hidden layer \ell, \mathbf{W}^{(\ell)} is a matrix with m_\ell rows and m_{\ell - 1} columns (with m_0 = k, the number of inputs), and \mathbf{w}^{(\ell)}_0 holds the layer’s m_\ell intercepts. With L = 1 this is 4 again. The number of units in a layer is its width, and the number of hidden layers is the network’s depth; deep learning is the use of networks with many layers.
Figure 6 draws a network with two hidden layers. Each unit in the second layer applies a kink to a weighted sum of functions that are already kinked, so a deep network builds bends out of bends. One hidden layer with enough units can already approximate any reasonable function, but a deeper network can often produce the same shape with far fewer units (Goodfellow et al. 2016, ch. 6).
Parameters add up quickly. Hidden layer \ell has m_\ell (m_{\ell - 1} + 1) of them, one weight for each unit of the layer below plus an intercept for each of its own units, and the output has m_L + 1. The network used for Figure 8 below has one input and two hidden layers of 200 units, so it has 200 \times 2 + 200 \times 201 + 201 = 40{,}801 parameters, and it is trained on 60 observations. In PyTorch, each pair \mathbf{W}^{(\ell)}, \mathbf{w}^{(\ell)}_0 is an nn.Linear layer and each activation an nn.ReLU, so that network is written nn.Sequential(nn.Linear(1, 200), nn.ReLU(), nn.Linear(200, 200), nn.ReLU(), nn.Linear(200, 1)).
Backpropagation
The parameters of any of these networks are found exactly as before: define the loss (1) and minimize it by gradient descent (2). Gradient descent needs the derivative of the loss with respect to every parameter, and for a network that is where the difficulty lies.
The brute-force approach nudges one parameter at a time. With n parameters in \pmb{\theta} and a small step \epsilon, \frac{\partial L}{\partial \theta_i} \approx \frac{L(\pmb{\theta} + \epsilon \, \mathbf{e}_i) - L(\pmb{\theta})}{\epsilon}, \qquad i = 1, \dots, n, \tag{6} where \mathbf{e}_i has a one in position i and zeros elsewhere. Each evaluation of L is a pass of the whole sample through the network, so one gradient costs n + 1 passes. For the 40,801 parameters of the network behind Figure 8, a single step of gradient descent takes 40,802 passes through the data, and today’s largest networks have billions of parameters. The approximation is also imprecise, because a small \epsilon subtracts two nearly equal numbers (Baydin et al. 2018).
The chain rule of calculus does far better. Take the network of Figure 3 with one input and one hidden unit, and the loss on a single observation, \ell = (y - \hat{y})^2. The forward pass computes, in order, z = w_0 + w_1 x, \qquad h = g(z), \qquad \hat{y} = \beta_0 + \beta_1 h, \qquad \ell = (y - \hat{y})^2. The backward pass then applies the chain rule in reverse order, from the loss back to the input: \begin{gathered} \frac{\partial \ell}{\partial \hat{y}} = -2 (y - \hat{y}), \qquad \frac{\partial \ell}{\partial \beta_0} = \frac{\partial \ell}{\partial \hat{y}}, \qquad \frac{\partial \ell}{\partial \beta_1} = \frac{\partial \ell}{\partial \hat{y}} \, h, \\ \frac{\partial \ell}{\partial z} = \frac{\partial \ell}{\partial \hat{y}} \, \beta_1 \, g'(z), \qquad \frac{\partial \ell}{\partial w_0} = \frac{\partial \ell}{\partial z}, \qquad \frac{\partial \ell}{\partial w_1} = \frac{\partial \ell}{\partial z} \, x. \end{gathered} \tag{7} For the ReLU, g'(z) is 1 when z > 0 and 0 otherwise. Each derivative reuses the one computed just before it: \partial \ell / \partial \hat{y} is computed once and serves \beta_0, \beta_1 and z, and \partial \ell / \partial z serves both weights of the hidden unit. Nothing is computed twice, and nothing is approximated.
A deep network works the same way. The forward pass computes and stores the values of every layer in 5. The backward pass carries the derivative of the loss with respect to each layer’s values from the output back toward the inputs, one layer at a time, and picks up the derivatives with respect to that layer’s weights and intercepts along the way. This is backpropagation. Its cost is a small multiple of the cost of the forward pass, always less than six and typically two or three, whatever the number of parameters (Baydin et al. 2018). For the network behind Figure 8, a gradient costs the equivalent of two or three passes instead of 40,802. That difference is what makes networks with millions or billions of parameters trainable at all.
The idea is not new. Running the chain rule backward through a computation, called reverse-mode automatic differentiation in numerical analysis, is usually credited to Linnainmaa’s 1970 master’s thesis and a 1976 article (Linnainmaa 1976), and Rumelhart et al. (1986) made it famous as the way to train networks with hidden layers. For a long time, though, the backward pass had to be derived on paper and coded by hand for each new model, which is slow and prone to error (Baydin et al. 2018). What changed is that libraries such as PyTorch now apply the chain rule automatically: they record the operations of the forward pass as the code runs and then run through them in reverse. Any model a user can write down gets its exact gradient for the cost of a few forward passes. That is what the call .backward() does in the code of this chapter and of the notebooks. The calculus of a first course, carried out by a computer, together with faster hardware and much larger datasets, is what turned neural networks into the tools behind today’s language models. Goodfellow et al. (2016) is the standard reference for all of this.
Classification
So far the outcome has been a number. Many problems ask instead for a category: whether a loan applicant will repay, or which of ten digits a handwritten character is. The second problem has a place in the history of finance. In the 1990s, LeCun et al. (1998) built neural networks that read the amounts handwritten on bank checks; their system was in commercial use in NCR’s check readers and processed millions of checks in banks across the United States. To train it they assembled 70,000 images of handwritten digits from collections of the National Institute of Standards and Technology, the MNIST database, shown in Figure 7.
For a model, each image is a vector \mathbf{x} of 28 \times 28 = 784 pixel values. A classifier with C classes produces C numbers, one score s_c per class, and its answer is the class with the highest score. In a linear classifier each score is a linear regression on the pixels, s_c = w_{c0} + \mathbf{w}_c'\mathbf{x}; in a network, the scores are the outputs of the last layer, computed from the hidden units. The softmax function turns the scores into probabilities that are positive and add up to one: p_c = \frac{e^{s_c}}{e^{s_1} + e^{s_2} + \dots + e^{s_C}}, \qquad c = 1, \dots, C. \tag{8} Training needs a loss to minimize, as the squared error was for a regression. The usual one is the cross-entropy, the average of minus the log probability the model gives to the correct class y_i: L = -\frac{1}{n} \sum_{i=1}^{n} \ln p_{y_i}(\mathbf{x}_i). \tag{9} It is zero when the model gives every correct class probability one, and grows without bound as the probability of a correct class falls toward zero. Minimizing it is maximum likelihood: with linear scores, this is the multinomial logistic regression of statistics courses, and with two classes it is the ordinary logit. Gradient descent and backpropagation work exactly as before, with 9 in place of 1.
The notebook Reading Handwritten Digits trains both models on the 60,000 training images of MNIST and tests them on the other 10,000, written by different people. The linear classifier reads 92% of the test digits correctly; a network with one hidden layer of 128 ReLU units reads 97%, cutting the error rate from 7.8% to 2.8%. LeCun et al. (1998) report the same ranking with the methods of their time, test errors of 12.0% for a linear classifier and 4.7% for a network with one hidden layer of 300 units. A linear classifier can only compare the ink in an image with one template per digit, while the hidden units respond to combinations of strokes. Unlike the financial problems of the chapter Predicting Stock Returns, digits are a problem with a strong signal and plenty of data: the network reads 97.9% of the training digits and 97.2% of the test digits, so what it learned carries over to digits it has never seen.
Overfitting
Flexibility has a cost. A network with enough parameters can fit the noise in its training data as well as the relation behind it, and then it predicts new data badly. This is overfitting, and it is the central problem of machine learning.
The defense is to judge a model only on data it was not trained on. The usual practice splits the sample in three:
- a training set, used to fit the parameters;
- a validation set, used to choose among models and to decide when to stop training;
- a test set, used once, at the end, to report how well the chosen model does.
Figure 8 shows the typical pattern. Early in training, both losses fall: the network is learning the relation. Later, the training loss keeps falling while the validation loss rises: the network is memorizing the training noise. Stopping at the lowest validation loss, called early stopping, is one remedy. Others shrink the model’s flexibility directly, for example by penalizing large weights in the loss (weight decay) or by using fewer hidden units.
Practice Problems
These problems give you a chance to practice the concepts introduced in this chapter. Try to solve each one on your own before expanding the solution.
Problem 1 (Choosing a Learning Rate) You minimize a regression loss by gradient descent with three learning rates and record the loss after 50 steps:
| Learning rate | Loss after 50 steps |
|---|---|
| 0.001 | 0.912 |
| 0.1 | 0.251 |
| 2.0 | 4.7e12 |
Which statement is most accurate?
- The learning rate of 0.001 is best, because small steps are always safer.
- With a learning rate of 2.0 the steps overshoot the minimum and the loss explodes; 0.001 is too small to get close to the minimum in 50 steps; 0.1 works best here.
- The learning rate does not matter, because gradient descent always finds the minimum.
- A loss of 4.7e12 shows that the data contain errors.
Solution
The answer is (b). Each step moves the parameters by the learning rate times the gradient. When the rate is too large the step overshoots the minimum by more than it started away from it, so each step lands farther away and the loss grows without bound, as in the right panel of Figure 1. When it is too small the parameters move toward the minimum but slowly, so after 50 steps the loss is still high. A small rate is safe only in the sense that it does not explode, so (a) is wrong, and (c) and (d) ignore what the table shows.Problem 2 (A Network Made of Kinks) A network with one input x, two ReLU hidden units and no output intercept computes \hat{y} = 2 \max(x - 1, 0) - 2 \max(x - 3, 0). Compute \hat{y} for x = 0, x = 2 and x = 5, and describe the shape of \hat{y} as a function of x.
Solution
At x = 0 both terms are zero, so \hat{y} = 0. At x = 2 the first term is 2 \times 1 = 2 and the second is zero, so \hat{y} = 2. At x = 5 the terms are 2 \times 4 = 8 and 2 \times 2 = 4, so \hat{y} = 4. The function is flat at zero up to x = 1, rises with slope 2 between 1 and 3, and stays flat at 4 beyond 3. Each hidden unit adds one kink: the first starts the rise, and the second, with a negative output weight, cancels the slope at 3.Problem 3 (Scores, Probabilities and the Loss) A classifier with three classes gives an image the scores s_1 = 2, s_2 = 1 and s_3 = 0. Use 8 to compute the three probabilities. Which class does the classifier choose? If the image belongs to class 2, what is its contribution -\ln p_{y} to the cross-entropy, and how would it change if s_2 rose to 3?