Embedded HandbookApps
All sections › XIV. Machine learning on a microcontroller
STM32F407 · level advanced · 17 min read
Open in the interactive handbook

121и. Cross-entropy, softmax, regularization and hyperparameter tuning in practice

In 116б cross-entropy, L2, dropout, early stopping and Xavier initial weights are already there — as ready-made techniques with one experiment each. In 121з it is derived that for softmax with cross-entropy the error of the output layer equals P − Y. Here is why these techniques work and how to use them: how exactly the quadratic cost slows learning down and where this shows in the formula, how to compute softmax and the logarithm of a probability so as not to get an infinity, what each regularization does to the weights, when the spread of the initial weights matters and when it does not, and the order of tuning the step, stopping and batch size. At the end — what of all this reaches the microcontroller.

Basis: numpy 2.3.3 in the stm-ml:1 image, the script train121j.py — all experiments, a repeated run gives the same files. The data are the same reader of a 5 × 7 dot-matrix display as in 121ж and 121з (35 bits, board shift, stray light, dot errors), with its own seed: 3000 examples for training, 1000 for tuning (they take no part in training, settings are chosen on them), 1000 for testing. The answer in C: gcc 12.2.0 (stm-sys:1) for the cross-check, arm-none-eabi-gcc 12.2.1 and QEMU 7.2 (stm-arm:1, board netduinoplus2 with an STM32F405 — the same Cortex-M4F core as the F407) — instruction counts, armclang 6.24 — bytes.

Terms used in the documentation

Term Meaning
learning slowdown slowdown of learning: the gradient is small although the error is large
saturated neuron saturated neuron: the sum is far from zero, σ′ is almost zero
log-likelihood cost log-likelihood cost: minus the logarithm of the probability of the correct class
log-sum-exp the logarithm of a sum of exponentials, computed after subtracting the largest term
L1 regularization a penalty on the sum of absolute weights: presses unneeded weights to zero
weight norm weight norm: the square root of the sum of squares
inverted dropout dropout with division by the share kept: nothing changes at inference
learning rate schedule step schedule: when and by how much to reduce it
patience patience: how many epochs to wait for an improvement before stopping
argmax the index of the largest element

121и.1 Why the quadratic cost slows down a saturated neuron

Take an output neuron a = σ(z) with a target y. For the quadratic cost C = ½(a − y)² the derivative with respect to the weighted sum has, by the chain rule, two parts: ∂C/∂a = a − y and ∂a/∂z = σ′(z). In total (a − y)·σ′(z). The error a − y may be almost one, but if z is far from zero, σ′(z) is almost zero — and the gradient is almost zero. The neuron is confidently wrong and yet hardly learns: the more saturated it is, the more slowly it leaves saturation.

Cross-entropy for the same neuron is C = −[y ln a + (1 − y) ln(1 − a)]. Its derivative with respect to a is (a − y)/(a(1 − a)), and σ′(z) of the sigmoid is exactly a(1 − a). When multiplied they cancel, and what remains is ∂C/∂z = a − y: the gradient is proportional to the error and does not depend on how saturated the neuron is. That is the whole point of the choice — the cost was picked so that the factor σ′ goes away.

        return (a - T) * a * (1.0 - a)                 # ∂C/∂z = (a − y)·σ′(z)
        return sig(z) - T                              # ∂C/∂z = a − y: σ′ сократилась

One neuron. Input 1, target 0, initial w = b = 2: the sum is 4, the output 0.982 — the neuron is confidently wrong. Step 0.15:

After steps 0 10 30 100 300
output, quadratic cost 0.982 0.981 0.979 0.964 0.203
output, cross-entropy 0.982 0.775 0.204 0.041 0.012

On the first step ∂C/∂z of the quadratic cost is 0.0173, of cross-entropy 0.9820: 57 times larger at the same error.

