How a small neural network learns a curve from x/y data: neurons, layers, activation functions, loss, gradient descent, backpropagation, epochs and the seed.

Contents
  1. The Map of Machine Learning
  2. What Is Machine Learning? A Curve Learned from Examples
  3. The Parts of a Network
    1. Neuron
    2. Layer
    3. Activation Function
  4. How It Learns
    1. Loss: Mean Squared Error
    2. Gradient Descent and the Learning Rate
    3. Backpropagation
    4. Epoch
  5. Which Settings Should You Pick?
  6. Key Ideas
    1. Random Start and the Seed
    2. Input Scaling
    3. Underfitting and Overfitting
    4. A Network Is Not a Formula
  7. Example: A Noisy Sine, Learned Epoch by Epoch
  8. REFs

The Map of Machine Learning

Machine learning is not one method but a family: each member learns a rule from data instead of being given one. One useful way to divide this family is to ask a simple question: what information does the data provide to the learner? Fig 1 shows the five branches, with the three topics covered in this series highlighted in blue.

A tree: machine learning at the top, five branches below it - supervised, unsupervised, semi-supervised, reinforcement, self-supervised. Under supervised, regression (Part 1, this page, highlighted) and classification (Part 2); under unsupervised, clustering (Part 3)

Fig 1. The five branches of machine learning and the three parts of this series

This series covers three tasks from Fig 1 that work with numerical data arranged in columns, like the data in a spreadsheet:

The rest of this article is Part 1.

What Is Machine Learning? A Curve Learned from Examples

Usually, a curve comes from a formula: write $y = \sin x$, and every value follows. Machine learning (ML) works the other way around. It starts from examples, pairs of $x$ and $y$, and adjusts a flexible model until the model reproduces them. Nobody writes the formula; the model learns the shape from the data. When the output is a number, as here, the task is called regression.

This article uses the simplest flexible model there is: a small neural network with one input $x$, one hidden layer of neurons, and one output $\hat y$. Each part does very little. The learning comes from repeating one small correction many times, which is what the calculators let you watch.

Consider three datasets, each sampled at 41 points from $x$ = 0 to 10 in steps of 0.25. Table 1 lists ten of the rows; Chart 1 and Chart 2 show all of them.

$x$00.250.512357910
$y_1$0.00000.24740.47940.84150.90930.1411โˆ’0.95890.65700.4121โˆ’0.5440
$y_2$0.00010.27730.45200.79600.86010.1517โˆ’1.14310.65210.4089โˆ’0.5330
$y_3$54.754.54320245

Table 1. Ten of the 41 rows of the example

y1 in blue and y2 in red as dots at every sample from x = 0 to 10: one and a half sine cycles between โˆ’1 and 1, the red dots scattered around the blue

Chart 1. $y_1$ and $y_2$ of Table 1 at all 41 samples

y3 as green dots from x = 0 to 10, falling in a straight line from 5 to 0 at x = 5, then rising back to 5

Chart 2. $y_3$ of Table 1 at all 41 samples

Chart 3 shows the result of the learning process. The black dots represent $y_2$ from Chart 1, which is the only data given to the network. With the calculator's default settings, 8 neurons and 2,000 passes through the data, the purple curve already follows the dips, but it misses the first peak. After 20,000 passes, the blue curve follows the whole sine: its RMS distance from the true $\sin x$ is 0.0556, closer than the noisy data itself (0.0891).

The y2 samples as black dots from x = 0 to 10; a purple curve after 2,000 epochs that follows the data except near the first peak; a blue curve after 20,000 epochs that follows the whole sine

Chart 3. $y_2$ of Chart 1 and the curve a network learned from it, after 2,000 and 20,000 epochs

Every later chart uses the same $y_1$, $y_2$ and $y_3$. The rest of this article looks inside the network: what its parts are and how repeated small adjustments produce the result shown in Chart 3.

The Parts of a Network

