A neural networkA model that takes a set of input variables and builds a nonlinear function of them to predict the answer. sounds like a new kind of model, with neurons and layers and its own vocabulary.
Underneath, its pieces are ones this blog has already used. Each unit of a layer is the weighted
sum from linear regression, followed by one fixed function that
bends it. The network’s output is one more linear regressionA simple method that predicts a numeric answer by assuming a straight-line relationship between the inputs and the answer., fitted on those bent values. That
small step, the bend, is the whole difference between a network and a straight line, and this
post is about what it buys and what it costs.
The running example is the one from the linear regression post: predict next month’s volatilityHow much an asset's price spikes and dips; most often measured as the standard deviation of its per-period returns.
(how much a price will swing over the next 20 trading days, in % a year) for SPY, NVDA, GS, XOM
and GLD, from seven featuresAn input variable a model uses to make its prediction; also called a predictor or an independent variable. computed from prices up to today. Training uses 2020 to 2022, the
year 2023 is held out to choose settings, and 2024 to October 2025 is the test, used once at the
end. Every model is scored by its RMSEThe square root of the mean squared error. (root mean squared error, the typical size of a miss, in
the same points of % a year as the target; see Scoring a model).
One unit is a weighted sum, then a bend
ISLP builds a single-layer network in two steps (section 10.1). First, each of Khidden unitsOne unit inside a neural network: a weighted sum of its inputs, passed through an activation function. Its value is never observed in the data.
takes its own weighted sum of the p features and passes it through an activation functionA nonlinear function inside a neural network that is chosen in advance, not learned.,
“a nonlinear activation function that is specified in advance”:
h, what hidden unit k outputs
hk=g(wk0+wk1x1+⋯+wkpxp)
Here x1 to xp are the features of one row, wk1 to wkp are unit k‘s weights,
wk0 is its bias (a constant added to the sum, so the unit can shift where it bends), and
g is the activation. The modern default is the ReLUAn activation function that keeps a positive number and turns a negative one into zero. (rectified linear unit), which keeps a
positive number and turns a negative one into zero (ISLP equation 10.5):
g(z)=max(0,z)
Second, the output is a weighted sum of the hidden units’ values (ISLP equation 10.3), “a linear
regressionA prediction problem whose answer is a number; when the answer is a category it is classification instead. model in the K activations”:
ŷ, the network's prediction
y^=β0+β1h1+⋯+βKhK
So each hidden unit builds a new feature from the old ones, and the output layer is ordinary
linear regression on the new features. The difference from adding features by hand is that the
network learns how to build them: the w‘s are fitted together with the β‘s. Bishop and
Bishop describe the same design as basis functions that “themselves have learnable parameters”
(section 6.2). A network with more than one hidden layer feeds the first layer’s outputs into a
second layer of the same kind, and so on; that is the stacking in the title.
Without the bend, the stack is one straight line
Take the activation away and a network of any depth is linear regression with extra steps.
ISLP: “without it the model f(X) in (10.1) would collapse into a simple linear model in
X1,…,Xp” (section 10.1). The algebra is two lines. With g(z)=z, put each unit’s sum
into the output and collect the terms by feature:
The first bracket is one number, an interceptThe constant term in a linear model: together with the slope it is one of the model's coefficients.. The second is one number per feature, a slope. That
is the form of linear regression, whatever K is. Murphy shows the same for L layers: the
weight matrices multiply out to one matrix (PML1 equation 13.10), and Bishop and Bishop add that
“we can always find an equivalent network without hidden units” (section 6.2.3).
A small case shows both behaviours on the same weights. One input x, two hidden units with sums
2x+1 and −x+3, and an output that adds half of each. Table 1 runs four values of x
through it, once with no bend and once with ReLU.
Table 1. One input, two hidden units, output = half of each unit’s value, added
x
Unit 1: 2x+1
Unit 2: −x+3
Output, no bend
Output, ReLU
0
1
3
2.0
2.0
2
5
1
3.0
3.0
4
9
−1
4.0
4.5
6
13
−3
5.0
6.5
With no bend the output is 0.5x+2 at every x: one straight line, rising 0.5 per step of x.
With ReLU, unit 2 is switched off once its sum goes negative (above x=3), so from there the
output rises 1.0 per step instead of 0.5. The line has a kink at x=3. Many units, each with its
kink in a different place, can join up into a curve; Murphy notes that a network with one hidden
layer is a “universal function approximator”, able to model “any suitably smooth function, given
enough hidden units” (PML1 section 13.2.5). Being able to draw a
curve is not the same as finding the right one from a few thousand noisy rows, which is the rest of
this post.
Figure 1, panel 1, shows a bend on the real data, with one input, this month’s volatility, and a
network of 8 ReLU units. The network rises more steeply than the line up to about 43% and then
flattens. On the test years the line misses by 12.83 points and the network by 12.18. Both do
better than the seven-feature models in Tables 2 and 4: more inputs are not automatically better.
The real data says the same. Table 2 fits a network with two hidden layers of 32 units and no
bend (scikit-learn’s activation="identity") from five different random starting weights.
Table 2. Typical miss on next month’s volatility, test years 2024 to October 2025
Model
Typical miss, test (points)
Guess the training average every time
18.36
Linear regression, seven features
12.92
Network 32-32, no bend, five random starts
12.92 to 12.94
Guessing the training average misses next month’s volatility by 18.36 points of % a year on a
typical test day. Linear regression cuts that to 12.92. The network without a bend has
1,345 weights instead of 8, and lands on the same 12.92 to 12.94: the extra
weights only re-describe the same straight line.
Fitting: walk the weights downhill on the squared error
A network is fitted the same way for any number of layers: choose the weights that make the squared
error on the training rowsThe observed examples a method learns from: they are used to teach it how to make its estimate. small (ISLP equation 10.25, with all the weights collected in one list
θ):
R, the training error to make smally, the actual next-month volatilityŷ, the network's prediction
R(θ)=21∑i(yi−y^i)2
Linear regression has a formula for its best weights. A network does not: the bend makes this
error a bumpy surface with many low points (ISLP calls it “nonconvex”, section 10.7). So the fit is
gradient descentFitting by repeated small steps in the direction that lowers the error fastest, recomputing that direction after every step.: start from random weights, work out which way each weight should move to
lower the error (the gradient), take a small step that way, repeat (ISLP equation 10.27, ρ is
the step size, called the learning rateThe number that sets how big each update step is.):
θ←θ−ρ∇R(θ)
BackpropagationThe way a neural network's fitting works out, by the chain rule, how much each parameter contributed to the error. is how the gradient is computed: the chain rule of calculus, applied from the
output back to the first layer, so each weight gets its share of the miss (ISLP section 10.7.1). In
practice each step uses a small random batch of rows rather than all of them (stochastic gradient
descent, section 10.7.2); scikit-learn’s default batch is 200 rows, so one epochOne complete pass through the whole training set during fitting., a full pass
through the 3,680 training rows, is 19 steps.
Two things follow that linear regression never had. The answer depends on the random start: the
same network, fitted from five starts, gives five different models. And the fit has to be told
when to stop, because the training error can keep falling long after the model has stopped
learning anything that carries over to new days.
A network with room to spare learns the noise too
Figure 1, panel 2, fits a network with two hidden layers of 256 units each and a negligible weight
penalty, one epoch at a time, and scores it after every epoch on the training years and on the
validation year. The network has 68,097 weights and biases, for 3,680 training rows.
Figure 1. A bent line on one input, and training against validation error epoch by epoch
Table 3 reads off a few epochs.
Table 3. The 256-256 network, typical miss after each epoch (points)
Epoch
Training years, 2020 to 2022
Validation year, 2023
1
31.48
22.37
10
14.72
13.22
94
13.29
11.70
300
11.63
12.34
After epoch 94 the training error keeps falling, from 13.29 to 11.63, while the validation error
rises, from 11.70 to 12.34. From that point on, every step makes the model fit
2020 to 2022 better and 2023 worse: it is learning the particular days, not the pattern.
That is overfittingWhen a flexible model follows the noise in its training data too closely, so its predictions on new data are poor., and in a network it shows up over time, during a single fit, not only
across model sizes.
The training error ends below linear regression’s (11.63 against 14.98 on the same rows). That
number says how well the network remembers the training rows. Only the validation and test rows
say how well it predicts.
Three brakes: a weight penalty, stopping early, dropout
All three appear in the books as standard parts of fitting a network, not extras.
Weight penalty (ridgeLeast squares with a penalty that shrinks the coefficients towards zero; a tuning parameter sets how strong the shrinking is., or weight decayA penalty on the sum of squared weights, added to the training error, which pulls weights towards zero unless the data supports them.). Add λ∑jθj2 to the training
error, so large weights cost something (ISLP equation 10.31). Bishop and Bishop: it “encourages
weight values to decay towards zero, unless supported by the data”, and the size of λ
sets “the effective model complexity” (section 9.2).
Early stoppingStop training at the point where the error on validation data is lowest, before the model starts to overfit.. Watch the validation error and keep the weights from its lowest point,
epoch 94 in Table 3. Bishop and Bishop show it behaves like a weight penalty (section 9.3.1).
DropoutA form of regularisation for neural networks: while fitting, randomly remove a fraction of the units in a layer.. During training, switch off a random share of units for each row, so no unit can
rely on a particular partner (ISLP section 10.7.3, Murphy section 13.5.4). scikit-learn’s
network has no dropout; the post uses the first two.
Table 4 fits the 256-256 network at four penalty strengths, five random starts each. The strength
is scikit-learn’s alpha, which it divides by the number of rows before adding.
Table 4. The 256-256 ReLU network by penalty strength, mean of five random starts (points)
Penalty, alpha
Training years
Validation year
Test years
Test, range of five starts
0.0001 (almost none)
11.61
12.24
12.89
12.53 to 13.25
10
12.47
11.62
12.36
12.13 to 12.67
100
13.81
11.70
12.19
12.09 to 12.47
1000
14.96
12.25
12.97
12.88 to 13.00
Linear regression, for comparison
14.98
12.20
12.92
With almost no penalty the network fits the training years best (11.61) and tests no better than
linear regression on average (12.89 against 12.92), with a spread of 0.72 points between its best
and worst start. A heavy penalty (1000) takes back the freedom the bend gave: the training miss
rises to 14.96, linear regression’s level, and the test miss goes back to the line’s too. In between, the network
beats the line.
The validation year picks λ=10 (lowest validation miss, 11.62), and on the test years
that network misses by 12.36 on average, below linear regression’s 12.92 in all
five starts. The penalty of 100 would have tested slightly better (12.19), but choosing it would
mean choosing on the test years, and the test number would then no longer be a test.
The bend helps here, a little, and only with a brake. The penalised network cuts the typical
miss by 0.56 points, from 12.92 to 12.36. Linear regression had already cut it by 5.44 points
from guessing the average. The unpenalised network, with 68,097 weights, did not beat the line
at all.
When a network is the wrong tool
ISLP asks this directly (section 10.6). On a table of 263 baseball players and 19 features, a
network with 1,345 parameters scored a test R2 of 0.54 against linear regression’s 0.56, after
“a fair bit of time fiddling with the configuration parameters”. Their conclusion is the rule
“when faced with several methods that give roughly equivalent performance, pick the simplest”, and
they expect deep learningThe branch of machine learning built on neural networks. to be “an attractive choice when the sample size of the training set is
extremely large, and when interpretability of the model is not a high priority”.
The volatility data sits near that line. It is tabular (seven numbers per row, each with its own
meaning), and the training set is 3,680 rows. Those rows are fewer than they look: six of the
seven features, and the target, are computed over windows of several days, so neighbouring days
share most of their data. The network won by 0.56 points; to get there it needed a validation
year, a search over four penalties and five random starts each, twenty fits to choose one. The
linear model’s eight numbers can be read off one by one; the network’s 68,097 cannot.
Try the line first, and let the network earn its place on held-out data. Networks have had
their big successes where the input has a structure, such as pixels next to each other or words in
order (ISLP section 10.6), with designs built for that structure (Murphy, PML1 section 13.1). A
table of features is not that case.
And a smaller miss on volatility is a better forecast, not a better trade:
the network minimises squared error, which is not what a portfolio is paid for.
Check yourself
A network has three hidden layers of 100 units each and no activation function. What can it represent that linear regression on the same features cannot?
Nothing. Without the bend, each layer’s output is a weighted sum of the one before, and weighted
sums of weighted sums multiply out to one intercept and one slope per feature. On the volatility
data a 32-32 network without a bend scored 12.92 to 12.94 against linear regression’s 12.92.
The 256-256 network's training error keeps falling after epoch 94. Why stop there?
Because the validation error was lowest there, 11.70, and rose to 12.34 by epoch 300. From epoch 94
the network was fitting the particular days of 2020 to 2022 rather than a pattern that carried over
to 2023. Early stopping keeps the weights from the validation minimum.
A penalty of 100 tested better than the chosen 10 (12.19 against 12.36). Why report 12.36?
The penalty was chosen on the validation year, where 10 was best. Picking 100 because it tested
better would use the test years to make a choice, and then the test number would no longer measure
how the model does on data it has not influenced.
Traps
Table 5. Common mistakes with neural networks
People think
Actually
More layers make a more powerful model
only with an activation between them; without it, any depth is one linear regression
A lower training error means a better network
the unpenalised 256-256 network had the lowest training error and tested no better than the line
One fit shows how good the network is
five random starts of the same network tested 0.72 points apart
Networks always beat linear models
on this table of features the gain was 0.56 points, and only with a penalty chosen on held-out data
The test set can choose the settings
then it is a second validation set, and the reported score is optimistic
The code
The snippet fits linear regression, a network without a bend and a ReLU network on three of the
features, for all five tickers. It is shorter than the post’s script: it trains on 2020 to 2023 with
no validation year and a fixed penalty, so its numbers are close to, not equal to, the tables.
Table 6. What the snippet’s variables hold
Variable
Holds
px
adjusted closes, one column per ticker
r
daily returns, one column per ticker
X
three features per ticker and day: 5- and 20-day volatility (% a year) and the 20-day return
y
the target: the volatility of the next 20 daily returns (% a year)
train, test
rows before 2024, and rows from 2024 on
import numpy as npimport pandas as pdfrom sklearn.linear_model import LinearRegressionfrom sklearn.neural_network import MLPRegressorfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScalerurl = "https://raw.githubusercontent.com/ankurtrapasiya/examples/main/data/prices.csv"px = pd.read_csv(url, index_col="date", parse_dates=True)r = px.pct_change()A = np.sqrt(252) * 100 # daily standard deviation -> % a yearrows = []for t in px.columns: # one row per ticker and day rows.append(pd.DataFrame({ "vol_5d": r[t].rolling(5).std() * A, "vol_20d": r[t].rolling(20).std() * A, "ret_20d": px[t] / px[t].shift(20) - 1, # target: the standard deviation of the NEXT 20 daily returns "next_vol": r[t][::-1].rolling(20).std()[::-1].shift(-1) * A, }).dropna())df = pd.concat(rows)X, y = df[["vol_5d", "vol_20d", "ret_20d"]], df["next_vol"]train, test = df.index < "2024-01-01", df.index >= "2024-01-01"def net(activation): # scale the features first: a network's gradient steps assume inputs of similar size return make_pipeline(StandardScaler(), MLPRegressor(hidden_layer_sizes=(256, 256), activation=activation, alpha=10, max_iter=500, random_state=0))models = {"linear regression": LinearRegression(), "network, no bend": net("identity"), "network, ReLU": net("relu")}for name, m in models.items(): m.fit(X[train], y[train]) miss = np.sqrt(np.mean((y[test] - m.predict(X[test])) ** 2)) print(f"{name:<18} typical miss on 2024-25: {miss:.2f} points")
It prints a typical test miss of 12.79 for linear regression, 12.76 for the network without a
bend, and 12.00 for the ReLU network: the same pattern as Tables 2 and 4. Change random_state=0
to another number and the ReLU line moves; the other two barely do.
ReLU keeps a positive sum and sets a negative one to 0
The output layer
linear regression on the hidden units’ values
the network builds its own features and fits a line on them
No bend, no gain
stacked weighted sums multiply out to one
32-32 with no bend: 12.92 to 12.94, the line: 12.92
Fitting
gradient descent on squared error, from a random start
five starts of one network tested 0.72 points apart
Overfitting over time
training error falls while validation error turns up
validation lowest at epoch 94, then 11.70 to 12.34
Brakes
weight penalty, early stopping, dropout
penalty 10, chosen on 2023: 12.36 against the line’s 12.92
Wrong tool
small tables of features rarely repay a network
a 0.56-point gain for 68,097 weights instead of 8
References
James, Witten, Hastie, Tibshirani and Taylor, An Introduction to Statistical Learning, with Applications in Python (Springer, 2023), chapter 10: the single-layer network and its activations (section 10.1, equations 10.1 to 10.5), the collapse without a nonlinearity (section 10.1), when to use deep learning and the baseball comparison (section 10.6, Table 10.2), fitting by gradient descent and backpropagation (sections 10.7 and 10.7.1, equations 10.25 and 10.27), minibatches, the ridge penalty and early stopping (section 10.7.2, equation 10.31), dropout (section 10.7.3)
Christopher M. Bishop and Hugh Bishop, Deep Learning: Foundations and Concepts (Springer, 2024): hidden units as learnable basis functions (section 6.2), the equivalent network without hidden units when activations are linear (section 6.2.3), weight decay (section 9.2), early stopping (section 9.3.1)
Kevin P. Murphy, Probabilistic Machine Learning: An Introduction (MIT Press, 2022), chapter 13: tabular data against unstructured data (section 13.1), linear activations reducing to a linear model (section 13.2.3, equation 13.10), the universal approximator (section 13.2.5), early stopping, weight decay and dropout (sections 13.5.1, 13.5.2, 13.5.4)
scikit-learn, MLPRegressor: the alpha penalty divided by the number of rows, and the default batch of 200 rows