A network. The 35 → 16 → 10 network, initial weights N(0, 1) — 19.0 % of the output neurons have σ′ < 0.01 at the start. The same initial weights, the same order of examples, batch 20, step 0.5; only the cost at the output changes:

On the left the learning curves of the 35 → 16 → 10 network with the same initial weights N(0, 1): horizontally epochs 1, 2, 3, 5, 10, 20, 30, vertically correct out of 1000 on the tuning set; the quadratic cost grows from 147 to 725, cross-entropy with a sigmoid from 584 to 917, softmax with log-likelihood from 596 to 903. Top right, why: δ of the output neuron is (a − y)·σ′(z) for the quadratic cost and a − y for cross-entropy; a neuron with output 0.982 at target 0 gets δ 0.0173 against 0.9820 and after 30 steps outputs 0.979 against 0.204. Bottom right, 100 examples on the 35 → 30 → 10 network: without regularization 100 % on training and 617 out of 1000 on tuning, L2: 639 and the norm of W1 from 20.5 to 14.9, L1: 626 and 795 out of 1050 weights near zero, dropout 0.5: 641, data augmentation: 858

Epoch 1 2 3 5 10 20 30
quadratic cost 147 272 289 380 549 708 725
cross-entropy (sigmoid at the output) 584 716 766 836 870 906 917
softmax + log-likelihood 596 763 783 837 864 894 903

Correct out of 1000 on the tuning set. After the first epoch the quadratic cost recognises 147 digits — almost guessing, cross-entropy 584. In 30 epochs the quadratic cost reached 725 — as much as cross-entropy gained in two or three epochs. The sigmoid with cross-entropy and softmax with log-likelihood behave almost the same: both have δ = a − y.


121и.2 softmax and log-likelihood: how to compute them without infinity

softmax turns the output sums into probabilities pₖ = e^zₖ / Σ e^zⱼ, the cost is −ln p of the correct class. Both formulas computed head-on break in float32: e^z overflows already at z > 88.72 (121з.7), and a very small probability turns into zero, and its logarithm into minus infinity.

The first is cured by subtracting the largest sum m: e^(zₖ − m) / Σ e^(zⱼ − m) is the same thing, because the factor e^(−m) cancels, but the exponents are now not above zero. The second — by computing the logarithm of the probability directly, not through the probability itself: ln pₖ = zₖ − m − ln Σ e^(zⱼ − m). Under the logarithm the sum is not less than one (the term of the largest sum is exactly 1), so no zero appears there.

    return s - m - np.log(np.exp(s - m).sum(axis=1, keepdims=True))   # log-sum-exp

Two sums (0; −d) in float32, the logarithm of the probability of the second class:

Gap d ln(softmax) head-on log-sum-exp
20 −20 −20
102 −101.9 −102
104 −inf −104

At a gap of 102 the probability is a denormal number of a few units of the lowest float32 digit, and the logarithm is already inaccurate; at 104 it turns into zero. For the answer this does not matter, for training a cost of inf and a NaN gradient on a single example spoil all the weights.

In int8. A model after quantization (119) gives the output sums as integers: z ≈ s·q with one scale s > 0 for the whole layer. Multiplication by a positive number does not change the order, so the index of the largest sum is taken directly from the codes q, without conversion to float and without softmax. On our network (scale 0.153 — sums up to 19.5 in magnitude) the answer from the int8 codes matched the answer from float32 for 499 examples out of 500: one example was lost to rounding. If softmax is needed, though (the confidence of the answer), its result in a byte with a step of 1/255 is coarse: 78.3 % of all probabilities turned into zero, for 2 examples out of 500 even the probability of the correct class is zero, its logarithm cannot be computed. So the cost and any logarithms are computed from the sums via log-sum-exp, not from quantized probabilities.


121и.3 Overfitting on a small set and what regularization does to the weights

The 35 → 30 → 10 network (1390 parameters), only 100 examples, batch 10, step 0.5, initial weights N(0, 1/n):