A network is built from a simple unit called a neuron, repeated many times and arranged in layers. Each neuron bends its input through an activation function. The sections below take the three parts in that order.

Neuron

In plain words. A neuron takes a number, multiplies it by a weight, adds a bias, and passes the result through an activation function. That is all it does. With tanh or sigmoid, a single neuron produces an S-shaped curve. The weight controls its steepness, while the bias shifts its position.

Control parameters. None directly: the weights and biases are what training changes. seed sets their starting values (Random Start and the Seed).

Basic idea. With input $z$ (the input $x$ after scaling, Input Scaling), weight $w$, bias $b$ and activation $\varphi$, the neuron first forms its pre-activation $a$, then its output $h$ (Math 1):

$$a = w z + b, \qquad h = \varphi(a)$$

Math 1.

Three tanh curves against input z from โˆ’3 to 3: blue w = 1, b = 0, a gentle S through zero; red w = 3, b = 0, a steep S through zero; green w = 3, b = โˆ’3, the same steep S moved right to z = 1

Chart 4. One neuron (Math 1) with $\varphi = \tanh$, for three weights and biases

Advantages

Disadvantages

Layer

In plain words. A hidden layer is a row of neurons that all receive the same input. The output layer then adds their outputs, each multiplied by its own weight, plus one more bias. Each hidden neuron contributes a curve, and adding several appropriately shaped curves can approximate a wide range of continuous functions.

Control parameters. hidden, the number of neurons in the hidden layer: 2, 4, 8 (default) or 16 on the basic calculator. The advanced calculator allows 1 to 3 hidden layers of up to 64 neurons each.

Basic idea. Fig 2 shows the calculator's default network: one input, 8 hidden neurons with tanh, and a linear output. With hidden weights $w_j$, biases $b_j$, output weights $v_j$ and output bias $c$, the network computes (Math 2):

A network diagram: the input x on the left, eight hidden neurons h1 to h8 in a column, the output ลท on the right; blue lines from x to each neuron labeled weights wj, biases bj, red lines from each neuron to ลท labeled weights vj, bias c

Fig 2. The default network: 1 input, 8 tanh neurons, 1 linear output

$$\hat y = \sum_{j=1}^{8} v_j \tanh(w_j z + b_j) + c = v_1 h_1 + v_2 h_2 + \dots + v_8 h_8 + c$$
$$\begin{aligned} \hat y &= \sum_{j=1}^{8} v_j \tanh(w_j z + b_j) + c \\ &= v_1 h_1 + v_2 h_2 + \dots + v_8 h_8 + c \end{aligned}$$

Math 2.

From x = 0 to 10: y2 as a thin gray line; eight thin dashed S-shaped curves in viridis colours, flat or stepping up or down between about โˆ’2 and +2; a bold red curve, their sum plus an offset, lying on the gray data

Chart 5. The eight neuron terms of Math 2 (dashed) and their sum (red), the network of Chart 3 trained 20,000 epochs on $y_2$

How the sum approaches the target. Chart 6 trains networks of 1, 2, 3 and 4 tanh neurons on $y_1$ of Chart 1, the sine without noise, for 20,000 epochs each. In the top panel, a single neuron draws one S-shaped step. It follows the first fall of the sine and then stays flat, with an RMS error of 0.59. In the bottom panel, each added neuron contributes one more step, and the curve moves closer to the dots: the RMS error falls to 0.33 with 2 neurons, 0.17 with 3 and 0.06 with 4. With 2 neurons, the curve forms the dip near $x$ = 4.7; with 3, it also follows the second peak; with 4, it rises from $x$ = 0 to the first peak as well. Where the curves coincide, each earlier curve is drawn as a wider band underneath the later one, so all four remain visible.

Two charts of y1 = sin x as black dots from x = 0 to 10. Top: one neuron, a light green S-shaped step from 0.7 down to 0 near x = 3, flat after it. Bottom: the same step with 2, 3 and 4 neurons drawn as nested bands, wide light green to thin dark purple; 2 neurons add the dip, 3 the second peak, and the thin 4-neuron curve follows the whole sine

