121н. Overfitting and regularization in depth: L2, L1, dropout, data augmentation, early stopping
In 121и.3 regularization is shown as a single table: what each method does to the weights on a small set of display images. Here the same ground is covered slowly, explaining why each technique works rather than only how to write it down. Where overfitting comes from and how to see it on the curves, why the data needs three sets rather than two, where the "slightly less than one" factor in the L2 gradient comes from and why small weights give a smooth function, how L1 differs from L2 and what its zeros give the flash memory, what dropout does during training and what has to be done at inference, how to augment sensor data with shift, noise and scale. At the end — one and the same network with every method in a single table, and what of it reaches the device.
Basis: numpy 2.3.3 in the stm-ml:1 image, the script train121n.py
runs all experiments, and a repeated run produces the same files. Data —
the accelerometer window generator from 121м: 64 samples on three axes,
integer mg, five classes (rest, knock, shake, double tap, tilt), the
event at a random place in the window, own seed 1221. There are three
sets: 100 windows for training (per class 19, 23, 15, 25, 18), 1000 for
validation and 1000 for test. The network is fully connected
192 → 128 → 5 with ReLU, softmax with cross-entropy (121и), batch 10,
step 0.1, 300 epochs, He initial weights. All experiments share the
same initial weights and the same example order: only the
regularization method changes.
What it is called in the documentation
Original Meaning generalization gap accuracy on training minus accuracy on new data holdout test set looked at once, after all choices are made optimistic validation estimate the best of many results on the validation set is inflated penalty term, regularization strength λ the penalty in the cost and its strength λ subgradient sign(w) the sign of the weight: the derivative of the absolute weight everywhere except zero keep probability the probability that a neuron is not switched off at a step co-adaptation the answer relies on several neurons firing together model averaging the answer is the average of the answers of many networks time shift, jitter, magnitude scaling three ways to augment a signal bitmask sparse format one bit per weight plus only the nonzero values
121н.1 Overfitting in a picture
One hundred windows is little for a network with 25349 parameters: it has more weights than there are numbers in all training windows put together (100 × 192 = 19200). Such a network can learn every window by heart. Here is how training goes with no regularization at all:
| Epoch | 1 | 5 | 10 | 20 | 40 | 100 | 200 | 300 |
|---|---|---|---|---|---|---|---|---|
| correct on training, of 100 | 23 | 46 | 53 | 75 | 97 | 100 | 100 | 100 |
| correct on validation, of 1000 | 221 | 304 | 345 | 416 | 631 | 622 | 608 | 607 |
| validation cost | 1.598 | 1.538 | 1.452 | 1.313 | 1.173 | 1.209 | 1.379 | 1.494 |
For the first 40 epochs both curves rise together: the network finds what all knocks and all tilts have in common. Then the paths part. Training accuracy reaches 100 of 100 by epoch 89, while validation no longer grows but slides — from 631 to 607. The validation cost starts rising even earlier: it is lowest at epoch 69, 1.164, and by epoch 300 it is 1.494. The network answers its hundred windows more and more confidently and is more and more confidently wrong on others.
Why. The error on the training windows is the only thing the gradient sees. Once what the classes have in common is learned, the cost can be pushed further down only one way: by fitting the weights to the peculiarities of individual windows — where exactly in this window the knock was, what noise lay on this recording. In new windows the knock is elsewhere and the noise is different, and everything the network learned beyond the common part gets in its way. The gap between 100 % on training and 61 % on validation is called the generalization gap. Regularization is anything that narrows this gap without adding real data.
121н.2 Three sets and early stopping
The training set fits the weights. The validation set chooses everything else: how many epochs to train, which λ to take, whether dropout is needed. The test set is looked at once, at the very end, and nothing is chosen by it. Why a third set is needed shows up with early stopping.
Early stopping means remembering the weights at the epoch where validation was best and stopping when it has not improved for a long time. The best epoch here is epoch 40, 631 of 1000. How long to wait for an improvement (patience) is also a setting: with a patience of 10 epochs training stops at epoch 50, with 20 — at epoch 60, with 50 — at epoch 90, and in all three cases the weights of epoch 40 are returned. More than two thirds of the epochs are not needed at all.
Now the test. The epoch 40 weights are right on 609 of 1000 test windows, not on 631. The epoch 300 weights — on 615. Early stopping did not help here, and 631 turned out to be inflated. This is not a bug but a law: out of three hundred epochs the one where validation happened to be best was chosen, and the luck of the choice went into that number. The more variants are tried on the validation set — epochs, λ, architectures — the more the best of them is inflated. An honest number comes only from a set by which nothing was chosen.
Hence the rule for a device: the model's data sheet states the test accuracy, and the test recordings are kept apart from the very start, preferably from other devices and other days (117а). If the test was peeked at during selection, it has become a second validation set and a new one is needed.
121н.3 L2: where "weight decay" comes from and why small weights mean a smooth function
Deriving the correction. A penalty for the size of the weights is added to the cost C₀ (cross-entropy over the examples):
C = C₀ + λ/(2n) · Σ w²,
where n is the number of training examples and the sum runs over all weights (biases are not penalized: they shift the threshold rather than amplify an input). The derivative of the penalty with respect to one weight is λ/(2n) · 2w = λw/n, so the gradient gains one term:
∂C/∂w = ∂C₀/∂w + λw/n.
The backward pass (121з) computes ∂C₀/∂w as before; the correction is added at the end, one line per layer:
g[k] = g[k] + l2 / n * net[k] + l1 / n * np.sign(net[k]) # поправка от штрафа: λ/n·w и λ/n·sign(w)
The SGD step with this correction: w ← w − η·∂C₀/∂w − ηλw/n = (1 − ηλ/n)·w − η·∂C₀/∂w. Before the old step the weight is multiplied by a number slightly less than one — hence the name "weight decay". Here η = 0.1, n = 100, and with λ = 1 the factor is 0.999. Training has 3000 steps (300 epochs of 10 batches), and a weight the gradient does not support shrinks over training to 0.050 of its initial value. A weight needed for the answer is pushed back by the gradient every time: only weights the examples "pay for" survive.
The correctness of the correction is checked numerically, as in 121з: on a small network with both penalties, 159 derivatives, the largest relative difference between the analytic and numerical gradient is 4.1·10⁻⁸.
Why small weights mean a smooth function. A neuron's output changes by Σ wᵢ·Δxᵢ when the input changes by Δx. Large weights mean a large response to a small change of input: the network can jump sharply from answer to answer between two close windows, that is, learn a separate "step" under each training window. Small weights cannot do that: the function changes smoothly, and a single window with unusual noise cannot bend it much. This is visible directly. Noise of 20 mg was added to every test window and the average shift of the network outputs was computed:
| λ | Correct on training | On validation | On test | W¹ norm | Output shift from 20 mg noise |
|---|---|---|---|---|---|
| 0 | 100 | 607 | 615 | 19.958 | 0.256 |
| 0.03 | 100 | 606 | 615 | 18.660 | 0.240 |
| 0.1 | 100 | 606 | 614 | 16.132 | 0.211 |
| 0.3 | 100 | 598 | 611 | 11.685 | 0.163 |
| 1 | 100 | 587 | 596 | 7.290 | 0.097 |
| 3 | 68 | 443 | 410 | 3.267 | 0.026 |
The larger λ, the smaller the weight norm and the calmer the network is about noise: with λ = 1 the output shifts 2.6 times less. But validation accuracy did not rise for any λ. The best by validation is λ = 0.03, 606 against 607 without a penalty, and with λ = 3 the network did not learn even the training windows.
Why L2 did not help here although in 121и.3 it gave 22 answers. Windows of one class differ not by small noise but by the place of the event: a knock at the start of the window and a knock at the end are distant points in input space, with no smooth transition between them. Smoothness does not teach the network that they are the same thing. L2 cures overfitting to noise; if the difference between examples is something large, a different remedy is needed (121н.6).
121н.4 L1: sparsity and what it gives the microcontroller
For L1 the penalty is the sum of absolute values: C = C₀ + λ/n · Σ|w|. The derivative of |w| is the sign of the weight, ±1, and the correction to the step is ±ηλ/n (the same listing line as above). The difference from L2 is one thing: L2 takes away a fraction of the weight, L1 takes away the same amount. L1 barely notices a large weight, while a small one reaches zero in a few steps and then oscillates around it with an amplitude of ηλ/n. So L2 gives many small weights, and L1 gives many zero ones and a few large ones.
After training, first-layer weights below 1 % of the largest one in absolute value are replaced with zero (pruning). Of the 24576 weights of W¹ what remains is:
| λ for L1 | Correct on training | On validation | On test | W¹ norm | Nonzero W¹ weights |
|---|---|---|---|---|---|
| 0 | 100 | 607 | 615 | 19.958 | 23357 |
| 0.01 | 100 | 608 | 614 | 17.039 | 19302 |
| 0.03 | 100 | 597 | 611 | 12.905 | 11554 |
| 0.1 | 100 | 586 | 602 | 8.969 | 2099 |
| 0.3 | 66 | 449 | 439 | 5.185 | 186 |
With λ = 0.1 the network keeps 2099 weights of 24576 — less than a ninth — and loses 13 answers on the test. What this gives the device:
- Zeros in flash save nothing by themselves. A dense int8 array takes 24576 bytes no matter how many zeros it holds. Savings appear only if they are stored differently.
- Bitmask: one bit per weight (24576 / 8 = 3072 bytes) plus only the nonzero values. The traversal order is the same as for the dense matrix, the code is simple. For the network with L1 and data augmentation (121н.6, 10161 nonzero weights) this is 13233 bytes instead of 24576 — 46 % less.
- Column indices (an index byte for each nonzero weight — there are 192 inputs, so the index fits a byte — and 2 bytes for the start of each of the 128 rows and the end of the last one) cost more than the mask while there are more than 2814 nonzeros, about 11 %: for the same 10161 weights — 20580 bytes, a saving of only 16 %.
- Multiplications. Skipping zeros, the forward pass does as many multiplications as there are nonzero weights. But a branch on every weight costs instructions on a Cortex-M4; sparse code wins only when zeros are the majority.
- int8 after L1. With quantization at one scale per layer (119) a weight below half a step becomes zero by itself. The network without a penalty has 472 zeros of 24576 in int8, the network with L1 and augmentation — 13197, and the accuracy after int8 is almost the same (824 against 823 in float). L1 moves small weights in advance to where int8 would zero them anyway — and leaves large ones large, so the quantization step does not get finer because of them.
Unstructured pruning (individual weights) is as in 119а; removing a whole input or a whole neuron would pay more, but in these experiments not a single input and not a single hidden neuron was zeroed entirely.
121н.5 Dropout: what to do during training and at inference
During training. On every batch each hidden neuron is switched off with probability 1 − keep: its output becomes zero and no gradient flows through it. The remaining ones are divided by keep so that the average input of the next layer does not change:
mask = (rng.random(h.shape) < keep) / keep
h = h * mask
With keep = 0.5 half the neurons are switched off on average, and the remaining ones are doubled. The mask is new on every batch; in the backward pass the hidden layer error is multiplied by the same mask.
At inference. Neurons are no longer switched off, and the division by keep was already done during training — the network is computed as usual. If training did not divide, at inference the hidden layer outputs must be multiplied by keep; forgetting one of the two means feeding the next layer an input 1/keep times larger than the network saw. Experiment: the network trained with division was computed once more with the hidden layer doubled. Correct on test became 625 instead of 638, answers changed in 141 windows of 1000, and the average probability of the chosen class rose from 0.769 to 0.853 — the network became more confident and worse. In a deep network the error accumulates from layer to layer, and in int8 it also pushes activations outside the scale computed during calibration.
Why it is an ensemble. Each mask is its own subnetwork of a random half of the neurons, and all of them share the same weights. Over training each subnetwork sees a few batches, and together they learn on all of them. No neuron can count on its neighbour being there, so a feature that relies on two or three neurons firing together does not survive — each neuron has to be useful on its own. At inference the full network with the keep scale is a quick approximation of the average over all subnetworks. Checked: one random subnetwork is right on 621 windows of 1000, the averaged probabilities of 200 random subnetworks — on 644, the full network — on 638, and its answers matched the average over subnetworks on 989 windows. Two hundred passes are replaced with one.
Result on this data: dropout 0.5 lifted validation from 607 to 634 and test from 615 to 638. More than any λ, but the generalization gap remained: training is still 100 of 100.
121н.6 Data augmentation for sensor signals and the summary table
Data augmentation means new training examples made from old ones by transformations that do not change the class. For an accelerometer window there are three such transformations, and each reproduces something real:
- shift — the event at a different place in the window: the device does not know when someone will tap;
- noise — another sensor unit, other interference;
- scale — spread of sensitivity and mounting stiffness.
Copies are made anew every epoch, so the network never sees the same window twice:
if shift:
idx = np.arange(L)[None, :] - rng.integers(-shift, shift + 1, n)[:, None]
out = np.take_along_axis(out, np.clip(idx, 0, L - 1)[:, :, None], axis=1)
if scale:
out = out * rng.uniform(1 - scale, 1 + scale, (n, 1, 1))
if noise:
out = out + rng.normal(0, noise, out.shape)
Shift — up to 12 samples both ways (the window edge is repeated), noise — 20 mg, scale — ±20 %. All methods on one network, the same initial weights and example order; "pruned" means W¹ weights below 1 % of the largest replaced with zero:
| Method | Correct on training | On validation | On test | Best epoch by validation, test at it | Nonzero W¹ after pruning | Test, weights in int8 |
|---|---|---|---|---|---|---|
| no regularization | 100 | 607 | 615 | 40, 609 | 23357 | 615 |
| L2, λ = 0.03 | 100 | 606 | 615 | 40, 608 | 23343 | 615 |
| L1, λ = 0.01 | 100 | 608 | 614 | 40, 605 | 19302 | 614 |
| dropout 0.5 | 100 | 634 | 638 | 188, 640 | 23491 | 638 |
| shift | 91 | 850 | 837 | 287, 861 | 22631 | 836 |
| noise and scale | 100 | 608 | 616 | 131, 616 | 23307 | 617 |
| shift, noise and scale | 89 | 840 | 833 | 250, 849 | 22705 | 834 |
| augmentation + L2, λ = 0.3 | 86 | 832 | 827 | 252, 836 | 21499 | 828 |
| augmentation + L1, λ = 0.03 | 88 | 829 | 823 | 288, 853 | 10161 | 824 |
λ for L2 and L1 without augmentation was chosen by validation from the grids of 121н.3 and 121н.4. The last two rows use λ from the grid 0.1 / 0.3 / 1 for L2 and 0.01 / 0.03 / 0.1 for L1 on top of augmentation; the ones taken are not the best by validation but those where the penalty already acts noticeably (for L1 — more than half as many nonzero weights).
What is visible:
- Shift solves almost everything. From 607 to 850 on validation and from 615 to 837 on test. This is the very cause of overfitting from 121н.3: a network with a separate weight for every sample must see a knock at every place in the window, and shifting shows it that. The convolutional network of 121м gets the same for free, through shared weights.
- Noise and scale gave nothing — 608 against 607. The difference between windows in this data is not in noise or amplitude but in the place of the event. Augmentation helps only if it reproduces what really distinguishes the recordings.
- Training accuracy dropped from 100 to 89 — and that is good: the network can no longer memorize the windows, because they are different every time. The generalization gap narrowed from 39.3 percentage points (100 % and 60.7 %) to 5.0 (89 % and 84.0 %).
- Early stopping with augmentation picks late epochs (250–288): validation grows almost to the end. Without augmentation the best epoch is epoch 40, and the test at it is worse than at the end (121н.2).
- A penalty on top of augmentation costs 8–11 answers on validation, but L1 cuts the nonzero weights by more than half. If flash memory is tight, that is a fair trade.
What reaches the device. Regularization lives only on the computer: the device receives the weights and computes the forward pass, which has no penalties, no masks and no window copies. Three traces remain in the weights:
- size — after L1 the weights can be stored sparsely (121н.4): 13233 bytes instead of 24576 for W¹ in int8; the dense network in float would take 101396 bytes, dense in int8 — 25748;
- int8 — L1 has more weights that quantization zeros by itself (13197 against 472), L2 and dropout have fewer outliers from which the layer scale is computed;
- dropout — nothing at inference if training divided by keep; that is exactly what is checked by looking at the export code.
Data augmentation does not change the size at all, yet it gave the most. For a device this is the main conclusion: first augment the data with what really distinguishes the recordings, then tune a penalty for the sake of size.
121н.7 Pitfalls
The best validation epoch as the final accuracy. 631 on validation turned into 609 on test. A number chosen by a set is not evaluated on that same set.
Dropout without scaling at inference. 141 answers of 1000 changed, accuracy dropped from 638 to 625, confidence rose. The error is invisible without comparing outputs with the training code.
Augmentation that does not reproduce reality. Noise and scale — 608 against 607: training time spent, accuracy unchanged. First understand how the recordings differ (117), then augment exactly that.
A shift that moves the event past the window edge. With shifts of up to 12 samples a long event may partly leave the window and the edge gets repeated. If what identifies the class is cut off, the copy gets someone else's label. The shift length is chosen smaller than the margin between the event and the edge.
Too large a λ. With λ = 3 for L2 and 0.3 for L1 the network did not learn even the training windows: 68 and 66 of 100. The λ grid is taken in multiples (0.03, 0.1, 0.3, 1…) and both training and validation are watched.
Zeros without a sparse format. After L1 the weights are zero, but a dense int8 array takes the same 24576 bytes. Savings appear only in a format with a mask or indices.
Penalizing biases. Biases are not penalized: there are few of them, and pulling a threshold toward zero smooths nothing, it only keeps the neuron from firing in the right place.
121н.8 Summary
- 100 windows, a network with 25349 parameters: 100 of 100 on training from epoch 89, on validation a maximum of 631 at epoch 40, by epoch 300 — 607; the validation cost grows from epoch 69.
- Early stopping: best epoch 40, patience 10 / 20 / 50 epochs — stop at epoch 50 / 60 / 90; on test these weights gave 609, the epoch 300 weights — 615.
- L2: a correction λw/n to the gradient, a factor 1 − ηλ/n before the step; with λ = 1 the W¹ norm goes from 19.958 to 7.290, the output shift from noise from 0.256 to 0.097, accuracy did not rise (best λ = 0.03: 606).
- L1: with λ = 0.1 2099 W¹ weights of 24576 remain at the cost of 13 answers on test.
- Gradient check with both penalties: 159 derivatives, difference 4.1·10⁻⁸.
- Dropout 0.5: validation 634, test 638; without scaling at inference — 625; the average of 200 subnetworks — 644, matched the full network on 989 windows.
- Data augmentation: shift — 850 on validation and 837 on test, noise and scale — 608, all together — 840 and 833; with L1 — 10161 nonzero weights, 13233 bytes with a bitmask instead of 24576.
Further reading: Michael Nielsen, Neural Networks and Deep Learning, neuralnetworksanddeeplearning.com.
Next: section 121о "Training networks in depth: weight initialization, learning rate, momentum, hyperparameter search".