Epoch 10 30 100 300
correct on training, out of 100 57 95 100 100
correct on tuning, out of 1000 387 585 619 617
training cost 1.353 0.384 0.044 0.008
tuning cost 1.871 1.641 2.102 2.568

By the hundredth epoch the network has learned all 100 examples, and on new ones it recognises 62 %. After that the training cost falls five times more, the tuning cost grows: the network is ever more confident in its answers on its own examples and ever more confidently wrong on others. The number of correct answers barely changes meanwhile — overfitting shows in the cost earlier than in accuracy, so both must be watched.

Now the same experiment, the same number of SGD steps (about 3000), one thing changes:

        W *= 1.0 - eta * l2 / n                        # L2: вес уменьшается в одно и то же число раз
        W -= eta * l1 / n * np.sign(W)                 # L1: вес уменьшается на одну и ту же величину
Method Correct on training On tuning Norm of W¹ Mean magnitude Largest Weights below 0.01 On tuning without them
no regularization 100 617 20.5 0.494 2.25 16 617
L2, λ = 0.1 100 639 14.9 0.361 1.52 23 640
L2, λ = 2 73 445 5.6 0.131 0.53 137 445
L1, λ = 0.2 100 626 12.9 0.136 2.96 795 622
dropout 0.5 100 641 31.2 0.776 3.05 7 641
data augmentation (shifts) 98 858 31.3 0.750 3.51 15 858

W¹ is the first layer, 1050 weights. "Without them" means the same weights where all below 0.01 in magnitude are replaced by zero.

    """Расширение данных: каждый пример ещё и сдвинутым на точку в 8 сторон — 9 копий."""

121и.4 Initial weights: N(0, 1) against N(0, 1/n)

If the weights of a neuron with n inputs are drawn from N(0, 1), the spread of its sum grows as √(number of inputs equal to one). The sum goes far from zero, the sigmoid saturates, and in a hidden layer cross-entropy no longer helps: σ′ of this layer stands in the backward transfer of δ (121з.2). A spread of 1/√n keeps the spread of the sum around one for any n.

Inputs, network Initial weights Spread of the sum Saturated neurons Epoch 1 2 5 10 30
35, 35 → 100 → 10 N(0, 1) 3.6 19.6 % 802 878 920 931 953
35, 35 → 100 → 10 N(0, 1/n) 1.1 0.0 % 557 740 804 868 943
560, 560 → 30 → 10 N(0, 1) 14.2 73.8 % 594 705 809 833 866
560, 560 → 30 → 10 N(0, 1/n) 1.1 0.0 % 787 856 893 910 920

"Saturated" is the share of hidden neurons with σ′ < 0.01 at the start; correct out of 1000 on the tuning set. 560 inputs are the same display read by a matrix of 20 × 28 sensors: each dot is a 4 × 4 square, each sensor has 3 % errors.

On 35 bit inputs N(0, 1) even wins: a sum with a spread of 3.6 saturates only a fifth of the neurons, while the narrow weights N(0, 1/n) give an almost linear sigmoid, and at step 0.5 the network speeds up slowly. On 560 inputs the picture is reversed: three quarters of the neurons are saturated, and after 30 epochs such a network recognises 866 against 920. The 1/√n rule is needed not for small networks but so that the behaviour does not depend on the number of inputs: sensors added — the step does not have to be tuned again.


121и.5 Hyperparameter tuning: the order of steps

The 35 → 30 → 10 network, all 3000 examples, batch 20. Everything is chosen on the 1000 tuning examples; the test examples are opened once at the end.

1. The step — first the order of magnitude. Five epochs with steps ten times apart:

Step 0.01 0.1 1 10 100
training cost after 5 epochs 2.252 1.455 0.318 0.366 59.278
correct on tuning 209 568 857 853 100

