Embedded HandbookApps
All sections › XIV. Machine learning on a microcontroller
STM32F103 · level intermediate · 15 min read
Open in the interactive handbook

121ж. The perceptron and the sigmoid neuron: from a logic gate to a trainable network

This section opens the series "Neural networks from the inside". In 116б the neuron, loss functions and backpropagation were taken apart on a pump task, in 116 and 118 scikit-learn trained the perceptron. Here we step back to the simplest neuron: the perceptron as a logic gate from which an adder is built; why it is hard to train and what the sigmoid changes; layers and forward propagation on a task with 35 sensors. At the end both models go to C for a Cortex-M0 and a Cortex-M3 without a floating-point unit: an integer perceptron against a sigmoid network in float.

Basis: numpy 2.3.3 in the stm-ml:1 image, the script train121h.py — every number of the section comes from its run, a repeated run gives the same files. Inference 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, boards microbit with a Cortex-M0 and netduino2 with a Cortex-M3) — instruction counts, armclang 6.24 with microlib — bytes. The STM32F103C8 data come from the device description in the Keil pack STM32F1xx_DFP 2.4.1.

Terms used in the documentation

Term Meaning
perceptron perceptron: a weighted sum and a threshold, output 0 or 1
threshold, bias threshold; the bias is the threshold with the opposite sign
step (Heaviside) function step: 1 for a positive input, otherwise 0
linearly separable linearly separable: one line (plane) divides the classes
half adder, full adder half adder, full adder
ripple-carry adder adder with a sequential carry chain
perceptron learning rule perceptron rule: on an error add the input to the right class, subtract it from the wrong one
sigmoid neuron sigmoid neuron: the same sum through the smooth 1/(1 + e⁻ᶻ)
input, hidden, output layer input, hidden, output layer
feedforward network feedforward network: the signal only goes forward
dot-matrix display dot-matrix display
soft-float library software floating-point library

121ж.1 The perceptron: a weighted vote with a threshold

A perceptron receives several binary inputs, each with its own weight — "how many votes" that input has. The votes are added, the bias is added to the sum, and if the result is above zero the output is 1, otherwise 0:

def perc(w, b, x):
    return int(np.dot(w, x) + b > 0)

The bias is the same threshold with the opposite sign: "more than −b votes are needed". A positive weight votes "for", a negative one "against", zero makes the input irrelevant. Logic gates come from choosing three integers:

Gate Weights Bias Output for 00, 01, 10, 11
AND 1, 1 −1 0001
OR 1, 1 0 0111
NAND −1, −1 2 1110

There are 16 functions of two inputs. Trying all weights and biases from −3 to 3 — 343 combinations — gives only 14 of them. "Exclusive OR" and its negation do not come out: on the plane of inputs the points 01 and 10 would have to be separated from 00 and 11 by one line, and no such line exists. A perceptron divides the inputs only by a line (a plane in many dimensions); the classes must be linearly separable.


121ж.2 Any logic from perceptrons: an adder

Since a perceptron can do NAND, any logic circuit can be built from perceptrons: NAND gates alone give everything else. But a perceptron is stronger than a NAND gate — it weighs many inputs at once. XOR, which a single perceptron lacks, takes three in two layers: AND of the outputs of OR and NAND, truth table 0110.

A full adder (two bits and a carry in) needs just two perceptrons. The carry is "at least two of three": weights 1, 1, 1 and bias −1. The sum sees the three inputs and the carry itself with weight −2: the carry "eats" two votes.

def full_adder(a, b, cin):
    """Полный сумматор из двух перцептронов: перенос — «два из трёх», сумма видит перенос с весом −2."""
    cout = perc((1, 1, 1), -1, (a, b, cin))
    s = perc((1, 1, 1, -2), 0, (a, b, cin, cout))
    return s, cout

Check against the full truth table: 8 rows out of 8 are right. Four such adders in a chain make a 4-bit ripple-carry adder of 8 perceptrons; all 512 combinations of two 4-bit numbers and the carry in give the right sum, 0 errors. The second layer here receives not only the output of the first one but also the original inputs — that is allowed too.

On the left a full adder of two perceptrons: the carry cout with weights 1, 1, 1 and bias minus 1, the sum s sees the inputs a, b, cin and the carry with weight minus 2, truth table 8 of 8, 4-bit adder 512 of 512, one perceptron gives 14 of 16 functions of two inputs. On the right a 5 × 7 matrix of 35 phototransistors gives 35 bits, then two models: the integer perceptron 35 → 10 — 777 right out of 1000, the sigmoid network 35 → 16 → 10 with 746 parameters — 909 of 1000; without a shift 352 and 363 of 369, with a shift 425 and 546 of 631; on a Cortex-M3 1133 and 79291 instructions per answer