Chart 6. Networks of 1 to 4 tanh neurons, each trained 20,000 epochs on $y_1$: one neuron (top), then 1, 2, 3 and 4 neurons together (bottom)

More than one hidden layer. The advanced calculator can stack 2 or 3 hidden layers. The rule for counting weights stays the same: a neuron has one weight for each value that feeds into it. A neuron in layer 1 receives only the scaled input $z$, so it has one weight $w_j$, as in Math 2. A neuron in layer 2 receives the outputs of every neuron in layer 1, so it has one weight for each of them. In Fig 3, each neuron in layer 2 therefore has 4 weights, drawn as the 16 green lines between the layers (Math 3):

A network diagram with two hidden layers: the input x on the left; four neurons h1.1 to h1.4, each joined to x by one blue line; four neurons h2.1 to h2.4, each joined to all four layer-1 neurons by green lines, 16 in all; the output ลท on the right, joined to the four layer-2 neurons by red lines

Fig 3. Two hidden layers of 4: one weight per layer-1 neuron, four per layer-2 neuron

$$\begin{gathered} h^{(1)}_j = \tanh\!\big(w^{(1)}_j z + b^{(1)}_j\big), \qquad h^{(k)}_j = \tanh\!\Big(\sum_{i=1}^{n} w^{(k)}_{ji}\, h^{(k-1)}_i + b^{(k)}_j\Big) \\ \hat y = \sum_{j=1}^{n} v_j h^{(K)}_j + c \end{gathered}$$
$$\begin{aligned} h^{(1)}_j &= \tanh\!\big(w^{(1)}_j z + b^{(1)}_j\big) \\ h^{(k)}_j &= \tanh\!\Big(\sum_{i=1}^{n} w^{(k)}_{ji}\, h^{(k-1)}_i + b^{(k)}_j\Big) \\ \hat y &= \sum_{j=1}^{n} v_j h^{(K)}_j + c \end{aligned}$$

Math 3.

Advantages

Disadvantages

Activation Function

In plain words. The activation function is the bend inside every hidden neuron. Without it, each neuron would be a straight line, and a sum of straight lines is still a straight line. tanh and sigmoid bend smoothly into S shapes; ReLU bends sharply, at one corner.

Control parameters. activation = tanh (default), relu or sigmoid, the same for every hidden neuron. The output neuron has no activation: it is linear, so $\hat y$ can take any value.

Basic idea. The three functions, of the pre-activation $a$ of Math 1 (Math 4):

$$\tanh a = \frac{e^{a} - e^{-a}}{e^{a} + e^{-a}}, \qquad \operatorname{ReLU}(a) = \max(0, a), \qquad \sigma(a) = \frac{1}{1 + e^{-a}}$$
$$\begin{aligned} \tanh a &= \frac{e^{a} - e^{-a}}{e^{a} + e^{-a}} \\ \operatorname{ReLU}(a) &= \max(0, a) \\ \sigma(a) &= \frac{1}{1 + e^{-a}} \end{aligned}$$

Math 4.

Three functions of a from โˆ’4 to 4: blue tanh, an S from โˆ’1 to 1 through zero; red sigmoid, an S from 0 to 1 through 0.5; green ReLU, flat at zero then a straight line rising to 4

Chart 7. The three activation functions of Math 4

With and without an activation. Chart 8 repeats the networks of Chart 6 without the bend. Without an activation function, each neuron computes $w z + b$, a straight line, and the output adds straight lines, so the network can only draw a single straight line, whatever the number of neurons. Trained on $y_1$, this line has an RMS error of 0.66 with 1 neuron and with 4 neurons (green). With tanh, the same networks reach 0.59 with 1 neuron (top) and 0.06 with 4 neurons (bottom, purple).

