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
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.
Fig 1. The five branches of machine learning and the three parts of this series
- Supervised learning: every example comes with its answer. The learner maps an input to that answer: a number (regression) or a label (classification). Example: a house's size and age to its price.
- Unsupervised learning: examples only, no answers. The learner finds structure: groups (clustering), fewer dimensions, or rare points. Example: customers grouped by what they buy.
- Semi-supervised learning: a few answers among many unanswered examples. The learner uses both: the unanswered ones show where the data lies, the answered ones what it means. Spreading labels to similar neighbours is one way to do it. Example: a hundred tagged photos labelling ten thousand more.
- Reinforcement learning: no fixed examples; the learner learns by interaction. It acts, the environment answers with a reward, and the learner finds the actions that pay off over time. Example: a program learning a board game by playing it.
- Self-supervised learning: each example hides part of itself, and the learner fills the gap. The answers come from the data, so no one labels anything. Example: a language model predicting the next word.
This series covers three tasks from Fig 1 that work with numerical data arranged in columns, like the data in a spreadsheet:
- Part 1, regression (this page): a number from $x$, learned by a small neural network. When a formula is chosen in advance and only its parameters are fitted, the task is usually called curve fitting.
- Part 2, classification: a label from two inputs, with logistic regression, k-nearest neighbours and a small network. Coming next.
- Part 3, clustering: groups in unlabelled points, with k-means, DBSCAN and Gaussian mixtures. After Part 2.
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.
- $y_1 = \sin x$: clean, rounded to four decimals. The true curve is known, so every result can be checked against it.
- $y_2 = \sin x$ + noise: the same curve with added noise (standard deviation 0.1), as a real measurement might have. Its RMS distance from $\sin x$ is 0.0891.
- $y_3 = |x - 5|$: a V shape with a sharp corner at $x$ = 5, which tests how a network handles a kink.
| $x$ | 0 | 0.25 | 0.5 | 1 | 2 | 3 | 5 | 7 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|
| $y_1$ | 0.0000 | 0.2474 | 0.4794 | 0.8415 | 0.9093 | 0.1411 | โ0.9589 | 0.6570 | 0.4121 | โ0.5440 |
| $y_2$ | 0.0001 | 0.2773 | 0.4520 | 0.7960 | 0.8601 | 0.1517 | โ1.1431 | 0.6521 | 0.4089 | โ0.5330 |
| $y_3$ | 5 | 4.75 | 4.5 | 4 | 3 | 2 | 0 | 2 | 4 | 5 |
Table 1. Ten of the 41 rows of the example
Chart 1. $y_1$ and $y_2$ of Table 1 at all 41 samples
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).
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):
Math 1.
- Why a weight and a bias: Without them, every neuron would draw the same curve. The weight controls the steepness of the curve, while the bias shifts its position along the input axis.
- Worked: Chart 4 draws Math 1 with $\varphi = \tanh$ for three pairs of $w$ and $b$. On the green curve, $w$ = 3 and $b$ = โ3, at the input $z$ = 1.5:
$$\begin{aligned} &a = w z + b = 3 \times 1.5 - 3 = 1.5 \\[0.9em] &h = \tanh 1.5 = 0.9051 \end{aligned}$$
- Picture: In Chart 4, increasing $w$ from 1 to 3 makes the blue curve steeper (red). Setting $b$ = โ3 then shifts the curve to the right, so that it is centred at $z$ = 1 (green), where $a$ = 0.
Chart 4. One neuron (Math 1) with $\varphi = \tanh$, for three weights and biases
Advantages
- Simple: one multiplication, one addition and one function per neuron.
- Smooth: with tanh or sigmoid, the output changes smoothly with $w$ and $b$, so a small change generally moves it only a little, which is what lets training adjust it gradually.
Disadvantages
- One step only: a single neuron cannot draw a peak, let alone a sine. It takes several, added together (Layer).
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):
Fig 2. The default network: 1 input, 8 tanh neurons, 1 linear output
Math 2.
- Why a sum: Each $h_j$ is the output of one neuron, as described in Math 1. Adding these outputs with positive and negative weights creates bumps and dips. With enough neurons and a suitable nonlinear activation, such as tanh or sigmoid, such a sum can approximate any continuous function on a closed, bounded interval of $x$, such as 0 to 10, as closely as wanted: the universal approximation theorem.
- Counting: 8 values of $w_j$, 8 of $b_j$, 8 of $v_j$ and one $c$ make 25 numbers. Training chooses all 25.
- Picture: Chart 5 opens up the network trained for 20,000 epochs on $y_2$ (the blue curve of Chart 3). The dashed lines are the eight terms $v_j h_j$ of Math 2, converted to $y$ units. Each is a single S-shaped step, some rising and some falling, several reaching ยฑ2. None of these individual curves looks like a sine wave, but their sum, together with the constant offset, produces the red curve that follows the 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.
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):
Fig 3. Two hidden layers of 4: one weight per layer-1 neuron, four per layer-2 neuron
Math 3.
- Notation: the superscript $(k)$ is the layer, from 1 to $K$; $n$ is the number of neurons per layer; $w^{(k)}_{ji}$ is the weight from neuron $i$ of layer $k-1$ to neuron $j$ of layer $k$. With $K$ = 1, Math 3 is Math 2.
- Counting: two layers of 8 neurons have 8 weights and 8 biases in layer 1, 8 ร 8 = 64 weights and 8 biases in layer 2, and 8 output weights plus $c$: 97 numbers, against 25 for one layer. Layer 2 holds most of them, because every pair of neurons in the two layers gets its own weight.
- On the page: the advanced calculator's Network grid shows these numbers row by row: h1.1, h1.2, โฆ with a bias and one weight; h2.1, h2.2, โฆ with a bias and $n$ weights; then out with $c$ and the $n$ output weights $v_j$.
- Why stack layers: layer 2 combines the S-shaped curves of layer 1 instead of the raw input, so it can build bends out of bends. For a curve of one input, such as these examples, one hidden layer can already approximate it (Math 2); a second layer mainly adds many more numbers to train.
Advantages
- Flexible: more neurons, more steps, more shapes; no formula needs to be chosen in advance.
- Same rule everywhere: every neuron is trained by the same correction (Gradient Descent).
Disadvantages
- Meaningless parts: the individual terms in Chart 5 have no physical meaning; only their sum does.
- More is not always better: more neurons can follow the noise as well as the signal (Underfitting and Overfitting).
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):
Math 4.
- Why a bend: This nonlinearity is what allows the sum in Math 2 to represent more than a straight line. Which bend fits best depends on the shape being learned.
- Picture: Chart 7 draws Math 4. tanh runs from โ1 to 1 and is centred on zero. Sigmoid has the same S shape, but runs from 0 to 1. ReLU is zero for negative inputs and the input itself for positive ones.
- Measured: On the corner of $y_3$, ReLU reaches a loss of 0.000031 after 2,000 epochs, against 0.011 for tanh. On the smooth $y_2$, tanh is the better choice: 0.056, against 0.246 for ReLU (Table 3).
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).
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
- tanh: smooth and centred on zero, a useful choice for smooth curves such as $y_2$ (Table 3).
- ReLU: builds corners and straight pieces exactly, such as the V of $y_3$.
Disadvantages
- Sigmoid: its output never goes negative, its slope is at most 0.25, and far from the centre the slope nearly vanishes (saturation), so its gradients are small. In Table 3, after 2,000 epochs, it has the highest final loss of the three on both $y_2$ and $y_3$.
- ReLU: a neuron whose input stays negative outputs zero and stops learning; curves built from ReLU pieces are made of straight segments.
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):
Math 5.
- Why squares: Squaring ensures that errors are never negative, so positive and negative errors cannot cancel each other out. It also penalizes large errors more heavily than small ones. In addition, its derivative is easy to calculate, which is useful in the next two sections.
- A hand-sized example: Take three points, (0, 1), (1, 3) and (2, 4), and the smallest possible network: one linear neuron, $\hat y = w x + b$, starting at $w$ = 0.5 and $b$ = 0. Table 2 lists its predictions and errors; Math 5 gives the loss:
$$\begin{aligned} &L = \frac{1 + 6.25 + 9}{3} = 5.4167 \end{aligned}$$
- Picture: Chart 9 draws the three points of Table 2 and the starting line in red. The dashed red segments show the prediction errors; all three predictions are too low.
| $x$ | $y$ | $\hat y = 0.5x$ | error $\hat y - y$ | squared |
|---|---|---|---|---|
| 0 | 1 | 0 | โ1 | 1 |
| 1 | 3 | 0.5 | โ2.5 | 6.25 |
| 2 | 4 | 1 | โ3 | 9 |
| mean | 5.4167 |
Table 2. Three points and one linear neuron, $w$ = 0.5, $b$ = 0: the loss of Math 5
Chart 9. The three points of Table 2: the starting line (red) and the line after one update of Math 6 (blue)
Advantages
- One number: progress is easy to follow, epoch by epoch (Chart 11).
- Smooth: its slope with respect to every prediction exists everywhere, and with tanh or sigmoid so does its slope with respect to every weight, which gradient descent needs. ReLU has a corner at 0, where the calculators take the slope as 0 (a subgradient).
Disadvantages
- Outliers: because errors are squared, one wild point can pull the whole curve towards it. See outlier detection.
- Not the truth: a small loss means close to the data, noise included, not necessarily close to the true curve (Underfitting and Overfitting).
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:
Math 6.
- Why against the gradient: A positive gradient means that increasing the weight increases the loss, so the weight should be reduced. A negative gradient means the opposite. Subtracting the gradient gives the local direction of steepest descent; with a small enough learning rate, the update lowers the loss (Chart 10 shows a rate too large).
- Worked, one update: Math 6 on the errors of Table 2, with $\eta$ = 0.1. Both gradients are negative, so both weights grow. The loss falls from 5.4167 to 1.5419: the blue line of Chart 9.
$$\begin{aligned} &\frac{\partial L}{\partial w} = \frac{2}{3}\big[(-1)(0) + (-2.5)(1) + (-3)(2)\big] = -5.6667 \\[0.9em] &\frac{\partial L}{\partial b} = \frac{2}{3}\big[-1 - 2.5 - 3\big] = -4.3333 \\[0.9em] &w \leftarrow 0.5 - 0.1 \times (-5.6667) = 1.0667 \\[0.9em] &b \leftarrow 0 - 0.1 \times (-4.3333) = 0.4333 \\[0.9em] &L = 1.5419 \end{aligned}$$$$\begin{aligned} &\frac{\partial L}{\partial w} = \frac{2}{3}\big[(-1)(0) + (-2.5)(1) \\ &\qquad + (-3)(2)\big] = -5.6667 \\[0.9em] &\frac{\partial L}{\partial b} = \frac{2}{3}\big[-1 - 2.5 - 3\big] \\ &\qquad = -4.3333 \\[0.9em] &w \leftarrow 0.5 - 0.1 \times (-5.6667) \\ &\qquad = 1.0667 \\[0.9em] &b \leftarrow 0 - 0.1 \times (-4.3333) \\ &\qquad = 0.4333 \\[0.9em] &L = 1.5419 \end{aligned}$$
- The learning rate: Chart 10 trains the default network on $y_2$ from Chart 1 with three learning rates. With a learning rate of 0.005, the updates are too small: even after 2,000 epochs, the loss is still 0.457. At 0.05, it falls steadily to 0.056. With a learning rate of 0.5, the loss initially falls faster, reaching 0.149 at epoch 108. However, the updates then overshoot, causing the loss to rise as high as 3.0 before ending at 0.737. At 1.0, it diverges within 7 epochs, and the calculators stop with a message.
Chart 10. The default network on $y_2$: loss against epoch for three learning rates $\eta$ of Math 6
Advantages
- One rule for every weight: the same update works for 2 weights or 25, or thousands.
- Each step is cheap: one gradient and one subtraction per weight.
Disadvantages
- The learning rate must be chosen: too small is slow, too large overshoots or diverges (Chart 10).
- Local, not global: a network's loss surface is generally not convex, so depending on where it starts, gradient descent can settle in a different local minimum or slow down near a saddle point (Random Start and the Seed).
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:
Math 7.
- Why backwards: Each gradient in Math 7 reuses the one before it: $\partial L/\partial w_j$ is $\partial L/\partial b_j$ times $z$. Working backwards from the loss allows all the gradients to be computed efficiently in a single pass, rather than calculating each one separately. For $N$ rows, the contributions from all rows are summed. Since $\delta$ already includes the factor $1/N$, this sum gives the average gradient across the dataset.
- Flow: Fig 4 shows the two passes through one neuron. The forward pass (black) computes $a$, $h$, $\hat y$ and $L$ in turn. The backward pass (red) multiplies the local slopes: $2(\hat y - y)$ at the loss, $v$ at the output, $1 - h^2$ (the slope of tanh) at the neuron, and $z$ at the weight.
- Worked: One point, scaled input $z$ = 1, $y$ = 3, one tanh neuron with $w$ = 0.5, $b$ = 0, $v$ = 1, $c$ = 0. Forward, then backward with Math 7:
$$\begin{aligned} &a = 0.5 \times 1 + 0 = 0.5, \quad h = \tanh 0.5 = 0.4621, \quad \hat y = 1 \times 0.4621 + 0 = 0.4621 \\[0.9em] &\delta = 2\,(0.4621 - 3) = -5.0758 \\[0.9em] &\frac{\partial L}{\partial v} = -5.0758 \times 0.4621 = -2.3456 \\[0.9em] &\frac{\partial L}{\partial w} = -5.0758 \times 1 \times (1 - 0.4621^2) \times 1 = -3.9918 \end{aligned}$$$$\begin{aligned} &a = 0.5 \times 1 + 0 = 0.5 \\[0.9em] &h = \tanh 0.5 = 0.4621 \\[0.9em] &\hat y = 1 \times 0.4621 + 0 = 0.4621 \\[0.9em] &\delta = 2\,(0.4621 - 3) = -5.0758 \\[0.9em] &\frac{\partial L}{\partial v} = -5.0758 \times 0.4621 \\ &\qquad = -2.3456 \\[0.9em] &\frac{\partial L}{\partial w} = -5.0758 \times 1 \\ &\qquad \times (1 - 0.4621^2) \times 1 \\ &\qquad = -3.9918 \end{aligned}$$
- Check: Nudging $w$ by ยฑ0.000001 and dividing the change in the loss by 0.000002 gives โ3.9918 as well. The calculators' tests run this check on every weight.
Fig 4. One neuron: the forward pass (black) and the backward pass of Math 7 (red)
Advantages
- Exact: the gradients are exact, not estimated by nudging each weight.
- Efficient: One backward pass takes roughly the same amount of computation as one forward pass, regardless of the number of weights.
Disadvantages
- Vanishing gradients: going back through each layer, the gradient is multiplied by that layer's weights and its activation slopes, such as $1 - h^2$. If these products keep shrinking it, the gradient becomes very small in the first layers, and they barely learn.
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):
Math 8.
- Why many epochs: Because each update is deliberately small (Chart 10), many updates are usually needed to move from a random starting point to a good fit.
- Worked: The 41 rows of Table 1 with plain gradient descent: $B$ = 41, one update per epoch. With mini-batches of 8:
$$\begin{aligned} &\left\lceil 41 / 41 \right\rceil = 1, \qquad \left\lceil 41 / 8 \right\rceil = 6 \end{aligned}$$
- Picture: Chart 11 follows the loss of the default network on $y_2$ over 20,000 epochs, on log scales. It starts at 2.04, worse than predicting the average. It then stays near 1 for a while, falls to 0.21 by epoch 500 and to 0.056 by 2,000, then flattens out at 0.011. The red dots mark the snapshots drawn in Chart 17.
Chart 11. The default network on $y_2$: training loss (Math 5) over 20,000 epochs
Advantages
- Progress you can watch: the loss after every epoch shows whether training is still improving.
- Mini-batches: several updates per epoch, each computed from only part of the rows. Updates occur more frequently, and each one requires less computation. For large datasets, this can make training more efficient and practical.
Disadvantages
- No natural end: the loss may continue to decrease slowly for a long time, so deciding when to stop training can be difficult (Underfitting and Overfitting).
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$ loss | what it changes |
|---|---|---|---|
| default: 8 neurons, tanh, $\eta$ 0.05, 2,000 epochs | 0.0563 | 0.0112 | a reasonable start |
| 2 neurons | 0.2386 | 0.0136 | too few steps for a sine |
| 16 neurons | 0.0589 | 0.0104 | more steps, not faster |
| ReLU | 0.2460 | 0.000031 | corners and straight pieces |
| sigmoid | 0.3132 | 0.0147 | highest loss of the three |
| learning rate 0.005 | 0.4568 | 0.0226 | steps too small |
| learning rate 0.5 | 0.7374 | 0.1123 | steps too large, overshoots |
| 20,000 epochs | 0.0109 | 0.00096 | more time, better fit |
Table 3. One setting changed at a time: final training loss on $y_2$ and $y_3$
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.
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.
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:
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.
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.
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.
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 100 | epoch 500 | epoch 2,000 | epoch 20,000 | $\sin x$ |
|---|---|---|---|---|---|---|
| 0 | 0.0001 | 0.3940 | 0.8332 | 0.5394 | 0.0237 | 0.0000 |
| 1 | 0.7960 | 0.2970 | 0.7325 | 0.6727 | 0.7874 | 0.8415 |
| 2 | 0.8601 | 0.1797 | 0.5316 | 0.7194 | 0.9172 | 0.9093 |
| 3 | 0.1517 | 0.0581 | 0.0762 | 0.2131 | 0.1560 | 0.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 |
| 7 | 0.6521 | 0.0583 | 0.4811 | 0.6775 | 0.6006 | 0.6570 |
| 8 | 0.8915 | 0.1302 | 0.5326 | 0.8689 | 0.9257 | 0.9894 |
| 9 | 0.4089 | 0.1717 | 0.3987 | 0.3218 | 0.4173 | 0.4121 |
| 10 | โ0.5330 | 0.1868 | 0.2567 | โ0.3019 | โ0.5613 | โ0.5440 |
| RMS from $\sin x$ | 0.5953 | 0.3142 | 0.1548 | 0.0556 |
Table 4. $y_2$: the default network's predictions at four epochs, against the data and $\sin x$ (RMS over all 41 rows)
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