There is no point building logic this way — a microcontroller has instructions. What matters is the conclusion: a network of perceptrons is no weaker than any circuit, and the weights need not be chosen by hand — they can be learned.


121ж.3 Why the perceptron learns badly and what the sigmoid gives

Training is a series of small changes to the weights, and after each change the output should change a little. A perceptron's output jumps or does not change at all. An experiment on the trained network of 121ж.5: in the first layer the weight with the largest loss gradient is taken — from point 18 of the matrix to the fifth neuron of the hidden layer, its value is −2.1592. A shift from −1 to +1 in steps of 0.005 (400 steps) is added to it, and at each step the loss over the 3000 training examples is computed — for the network with the sigmoid and for the same network with a step in the hidden layer:

Hidden layer Steps without a loss change, of 400 Largest change per step Loss: from … to
sigmoid 0 0.0001 0.0907 … 0.1002
step 275 0.0023 0.2139 … 0.2349

With the step the loss is a staircase of 126 levels: on 275 steps of 400 it does not change, the derivative is zero and the descent has nowhere to go, and on the rest it jumps. Shifting the same weight by 0.05: with the step the neuron output flips completely (0 ↔ 1) for 3 examples of the 1395 where point 18 is lit, and does not change for the rest; with the sigmoid the output moves for every one of them, but by no more than 0.0125. To flip even one step output the weight has to move by at least 0.0372 — until then training sees nothing.

A sigmoid neuron computes the same sum z = w·x + b, but the output is σ(z) = 1/(1 + e⁻ᶻ): for a large positive z almost 1, for a large negative one almost 0 — like the step, with a smooth transition in between, and a small change of a weight gives a small change of the output. That is why gradient descent works (116б). The sigmoid does not erase the perceptron: in the trained network 56.2 % of the hidden-layer outputs on the test examples lie closer than 0.05 to zero or to one. If the sigmoid in it is replaced with a step without touching the weights, the network is still right in 874 cases of 1000 against 909 with the sigmoid.


121ж.4 Layers and forward propagation: a task with 35 sensors

The task. An old instrument shows a digit on a 5 × 7 dot-matrix display; on top of the display sits a board with 35 phototransistors, one above each dot. An STM32F103 reads them through the ADC and a threshold of 0.45 and gets 35 bits. A lit dot gives 0.80 ± 0.10 of full scale, a dark one 0.10 ± 0.08 (light from the neighbours). Disturbances: the board may sit shifted by one dot along each axis (probability 0.2 in one direction and 0.2 in the other), 3 % of the dots are dead or stuck — the bit is inverted. On average 12.79 dots of 35 are lit. The data are synthetic, seed 1218: 3000 examples for training, 1000 for tuning and 1000 for testing; the test set has 631 examples with a shift and 369 without. MNIST is the same idea on 28 × 28 pictures; here it is at microcontroller scale.

The network is made of layers:

Forward propagation means computing the layers one after another, from input to output; the signal only goes forward. In total 35 · 16 + 16 + 16 · 10 + 10 = 746 parameters. Example: test example No. 5 is the digit 2, read with a shift. In the hidden layer 6 neurons of 16 rose above 0.5, at the output after softmax the probability of "2" is 0.951, the next one, "3", is 0.037.

The integer perceptron for the same task is 10 perceptrons without a hidden layer, one per digit; the answer is whichever sum is larger. These are straight boundaries in a 35-dimensional space.


121ж.5 Training: the perceptron rule against SGD

The perceptron learns without derivatives. For each example 10 sums are computed; if the largest does not belong to the right digit, the input is added to the weights of the right one and subtracted from the weights of the wrong one:

        if p != t:                          # правило перцептрона: верному +x, ошибочному −x
            W[t] += x
            B[t] += 1
            W[p] -= x
            B[p] -= 1