Two charts of y1 = sin x as black dots from x = 0 to 10, each with a green, nearly flat straight line sloping slightly down from 0.27 to 0.08, the network without an activation. Top: one tanh neuron, a dark purple S-shaped step. Bottom: four tanh neurons, a dark purple curve that follows the whole sine

Chart 8. One neuron (top) and four neurons (bottom), each trained 20,000 epochs on $y_1$: without an activation (green) and with tanh (purple)

Advantages

Disadvantages

How It Learns

Training repeats four steps: compute the predictions, measure how wrong they are (the loss), work out how each weight affects that error (backpropagation), and move every weight a little in the direction that reduces it (gradient descent). One pass through the data is an epoch. The sections below follow these steps with a hand-sized example first.

Loss: Mean Squared Error

In plain words. The loss is one number that says how far the predictions are from the data. Square each error, so that misses above and below both count, and take the average: the mean squared error (MSE). The goal of training is to make this number as small as possible.

Control parameters. None: the calculators always use MSE. It is computed on scaled values (Input Scaling), so a loss of 1 means "no better than predicting the average", and 0 means a perfect fit.

Basic idea. For $N$ rows with predictions $\hat y_i$ (Math 5):

$$L = \frac{1}{N} \sum_{i=1}^{N} (\hat y_i - y_i)^2 = \frac{1}{N}\Big[(\hat y_1 - y_1)^2 + (\hat y_2 - y_2)^2 + \dots + (\hat y_N - y_N)^2\Big]$$
$$\begin{aligned} L &= \frac{1}{N} \sum_{i=1}^{N} (\hat y_i - y_i)^2 \\ &= \frac{1}{N}\Big[(\hat y_1 - y_1)^2 + \dots \\ &\qquad + (\hat y_N - y_N)^2\Big] \end{aligned}$$

Math 5.

$x$$y$$\hat y = 0.5x$error $\hat y - y$squared
010โˆ’11
130.5โˆ’2.56.25
241โˆ’39
mean5.4167

Table 2. Three points and one linear neuron, $w$ = 0.5, $b$ = 0: the loss of Math 5

Three black points at (0, 1), (1, 3) and (2, 4); a red line ลท = 0.5x below them with dashed red error segments up to each point, loss 5.4167; a blue line after one update, closer to the points, loss 1.5419

Chart 9. The three points of Table 2: the starting line (red) and the line after one update of Math 6 (blue)

Advantages

Disadvantages

Gradient Descent and the Learning Rate

In plain words. The loss depends on every weight. For each weight, we ask: if its value increases slightly, does the loss increase or decrease, and by how much? That slope is the gradient. Gradient descent moves every weight a small step against its gradient, downhill. The learning rate sets how big that step is.

Control parameters. learning_rate ($\eta$ below), 0.05 by default. On the advanced calculator, optimizer = gd (plain gradient descent, as here), sgd or adam (Epoch).

Basic idea. Every weight $\theta$ is updated by Math 6, first line. For the linear neuron of Table 2, the gradients of Math 5 are the second and third lines:

$$\begin{aligned} \theta &\leftarrow \theta - \eta\,\frac{\partial L}{\partial \theta} \\ \frac{\partial L}{\partial w} &= \frac{2}{N} \sum_{i=1}^{N} (\hat y_i - y_i)\,x_i = \frac{2}{N}\big[(\hat y_1 - y_1)x_1 + \dots + (\hat y_N - y_N)x_N\big] \\ \frac{\partial L}{\partial b} &= \frac{2}{N} \sum_{i=1}^{N} (\hat y_i - y_i) = \frac{2}{N}\big[(\hat y_1 - y_1) + \dots + (\hat y_N - y_N)\big] \end{aligned}$$
$$\begin{aligned} \theta &\leftarrow \theta - \eta\,\frac{\partial L}{\partial \theta} \\ \frac{\partial L}{\partial w} &= \frac{2}{N} \sum_{i=1}^{N} (\hat y_i - y_i)\,x_i \\ &= \frac{2}{N}\big[(\hat y_1 - y_1)x_1 + \dots \\ &\qquad + (\hat y_N - y_N)x_N\big] \\ \frac{\partial L}{\partial b} &= \frac{2}{N} \sum_{i=1}^{N} (\hat y_i - y_i) \\ &= \frac{2}{N}\big[(\hat y_1 - y_1) + \dots \\ &\qquad + (\hat y_N - y_N)\big] \end{aligned}$$

