Skip to main content

From Regression to Neural Networks

Published

November 23, 2026

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.

Two panels showing a U-shaped loss curve as a function of the slope. In the left panel, dots for successive steps move steadily down toward the bottom. In the right panel, the dots jump from side to side and climb up the curve.
Figure 1: Gradient descent on the loss of a regression slope. With a small learning rate the steps approach the minimum steadily; with a learning rate that is too large they overshoot and move away from it.

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.

Two diagrams. On the left, linear regression: one input circle x with a single arrow labeled beta one pointing to the output circle y hat. On the right, a neural network: two input circles, x one and x two, each with arrows to four hidden-unit circles in a middle column, each hidden circle containing a small kinked ReLU line. Every hidden circle has an arrow to the output circle y hat. The arrow from x one to the first hidden unit is labeled w one one, and the arrows from the first and last hidden units to the output are labeled beta one and beta m.
Figure 2: Linear regression and a neural network drawn as graphs. Each circle is a number and each arrow multiplies the number at its tail by a weight. Values arriving at a circle are added up, and in a hidden unit the sum then passes through the ReLU activation, drawn as a kink. Intercepts are not drawn.

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.

Three input circles, x one to x three, with arrows labeled w j one to w j three pointing to a circle marked with a summation sign, which also receives an arrow labeled w j zero from above. Below it reads z equals w j zero plus w j transpose x. An arrow leads to a box showing the ReLU function, flat at zero for negative z and rising for positive z, labeled g of z equals max of z and zero. An arrow labeled beta j leads from the box to the output circle y hat.
Figure 3: Inside hidden unit j. The unit adds its intercept to a weighted sum of the inputs, applies the ReLU activation, and sends the result to the output with weight \beta_j.

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.

Scatter of noisy points that follow a wave, falling to a trough near x equals minus 0.8, rising to a peak near 0.8 and falling again. A straight regression line cuts through the points. A curve from the neural network follows the trough and the peak.
Figure 4: A linear regression and a small neural network fitted to the same noisy data, generated from the wave \sin(2x). The network bends with the data; the line cannot.

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.

Two panels against x. The left panel shows several kinked lines, each zero on one side of a dot marking its kink and straight on the other side, some sloping up and some down. The right panel shows the gray data points and the network's fitted wave, built by adding up the lines on the left.
Figure 5: The network of Figure 4 taken apart. Left: the contribution \beta_j \max(w_{j0} + w_{j1} x, 0) of each hidden unit, with a dot at its kink. Right: the intercept plus the sum of the pieces is the fitted curve.

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.

Four columns of circles connected left to right by arrows. Two input circles, x one and x two, connect to each of four circles in the first hidden layer. Each of those connects to each of three circles in the second hidden layer, and those three connect to the output circle y hat. Every hidden circle contains a small kinked ReLU line. Above the gaps between columns are the labels W one, W two and beta.
Figure 6: A network with two hidden layers. Every unit of the first hidden layer feeds every unit of the second, and the second layer feeds the output. The matrices \mathbf{W}^{(1)} and \mathbf{W}^{(2)} hold the weights on the arrows into each hidden layer, and \pmb{\beta} the weights into the output. Intercepts are not drawn.

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.

Baydin, Atılım Güneş, Barak A. Pearlmutter, Alexey Andreyevich Radul, and Jeffrey Mark Siskind. 2018. “Automatic Differentiation in Machine Learning: A Survey.” Journal of Machine Learning Research 18 (153): 1–43.
Linnainmaa, Seppo. 1976. “Taylor Expansion of the Accumulated Rounding Error.” BIT Numerical Mathematics 16 (2): 146–60.
Rumelhart, David E., Geoffrey E. Hinton, and Ronald J. Williams. 1986. “Learning Representations by Back-Propagating Errors.” Nature 323 (6088): 533–36.
Goodfellow, Ian, Yoshua Bengio, and Aaron Courville. 2016. Deep Learning. MIT Press. https://www.deeplearningbook.org.

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.

Sixteen handwritten digits in two rows, each with its label above it, varying in slant, thickness and shape.
Figure 7: Handwritten digits from the MNIST database, with their labels. Each image has 28 \times 28 pixels, each a number from 0 (white) to 255 (black).

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.

LeCun, Yann, Léon Bottou, Yoshua Bengio, and Patrick Haffner. 1998. “Gradient-Based Learning Applied to Document Recognition.” Proceedings of the IEEE 86 (11): 2278–324. https://doi.org/10.1109/5.726791.

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.
Two curves of mean squared error against training epochs on a log scale. The training curve falls steadily toward zero. The validation curve falls at first, reaches a minimum, and then rises.
Figure 8: Training and validation loss of a large network trained on 60 noisy observations. The training loss keeps falling; the validation loss falls, then rises as the network starts to fit noise.

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?

  1. The learning rate of 0.001 is best, because small steps are always safer.
  2. 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.
  3. The learning rate does not matter, because gradient descent always finds the minimum.
  4. 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?

Solution The exponentials are e^2 = 7.39, e^1 = 2.72 and e^0 = 1, which add up to 11.11, so p_1 = 0.665, p_2 = 0.245 and p_3 = 0.090. The classifier chooses class 1, the highest score. If the image belongs to class 2, its loss is -\ln 0.245 = 1.41. With s_2 = 3 the exponentials are 7.39, 20.09 and 1, adding up to 28.47, so p_2 = 0.705, the classifier now chooses class 2, and the loss falls to -\ln 0.705 = 0.35. Training lowers the loss by raising the score of the correct class relative to the others.