The inputs are 0 and 1, the change is ±1, so the weights are always integers. Errors per epoch (of 3000): 1267 in the first, 969 in the second, 825 in the fifth, 743 in the tenth, 714 in the twentieth, 703 in the fortieth. It never reaches zero: with the shift and the noise the digits cannot be separated by straight boundaries, and on non-separable data the perceptron rule does not converge — the weights swing. So the weights of the best epoch on the tuning set are kept: epoch 17, 806 of 1000. On the training set — 2415 of 3000, on the test set — 777 of 1000. The weights from −35 to 35 fit into int8_t, the biases from −73 to 53 and the sums on the test set from −188 to 112 need int16_t.

The sigmoid network learns by descent: softmax with cross-entropy at the output, SGD with batches of 20, step 0.5, 60 epochs, initial weights by Xavier, in our own numpy code — the algorithm is taken apart in 116б. What is new here is that the derivative of the sigmoid is expressed through the output itself: σ′ = h(1 − h).

                    g = (g @ P[li][0].T) * h_in * (1.0 - h_in)      # производная сигмоиды: h(1 − h)

The inputs are bits, no normalisation is needed. The size of the hidden layer (weights of the best epoch on the tuning set):

Model Parameters Tuning of 1000 Test of 1000 No shift, of 369 Shifted, of 631
no hidden layer (softmax straight from the inputs) 360 825 807 352 455
hidden layer 4 194 738 712 336 376
hidden layer 8 378 865 862 352 510
hidden layer 16 746 928 909 363 546
hidden layer 32 1482 941 927 363 564
perceptron, integer weights 360 806 777 352 425

Without a shift the difference is small: the perceptron recognises 352 of 369, the network 363. The shift is where the hidden layer is needed: 425 against 546 of 631. The template "where the dots are lit" breaks under a shift, while the hidden neurons learn features that survive it. A narrow bottleneck of 4 neurons is worse than no hidden layer at all: everything the output sees is squeezed into 4 numbers. The network with 16 neurons was chosen (epoch 55): 32 give another 18 right answers with twice as many weights. Most often the perceptron takes an 8 for a 3 (24 times), the network a 3 for an 8 (17 times).


121ж.6 On the Cortex-M0 and Cortex-M3: integers against float

The STM32F103C8 has a Cortex-M3 core without a floating-point unit, 72 MHz, 64 KB of flash and 20 KB of RAM (Keil pack STM32F1xx_DFP 2.4.1). The perceptron in C is only additions and comparisons, with no multiplications at all: a lit dot simply adds its column of weights.

    for (int i = 0; i < N_IN; i++)
        if (x[i])
            for (int c = 0; c < N_OUT; c++)
                s[c] += PW[i * N_OUT + c];

The network in float: 35 · 16 + 16 · 10 = 720 multiply-adds and 16 calls of expf. Without an FPU each operation is a call into the software library: in net_classify armclang emits calls to __aeabi_fmul, __aeabi_fadd, __aeabi_fdiv and expf, in perc_classify — not a single call and not a single multiplication.

Cross-check. Both models are exported to model121h.h. infer121h.c, built with gcc on the computer, gave on the 1000 test examples the same answers as numpy in 1000 cases of 1000 for each model; in QEMU on the Cortex-M0 and the Cortex-M3 — also 1000 of 1000.

Instructions per answer — QEMU with -icount, SysTick counts, code from arm-none-eabi-gcc -O2, the mean over 1000 examples:

Core (QEMU board) Perceptron Sigmoid network Times more
Cortex-M0 (microbit) 1576 172932 110
Cortex-M3 (netduino2) 1133 79291 70

These are instructions, not cycles: a real chip takes more cycles, so the time is a lower bound. At 72 MHz the perceptron answers no faster than in 15.7 µs, the network in 1101 µs. On the Cortex-M0 the network needs twice as many instructions: in the Thumb-1 instruction set software floating point is longer.

Bytes — armclang -Os, -mfloat-abi=soft:

Cortex-M0 Cortex-M3
perc_classify 92 bytes 112 bytes
net_classify 208 bytes 216 bytes
image with the perceptron (microlib) 624 bytes 652 bytes
image with the network (microlib) 4588 bytes 4568 bytes
library code: perceptron / network 98 / 1264 bytes 98 / 1232 bytes

The perceptron weights are 350 bytes of int8_t, the network weights W₁ and W₂ — 2240 and 640 bytes of float. The image is a main that reads 35 inputs and calls one model (sz121h.c), linked by armlink. The network costs 7 times more flash and 70 times more instructions; in return — 909 right answers instead of 777. If the shift is removed mechanically (a board on locating pins), the perceptron is enough: 352 of 369 against 363.


121ж.7 Pitfalls