Math 6.

Loss on a log scale against epoch from 0 to 2,000, three lines: green learning rate 0.005 falling slowly to about 0.46; blue 0.05 falling steadily to about 0.056; red 0.5 falling fast at first, then jumping up and down and ending near 0.74

Chart 10. The default network on $y_2$: loss against epoch for three learning rates $\eta$ of Math 6

Advantages

Disadvantages

Backpropagation

In plain words. Math 6 requires the gradient of the loss with respect to every weight, including the hidden-layer weights, which affect the loss indirectly through the subsequent neurons. Backpropagation computes all of these gradients in one backward pass. It starts at the loss and works backwards through the network, multiplying the local derivatives at each step. This is the chain rule of calculus applied sequentially.

Control parameters. None: it is the method by which the gradient is computed, not a setting.

Basic idea. For one row of the network in Math 2, Math 7 first lists the forward values: the pre-activation $a_j$, the activation $h_j$ and the slope of the loss at the output $\delta$. The gradients follow from them:

$$\begin{aligned} &a_j = w_j z + b_j, \qquad h_j = \tanh(a_j), \qquad \delta = \frac{2(\hat y - y)}{N} \\[0.9em] &\frac{\partial L}{\partial c} = \delta, \qquad \frac{\partial L}{\partial v_j} = \delta\,h_j, \qquad \frac{\partial L}{\partial b_j} = \delta\,v_j\,(1 - h_j^2), \qquad \frac{\partial L}{\partial w_j} = \delta\,v_j\,(1 - h_j^2)\,z \end{aligned}$$
$$\begin{aligned} a_j &= w_j z + b_j \\ h_j &= \tanh(a_j) \\ \delta &= \frac{2(\hat y - y)}{N} \\[0.9em] \frac{\partial L}{\partial c} &= \delta, \qquad \frac{\partial L}{\partial v_j} = \delta\,h_j \\ \frac{\partial L}{\partial b_j} &= \delta\,v_j\,(1 - h_j^2) \\ \frac{\partial L}{\partial w_j} &= \delta\,v_j\,(1 - h_j^2)\,z \end{aligned}$$

Math 7.

Five boxes in a row: z, a = wz + b, h = tanh a, ลท = vh + c, L; black arrows forward from left to right; red arrows backward from right to left, labeled 2(ลท โˆ’ y), ยท v, ยท (1 โˆ’ hยฒ) and ยท z

Fig 4. One neuron: the forward pass (black) and the backward pass of Math 7 (red)

Advantages

Disadvantages

Epoch

In plain words. An epoch is one pass through all the training rows. Plain gradient descent makes one update per epoch, using every row at once. Training consists of many successive epochs, each making small adjustments to the weights in the direction that reduces the loss.

Control parameters. epochs, 2,000 by default, at most 20,000 on the basic calculator. On the advanced calculator, batch_size ($B$ below) splits each epoch into mini-batches for sgd and adam; gd always uses all rows.

Basic idea. With $N_{\text{train}}$ training rows and mini-batches of $B$ rows, the number of updates in one epoch is (Math 8):

$$\text{updates per epoch} = \left\lceil \frac{N_{\text{train}}}{B} \right\rceil$$

Math 8.

Training loss on a log scale against epoch on a log scale from 1 to 20,000: a blue line starting near 2, flat near 1 until about epoch 100, then falling to 0.21 at 500 and 0.056 at 2,000, then flattening at 0.011; red dots at epochs 100, 500, 2,000 and 20,000

Chart 11. The default network on $y_2$: training loss (Math 5) over 20,000 epochs