At 0.01 the cost has hardly moved away from ln 10 ≈ 2.30 — the cost of a network that answers at random; at 100 the network blew up: the cost grew to 59, correct 100 out of 1000 — guessing. The working band is from 1 to 10. We take a step near the lower edge of the band, where the cost falls fast and evenly — 1; refining it to the second digit is useless.

2. How many epochs — early stopping decides. Train while the accuracy on the tuning set grows; 10 epochs in a row without improvement — stop, return the weights of the best epoch. The stop came at the 37th epoch, the best was the 27th, 936 on tuning, 933 out of 1000 on the test. The number of epochs is no longer a hyperparameter.

3. Step schedule. Instead of stopping — 5 epochs without improvement, the step is halved; when it has become 128 times smaller than the initial one, stop. The run took 59 epochs, the best was the 19th: 934 on tuning, 935 on the test. On such a small task the schedule gave nothing but extra epochs: it is useful when a large step is needed to speed up and then the weights jump around the minimum.

4. Mini-batch size (10 epochs, best on tuning):

Batch 1 10 100 1000 100, step 10
SGD steps 30000 3000 300 30 300
correct on tuning 934 939 812 458 933

The batch gradient is averaged, so at the same step a large batch makes 10 times fewer steps per epoch and falls behind. If the step is increased together with the batch (100 and 10), it catches up. The batch size is chosen by the computing speed on your computer (121з.4), then the step is tuned for it.

The order: the step by order of magnitude → early stopping → regularization on the tuning set (121и.3) → optionally a schedule → the test once.


121и.6 What reaches the microcontroller

The cost, regularization, dropout and data augmentation live only on the computer: on the instrument the weights and the forward pass remain. Two traces still get through. The first is size: the 35 → 30 → 10 network takes 5560 bytes in float (W¹ 4200, W² 1200, biases 160). In the experiment of 121и.3 after L1 only 255 of the 1050 first-layer weights are needed — the rest need not be stored at all.

The second is softmax. The answer does not need it: the largest probability is where the largest sum is. It is needed only if the instrument must say how confident it is:

void softmax_f(const float *s, float *p)
{
    float m = s[argmax_f(s)], sum = 0.0f;
    for (int c = 0; c < N_OUT; c++) {
        p[c] = expf(s[c] - m); /* показатель не больше нуля: expf не переполнится */

The network from early stopping (121и.5), 500 test examples, QEMU netduinoplus2 with -icount, arm-none-eabi-gcc -O2 with the FPU:

Action Instructions At 168 MHz, no faster than
forward pass to the output sums 10967 65.3 µs
argmax_f over 10 sums 98 0.6 µs
softmax_f over 10 sums 912 5.4 µs
answer without softmax 11069 65.9 µs
answer with softmax and confidence 11977 71.3 µs

softmax is 9 times more expensive than argmax — ten expf calls — but against the forward pass with 30 sigmoids the addition is 908 instructions, 8.2 %. In bytes (armclang -Os, FPU): argmax_f 42, softmax_f 120, logits 192. The answers on the computer and in QEMU with and without softmax matched numpy in 500 cases out of 500, correct 463 out of 500. Confidence below 0.9 for 84 examples: this is the use of softmax on the instrument — to ask again or show "not sure" instead of a wrong digit.


121и.7 Pitfalls

Quadratic cost with a sigmoid at the output. The network learns, but the first epochs stand still: 147 out of 1000 after the first epoch against 584 for cross-entropy with the same weights. For classes — softmax with log-likelihood, the quadratic cost is for numbers (116б.2).

The logarithm of softmax head-on. At a gap between sums of 104 the probability in float32 is zero, the cost is inf, the gradient is NaN. Compute log-sum-exp.

Regularization against the wrong disease. λ = 2 instead of 0.1: 445 on tuning instead of 639, the network did not learn even its own 100 examples. The strength of the penalty is tuned just like the step — by order of magnitude on the tuning set.

L1 without zeroing. L1 brings weights down to small, but not to exact zeros: 795 weights below 0.01, exact zeros among them — none. To gain memory, they must be zeroed explicitly and the accuracy checked again.

Test data in tuning. If the step, the epoch and λ are chosen on the test examples, the test stops being a test — the estimate comes out too high. That is what the third, tuning set is for.


121и.8 Summary

Further reading: Michael Nielsen, Neural Networks and Deep Learning, neuralnetworksanddeeplearning.com.

Full sources

softmax121j.c — the forward pass, argmax, a stable softmax and an answer with confidence in C with the weights from model121j.h.

/* Раздел 121и: ответ сети 35 → 30 → 10 на приборе — с softmax и без него.
 * logits        — прямой проход до выходных сумм (сигмоида в скрытом слое).
 * argmax_f      — номер наибольшей суммы: ответу softmax не нужен, он не меняет порядок.
 * softmax_f     — вероятности, если нужна уверенность: вычесть наибольшую сумму, потом expf.
 * classify_arg  — ответ без softmax; classify_soft — ответ и вероятность через softmax.
 * Вход — 35 байтов 0/1. Веса и данные — model121j.h (train121j.py).
 * На компьютере (-DML_HOST) main сверяет оба ответа с numpy на 500 примерах.
 * Проверка — _verify/nn121j_check.py. */
#include <math.h>
#include <stdint.h>

#if defined(ML_HOST) && !defined(ML_DATA)
#define ML_DATA
#endif
#include "model121j.h"

void logits(const uint8_t *x, float *s)
{
    float h[N_HID];
    for (int j = 0; j < N_HID; j++) {
        float z = B1[j];
        for (int i = 0; i < N_IN; i++)
            if (x[i])
                z += W1[i * N_HID + j];
        h[j] = 1.0f / (1.0f + expf(-z));
    }
    for (int c = 0; c < N_OUT; c++) {
        float z = B2[c];
        for (int j = 0; j < N_HID; j++)
            z += h[j] * W2[j * N_OUT + c];
        s[c] = z;
    }
}

int argmax_f(const float *s)
{
    int k = 0;
    for (int c = 1; c < N_OUT; c++)
        if (s[c] > s[k])
            k = c;
    return k;
}

void softmax_f(const float *s, float *p)
{
    float m = s[argmax_f(s)], sum = 0.0f;
    for (int c = 0; c < N_OUT; c++) {
        p[c] = expf(s[c] - m); /* показатель не больше нуля: expf не переполнится */
        sum += p[c];
    }
    for (int c = 0; c < N_OUT; c++)
        p[c] /= sum;
}

int classify_arg(const uint8_t *x)
{
    float s[N_OUT];
    logits(x, s);
    return argmax_f(s);
}

int classify_soft(const uint8_t *x, float *conf)
{
    float s[N_OUT], p[N_OUT];
    int k;
    logits(x, s);
    softmax_f(s, p);
    k = argmax_f(p);
    *conf = p[k];
    return k;
}

#ifdef ML_HOST
#include <stdio.h>
int main(void)
{
    int right = 0, same = 0, low = 0;
    for (int k = 0; k < N_TEST; k++) {
        float conf;
        int a = classify_arg(&TEST_X[k * N_IN]), b = classify_soft(&TEST_X[k * N_IN], &conf);
        right += a == TEST_Y[k];
        same += a == b && a == NP_ANS[k];
        low += conf < 0.9f;
    }
    printf("right=%d,%d\nsame=%d,%d\nconf_below_0.9=%d\n", right, N_TEST, same, N_TEST, low);
    return 0;
}
#endif

Next: section 121к "Why a network can compute any function: universality by hand and a network instead of a sensor calibration table" — the series "Neural networks from the inside": how to build a bump from a pair of sigmoid neurons and any curve from bumps, what the universality theorem does not promise, why networks need depth and when a small network beats a thermistor calibration table and when it does not.

Open in the interactive handbook