The perceptron "never finishes learning". The number of errors per epoch drops from 1267 to 703 and stays there. Noisy data are not separable by straight boundaries — the perceptron rule does not converge, the last weights are random. Take the weights of the best epoch on the tuning set (epoch 17), not the last one.

Descent on a network with a step stands still. The derivative of the step is zero almost everywhere: on 275 steps of 400 the loss does not change. Training needs a smooth activation; the step can be put in after training (874 of 1000 instead of 909) if that saves cycles.

The perceptron sum overflowed. The weights fit into int8_t, but the sum of 35 weights does not: on the test set it reaches −188. The accumulator is int16_t or wider; the biases from −73 to 53 are not int8_t either.

C and Python answers differ on ties. The perceptron has 21 test examples with two equal largest sums. The selection rule must match: np.argmax takes the first one, and C takes the first one too (the comparison is strictly "greater").

The network on a Cortex-M0 is "slow". Without an FPU every float multiplication is a function call: 172932 instructions per answer. For a core without an FPU — integer weights (the perceptron or int8 from 119) or fewer neurons.

A narrow hidden layer is worse than none. 4 neurons — 712 of 1000, no hidden layer — 807. The layer size is chosen on the tuning set, as in 118.


121ж.8 Summary

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

Full sources

infer121h.c — both models in C with the weights from model121h.h.

/* Раздел 121ж: распознавание цифры по 35 точкам матричного индикатора 5 × 7 — две модели.
 * perc_classify — целочисленный перцептрон: веса int8, только сложения и сравнения.
 * net_classify  — сигмоидная сеть 35 → 16 → 10 во float: на Cortex-M0/M3 без FPU
 *                 каждое умножение и expf — вызов программной библиотеки.
 * Вход — 35 байтов 0/1, строка за строкой сверху вниз. Веса — model121h.h (train121h.py).
 * На компьютере (-DML_HOST) main сверяет ответы обеих моделей с numpy.
 * Проверка — _verify/nn121h_check.py. */
#include <math.h>
#include <stdint.h>

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

/* Перцептрон: каждая горящая точка добавляет свой столбец весов, ответ — наибольшая сумма */
int perc_classify(const uint8_t *x)
{
    int16_t s[N_OUT];
    int best = 0;
    for (int c = 0; c < N_OUT; c++)
        s[c] = PB[c];
    for (int i = 0; i < N_IN; i++)
        if (x[i])
            for (int c = 0; c < N_OUT; c++)
                s[c] += PW[i * N_OUT + c];
    for (int c = 1; c < N_OUT; c++)
        if (s[c] > s[best])
            best = c;
    return best;
}

static float sigmoidf(float a)
{
    return 1.0f / (1.0f + expf(-a));
}

/* Сигмоидная сеть: прямое распространение слой за слоем; softmax для ответа не нужен */
int net_classify(const uint8_t *x)
{
    float h[N_HID], s[N_OUT];
    int best = 0;
    for (int j = 0; j < N_HID; j++) {
        float a = B1[j];
        for (int i = 0; i < N_IN; i++)
            a += (float)x[i] * W1[i * N_HID + j];
        h[j] = sigmoidf(a);
    }
    for (int c = 0; c < N_OUT; c++) {
        float a = B2[c];
        for (int j = 0; j < N_HID; j++)
            a += h[j] * W2[j * N_OUT + c];
        s[c] = a;
    }
    for (int c = 1; c < N_OUT; c++)
        if (s[c] > s[best])
            best = c;
    return best;
}

#ifdef ML_HOST
#include <stdio.h>
int main(void)
{
    int ap = 0, an = 0, rp = 0, rn = 0;
    for (int k = 0; k < N_TEST; k++) {
        int p = perc_classify(&TEST_X[k * N_IN]), q = net_classify(&TEST_X[k * N_IN]);
        ap += p == NP_PERC[k];
        an += q == NP_NET[k];
        rp += p == TEST_Y[k];
        rn += q == TEST_Y[k];
    }
    printf("agree_perc=%d,%d\nagree_net=%d,%d\nright=%d,%d\n", ap, N_TEST, an, N_TEST, rp, rn);
    return 0;
}
#endif

Next: section 121з "Backpropagation in matrix form: four equations, the Hadamard product and why the algorithm is fast" — the series "Neural networks from the inside": four equations for a network of any depth, why the backward pass is hundreds of times cheaper than the numerical gradient and how to fine-tune a network right on the instrument.

Open in the interactive handbook