Advantages

Disadvantages

Which Settings Should You Pick?

Table 3 uses the default settings as a starting point and changes one setting at a time. Each row shows the results of training the network on $y_2$ (the noisy sine) and $y_3$ (the V shape) from Charts 1 and 2. The table lists the final training loss (scaled, as defined in Math 5). Chart 12 shows the same numbers as bars on a log scale.

setting$y_2$ loss$y_3$ losswhat it changes
default: 8 neurons, tanh, $\eta$ 0.05, 2,000 epochs0.05630.0112a reasonable start
2 neurons0.23860.0136too few steps for a sine
16 neurons0.05890.0104more steps, not faster
ReLU0.24600.000031corners and straight pieces
sigmoid0.31320.0147highest loss of the three
learning rate 0.0050.45680.0226steps too small
learning rate 0.50.73740.1123steps too large, overshoots
20,000 epochs0.01090.00096more time, better fit

Table 3. One setting changed at a time: final training loss on $y_2$ and $y_3$

Bars on a log scale for the eight rows of Table 3, red for y2 and green for y3: the green ReLU bar is far lower than all others, near 3e-5; the 20,000-epoch bars are the lowest of the rest; the learning rate 0.5 bars are the highest

Chart 12. Table 3 as bars

Start with the defaults. If the target curve has sharp corners or straight segments, try ReLU. If the loss is still decreasing at the final epoch (Chart 11), try training for more epochs before increasing the number of neurons. If the loss jumps up and down, lower the learning rate; if it falls very slowly, raise it carefully.

Key Ideas

Random Start and the Seed

Training must start from some weights. If all weights started at zero, every hidden neuron would produce the same output and receive the same update. They would therefore remain identical throughout training. The weights therefore start at small random values, and the seed is the number that fixes those random values. With the same seed, settings and data, a deterministic implementation repeats the same run. The calculators use a seeded random-number generator, so a run is reproduced exactly in the same browser. Another browser or the server may produce slightly different results in the last few digits.

Chart 13 trains the default network on $y_2$ from Chart 1 four times, with seeds 1 to 4. The four curves almost overlap in the middle, where the data provides the strongest constraints. They differ most at the left end, where the curve produced with seed 4 remains flat. Their losses after 2,000 epochs range from 0.0563 to 0.0816. Gradient descent follows the local gradient from its starting point. Consequently, different starting points can lead to different results. To compare two settings fairly, keep the seed fixed; to see how much the start matters, change only the seed.

y2 as black dots from x = 0 to 10 and four curves for seeds 1 to 4 in blue, red, green and purple: almost on top of each other except near the left end, where the purple seed 4 curve stays flat

Chart 13. The default network on $y_2$ with four seeds: same settings, different random starts

Input Scaling

A tanh neuron has its greatest rate of change for inputs near zero (Chart 4). In this example, the raw $x$ values range from 0 to 10. Without scaling, many neurons would receive inputs far from zero, where the tanh function is relatively flat. The calculators therefore standardize each column before training by subtracting its mean $\bar x$ and dividing by its standard deviation $s_x$ (Math 9). The same procedure is applied to $y$, and the predictions are then converted back to the original units.

$$z_i = \frac{x_i - \bar x}{s_x}, \qquad s_x = \sqrt{\frac{1}{N} \sum_{i=1}^{N} (x_i - \bar x)^2} = \sqrt{\frac{(x_1 - \bar x)^2 + \dots + (x_N - \bar x)^2}{N}}$$
$$\begin{aligned} z_i &= \frac{x_i - \bar x}{s_x} \\ s_x &= \sqrt{\frac{1}{N} \sum_{i=1}^{N} (x_i - \bar x)^2} \\ &= \sqrt{\frac{(x_1 - \bar x)^2 + \dots + (x_N - \bar x)^2}{N}} \end{aligned}$$

Math 9.

On the 41 values of $x$ in Table 1, Math 9 maps the range 0 to 10 onto โˆ’1.69 to 1.69:

$$\begin{aligned} &\bar x = 5, \qquad s_x = 2.9580 \\[0.9em] &x = 0: \ z = \frac{0 - 5}{2.9580} = -1.6903 \\[0.9em] &x = 10: \ z = \frac{10 - 5}{2.9580} = 1.6903 \end{aligned}$$

Chart 14 trains the default network on $y_2$ twice, once with standardized $x$ and $y$ and once on the raw values, and compares both losses on the same scale (the raw loss divided by the variance of $y_2$). After 2,000 epochs, the standardized run reaches 0.056; the raw run reaches only 0.32, and its loss jumps around epoch 520. Both runs use the same network and seed; only the scale of the input and output values differs. The weights shown by the calculators are in these scaled units. When some rows are held out for validation or testing, the mean and standard deviation should be calculated using only the training rows. These values should then be applied unchanged to the held-out rows to prevent information from the validation or test data from leaking into training.

Loss on a log scale against epoch from 0 to 2,000: blue, standardized, falling to about 0.056; red, raw x and y, starting very high, falling slowly with a spike near epoch 520 and ending near 0.32

Chart 14. The default network on $y_2$: loss with standardized values (Math 9) and with raw values

Underfitting and Overfitting

A network that is too simple cannot capture the shape of the curve; this is called underfitting. A sufficiently flexible network, when trained for long enough, can fit both the underlying curve and the noise. This is called overfitting. The training loss measures how well the network fits the training rows; the validation loss, on rows held out of training, estimates how well it does on data it has not seen. The training loss alone cannot distinguish between the two, because fitting the noisy training data more closely always reduces that loss. The distance from the true curve or the validation loss can help distinguish between them.

Chart 15 trains three networks on $y_2$ from Chart 1 for 20,000 epochs each, changing one setting at a time. With 2 neurons (green), the network does not have enough flexibility to reproduce one and a half sine cycles. Its RMS error relative to $\sin x$ is 0.31. With 8 neurons (blue), it is 0.056 from $\sin x$ and 0.071 from the data. The red curve comes from the same 8-neuron network, but trained with the Adam optimizer instead of plain gradient descent. Adam makes more progress within the same number of epochs. Its RMS error relative to the data is lower (0.057), but its error relative to $\sin x$ is higher (0.071). Near $x$ = 6.5, the curve bends to follow the noise. Even with 32 neurons, plain gradient descent produces an RMS error of 0.060 relative to $\sin x$ after 20,000 epochs. The advanced calculator's validation split holds some rows out of training to measure exactly this; a later topic covers it in detail.

y2 as black dots from x = 0 to 10 with a gray dashed true sin x; a green 2-neuron curve flat on both sides, missing the outer peaks; a blue 8-neuron curve close to the sine; a red curve, the same 8 neurons trained with Adam, close to the dots with a bend near x = 6.5

Chart 15. $y_2$: an underfit (2 neurons), a good fit (8 neurons) and an overfit (the same 8 neurons, Adam), each after 20,000 epochs

A Network Is Not a Formula

Conventional curve fitting starts from a formula chosen in advance, with a few meaningful parameters, such as an amplitude and a frequency. A network's weights are also fitted to data, but the network does not assume a particular formula in advance. This is an advantage when the underlying formula is unknown. The trade-off is that its 25 weights are not individually interpretable (Chart 5), and its predictions outside the training range are not guaranteed to be reliable.

Chart 16 extends both models beyond the data range, up to $x$ = 14. The sine model $a \sin(bx + c)$, fitted to $y_2$ (with SciPy's curve_fit), finds $a$ = 1.0115, $b$ = 0.9995 and $c$ = โˆ’0.0182, and keeps following $\sin x$ beyond $x$ = 10: 0.017 RMS from it there. The network trained for 20,000 epochs fits the data range just as well, but beyond that range its tanh-based curves simply flatten out. At $x$ = 14 it predicts โˆ’1.91, while the true value is 0.99. Like interpolation, a network estimates values between its training samples. How accurately it does so depends on the number and distribution of those samples. Beyond the range of the training samples, predictions become much less reliable.

From x = 0 to 14 with the region past x = 10 shaded as no data: y2 dots up to 10; a green sine model, fitted with SciPy curve_fit, continuing on the gray dashed true sine to 14; a blue network curve that matches up to 10 then falls and flattens near โˆ’1.9

Chart 16. $y_2$ past its last sample: the network of Chart 3 against a fitted sine model

Example: A Noisy Sine, Learned Epoch by Epoch

Consider $y_2$ from Chart 1 again, this time using the default network trained for 20,000 epochs. The snapshots are marked in Chart 11. Table 4 lists the network's predictions at each integer value of $x$ after 100, 500, 2,000 and 20,000 epochs, alongside the data and the true values of $\sin x$. Chart 17 draws the whole curve at each snapshot, from the random start at epoch 0.

$x$$y_2$epoch 100epoch 500epoch 2,000epoch 20,000$\sin x$
00.00010.39400.83320.53940.02370.0000
10.79600.29700.73250.67270.78740.8415
20.86010.17970.53160.71940.91720.9093
30.15170.05810.07620.21310.15600.1411
4โˆ’0.8912โˆ’0.0357โˆ’0.6859โˆ’0.8187โˆ’0.8470โˆ’0.7568
5โˆ’1.1431โˆ’0.0661โˆ’1.0490โˆ’1.0415โˆ’1.0528โˆ’0.9589
6โˆ’0.2637โˆ’0.0233โˆ’0.2630โˆ’0.4024โˆ’0.3445โˆ’0.2794
70.65210.05830.48110.67750.60060.6570
80.89150.13020.53260.86890.92570.9894
90.40890.17170.39870.32180.41730.4121
10โˆ’0.53300.18680.2567โˆ’0.3019โˆ’0.5613โˆ’0.5440
RMS from $\sin x$0.59530.31420.15480.0556

Table 4. $y_2$: the default network's predictions at four epochs, against the data and $\sin x$ (RMS over all 41 rows)

y2 as black dots from x = 0 to 10 with five curves: gray epoch 0, a gentle random slope; green epoch 100, nearly flat; purple epoch 500, the dip formed but the peaks too low; red epoch 2,000, close except at the left end; blue epoch 20,000, on the data

Chart 17. $y_2$: the default network's curve at epochs 0, 100, 500, 2,000 and 20,000 (Table 4)

The network does not learn the entire curve uniformly. At epoch 100 it is still nearly flat: the loss in Chart 11 has not started to fall. By epoch 500 the large dip around $x$ = 5 has formed, the biggest feature in the data. By epoch 2,000, the second peak has also formed, but the left end is still inaccurate: the prediction is 0.54 at $x$ = 0, compared with the data value of 0.00. Only the longer training run brings the ends of the curve into alignment. After 20,000 epochs, the RMS distance from $\sin x$ is 0.0556, smaller than the noise in $y_2$ itself, 0.0891. The network has effectively averaged out some of the noise, even though it was never told that the underlying curve is a sine wave. If the only goal is to reduce noise, smoothing can do so more quickly and with fewer parameters to choose.

A network learns the big shapes first and the details last. Watch the loss: while it is still falling, the curve is still changing.

REFs

Wikipedia, Neural network (machine learning) Wikipedia, Gradient descent Wikipedia, Backpropagation Wikipedia, Activation function Wikipedia, Universal approximation theorem Wikipedia, Overfitting Goodfellow, Bengio and Courville, Deep Learning (MIT Press, 2016) Glorot and Bengio, Understanding the difficulty of training deep feedforward neural networks (2010) Kingma and Ba, Adam: A Method for Stochastic Optimization (2014) NumPy documentation Curve Fitting: Which Equation Fits My Data, and How Well? Interpolation Smoothing