121к. Why a network can compute any function: universality by hand and a network instead of a sensor calibration table
In 121ж a network of perceptrons built an adder — any logic function. In 121з and 121и a network learned to recognise digits. Here the question is wider: which functions can a network compute at all? The answer is any continuous one, and this can be seen without theorems: a pair of sigmoid neurons makes a "bump", bumps make any curve, bumps along two axes make "towers" over a plane. We count how many neurons that takes, look at what this promise gives and what it does not, and why in practice networks are made deep. The second half is practice: converting the ADC code of a thermistor to degrees in four ways at the same accuracy — a table (76.3, 96.3), a polynomial, a piecewise linear function and a small network — measuring bytes and instructions on a Cortex-M4F.
Sources: numpy 2.3.3 in the stm-ml:1 image, the script train121k.py — all
experiments, a repeated run gives the same files. The functions g(x) and g(x, y) for
the experiments with bumps are our own, made up for clarity. The thermistor is
a model: the Steinhart–Hart equation 1/T = A + B·ln R + C·(ln R)³
with coefficients A = 1.1266·10⁻³, B = 2.3336·10⁻⁴, C = 1.0·10⁻⁷,
chosen to agree at 25 and 85 °C with the formula
with B = 3950 from 96.2 — these are not the data of a particular thermistor from
a datasheet. The circuit is as in 96.2: 10 kΩ to the supply, the thermistor
to ground, 12 bits. The answer in C: gcc 12.2.0 (stm-sys:1) for comparison,
arm-none-eabi-gcc 12.2.1 and QEMU 7.2 (stm-arm:1, the netduinoplus2 board
with an STM32F405 — the same Cortex-M4F core as the F407) — instruction counts,
armclang 6.24 — bytes.
Terms used in the documentation
Term Meaning universal approximation theorem one hidden layer approximates any continuous function bump the difference of two steps: one on an interval and zero outside it tower function a bump over a cell of the plane steepness the factor in front of the input; it decides how much the sigmoid looks like a step maximum (uniform) error the largest error over the whole domain — what a sensor guarantees depth efficiency a function that needs few neurons in a deep network and exponentially many in a shallow one Horner's scheme a polynomial as a chain of "multiply and add" Chebyshev fit fitting a polynomial on the Chebyshev basis: the error is spread more evenly than with plain powers Levenberg–Marquardt training a small network on the whole set at once, between Newton's method and descent lookup table, LUT a table of values that is searched rather than computed
121к.1 A step and a bump: what a function is built from
A sigmoid neuron with one input σ(w·x + b) goes from zero to one near the point x = −b/w, and the larger the weight w, the steeper the transition. With w in the thousands the transition takes thousandths of the interval — that is already a step at the point a = −b/w, and it is convenient to think of the neuron as "switching on at a".
Two such neurons with the same steepness and thresholds a < b, added with weights +h and −h at the output, give a bump: zero left of a, h between a and b, zero right of b. The output weight is the height of the bump, the thresholds of the hidden neurons are its edges:
y += hk * (sig(w * (x - a)) - sig(w * (x - b))) # столбик: ступенька вверх в a, вниз в b
Put the bumps side by side: split [0, 1] into N equal parts, on each one a bump with the height of g in the middle of the part. The sum is a staircase curve that follows g the more closely, the narrower the steps. A hidden layer of 2N neurons, the output is one linear sum: an ordinary 1 → 2N → 1 network whose weights are written out by hand, without training.
121к.2 A sum of bumps: number of neurons against error
The function g(x) = 0.5 + 0.3·sin 6x + 0.1·cos 17x on [0, 1] varies from 0.173 to 0.855, its steepest slope is 3.39 per unit of x. The error is the largest over 100001 points, steepness w = 10000:
| Bumps N | 2 | 5 | 10 | 20 | 50 | 100 | 200 |
|---|---|---|---|---|---|---|---|
| hidden neurons | 4 | 10 | 20 | 40 | 100 | 200 | 400 |
| largest error | 0.2699 | 0.3056 | 0.1639 | 0.0818 | 0.0330 | 0.0167 | 0.0084 |
From ten bumps on, the error is exactly halved when N is doubled. That is as it should be: a bump of width 1/N is off by no more than the slope of g times half the width — 3.39/(2N), at N = 200 that is 0.0085. With two and five bumps the rule does not work yet — the error depends on where the midpoints of the parts fall: at N = 5 the peak of g landed between them, and the result was worse than at N = 2.
Steepness is needed, but in moderation. The same 20 bumps:
| Steepness w | 10 | 30 | 100 | 1000 | 10000 |
|---|---|---|---|---|---|
| largest error | 0.1916 | 0.0999 | 0.0800 | 0.0793 | 0.0818 |
At w = 10 the transition is smeared over the whole width of a bump (1/20), and the "bumps" are no longer bumps. From w ≈ 100 on, the error is decided by the width, not the steepness; slightly smoothed edges even help a little — 0.0793 against 0.0818.
An important caveat: bumps are a proof, not a recipe. A 1 → 4 → 1 network trained with the Levenberg–Marquardt method (the best of 5 starting points) approximates the same g with an error of 0.02953 — almost three times better than 40 neurons built from bumps. A 1 → 10 → 1 network gives 0.00001. Trained neurons do not set up steps: they add up gentle pieces of sigmoids, and each neuron works over the whole domain at once.
121к.3 Two variables: towers
For a function of two variables a bump in x is "on" in one strip, a bump in y in another strip. Their sum equals 2 only where the strips cross — in a cell; elsewhere it is 1 or 0. A second-layer neuron with threshold 1.5 and high steepness keeps only the cell — that is a tower:
out += g2(c[i], c[j]) * sig(w * (bx[i] + by[j] - 1.5)) # башня: горит, только если горят оба столбика
Split the square [0, 1]² into m × m cells, over each a tower with the height of g(x, y) at its centre. The function g(x, y) = 0.5 + 0.25·sin 4x·cos 3y + 0.15·xy, the error is the largest over a 400 × 400 grid:
| Cells per side m | 2 | 5 | 10 | 20 |
|---|---|---|---|---|
| first-layer neurons (bumps) | 8 | 20 | 40 | 80 |
| second-layer neurons (towers) | 4 | 25 | 100 | 400 |
| largest error | 0.2738 | 0.1145 | 0.0607 | 0.0300 |
The error halves when m doubles, as in one dimension, but the number of towers grows as m². In three variables there would be cubes and m³, in ten — m¹⁰. The construction still proves "it can be done", but it takes as many neurons as there are cells in a table. A network that is trained rather than built suffers less from this — this is seen in 121к.6.
121к.4 What the theorem promises and what it does not
Stated strictly: for any continuous function on a bounded closed domain and any accuracy ε there exists a network with one hidden layer whose error is everywhere smaller than ε. Almost any nonlinear activation works, not only the sigmoid. Bumps and towers are a sketch of the proof. Now — what is not in this sentence.
How many neurons. The theorem says "there exists", not "how many". The construction of 121к.3 gives m² neurons for two variables, mᵈ for d. How many are really needed depends on the function.
That training will find these weights. The 1 → 6 → 1 network for the thermistor (121к.6) was trained with the Levenberg–Marquardt method from five starting points: the largest error was 0.080, 0.198, 0.114, 0.358 and 0.221 °C. The same network, the same data — a difference of 4.5 times. The same network trained with Adam (step 0.01, 20000 epochs over the whole set) stopped at 1.228 °C. Weights giving 0.08 °C exist; finding them is a separate problem, and the theorem says nothing about it.
That the network will cope with new examples. The theorem speaks about a function known everywhere. If only points are known, a network can pass through them exactly and still behave arbitrarily between them and beyond the edges. This is the overfitting of 116б and 121и; universality does not protect against it, rather the opposite: the more a network can do, the easier it is to learn the noise.
That the function is continuous. A discontinuity — for example a broken sensor
wire, when the code jumps to the end of the scale — the network will smooth into a steep but
continuous transition. Such cases are handled before the network with an ordinary if.
121к.5 Why depth is used in practice
One layer can do everything — but it may have to be very wide. An example where the difference is seen exactly: the "tent" t(x) = 2·relu(x) − 4·relu(x − 0.5) on [0, 1] — up to 1 in the middle and down to 0. Applying it k times in a row means stacking k layers of 2 ReLU neurons:
x = 2 * relu(x) - 4 * relu(x - 0.5)
Each layer doubles the number of teeth. A network with one hidden layer of N ReLU neurons gives a piecewise linear function of no more than N + 1 pieces, so it needs at least "pieces minus one" neurons:
| Layers k | 2 | 4 | 6 | 10 |
|---|---|---|---|---|
| neurons in the deep network | 4 | 8 | 12 | 20 |
| linear pieces (counted) | 4 | 16 | 64 | 1024 |
| neurons in one layer, at least | 3 | 15 | 63 | 1023 |
A shallow sigmoid network on the four-fold tent (16 pieces, range 1), trained by Levenberg–Marquardt (the best of three starting points): 8 neurons — largest error 0.548, 16 — 0.108, 32 — 0.103. The deep network of 8 neurons does it exactly.
This is an extreme example, but the idea is general: a deep network reuses what earlier layers have computed — edges, then shapes from edges, then objects from shapes. A shallow network has to write out every combination with separate neurons. Depth is paid for in training — the gradient through many layers vanishes or explodes; that is the next section of the series.
121к.6 Practice: a network instead of a thermistor calibration table
The task from 96.3: a 12-bit ADC code → °C. Over −40…+125 °C the model thermistor gives codes from 138 to 3971 — 3834 codes. The single-B model from 96.2 differs from the Steinhart–Hart equation by up to 3.14 °C — that is why the curve is approximated. The goal for all methods is the same: the largest error no more than 0.1 °C on every one of the 3834 codes against the equation in double.
A table (as in 76.3, but the step is a power of two, and the segment number is found by a shift, without a search): a step of 128 codes — 31 points and 2.3129 °C, 64 — 61 points and 0.8027, 32 — 121 and 0.2446, 16 — 241 points and 0.0684 °C.
A polynomial in the code, coefficients fitted on the Chebyshev basis, evaluated by Horner in float32: degree 4 — 12.003 °C, 8 — 2.193, 12 — 0.430, 16 — 0.0866. The thermistor curve near the ends of the scale is too steep for a polynomial in the code: it takes degree 16, 17 coefficients.
Piecewise linear with unequal segments: each segment is greedily stretched until the error inside it exceeds 0.095 °C. 31 points were enough — where the curve is straighter, the segments are longer.
A 1 → N → 1 network with a sigmoid: the input is the code scaled to [−1, 1], the output is (T − 42.5)/82.5. Training by Levenberg–Marquardt, the best of 5 starting points, the error is after converting the weights to float32:
| Hidden neurons N | 2 | 3 | 4 | 5 | 6 | 8 |
|---|---|---|---|---|---|---|
| weights | 7 | 10 | 13 | 16 | 19 | 25 |
| largest error, °C | 7.538 | 2.092 | 0.572 | 0.192 | 0.080 | 0.005 |
Six neurons are enough: 19 numbers. On the instrument it is the forward pass
of 121ж with six expf calls:
float t_net(uint16_t code)
{
float u = ((float)code - POLY_U0) * POLY_US, y = NET_D;
for (int j = 0; j < NET_N; j++)
y += NET_V[j] / (1.0f + expf(-(NET_W[j] * u + NET_B[j])));
return y * NET_YS + NET_Y0;
}
All five functions (the fifth is the equation itself through logf) went through all codes
on the computer and in QEMU; the errors matched to a ten-thousandth of a degree.
Instructions — QEMU netduinoplus2 with -icount, arm-none-eabi-gcc -O2
with FPU, the average per code; flash memory — armclang -Os: the code of the function together
with its table or weights:
| Method | Numbers | Flash, bytes | Instructions | At 168 MHz, at best | Largest error, °C |
|---|---|---|---|---|---|
| table every 16 codes | 241 | 1032 | 19 | 0.11 µs | 0.0684 |
| polynomial of degree 16 | 17 | 144 | 96 | 0.57 µs | 0.0866 |
| piecewise linear, 31 points | 92 | 410 | 85 | 0.51 µs | 0.0949 |
| network 1 → 6 → 1 | 19 | 216 + expf |
533 | 3.17 µs | 0.0799 |
equation through logf |
3 | 112 + logf |
104 | 0.62 µs | 0.0001 |
expf and logf from newlib (arm-none-eabi-gcc) take 600 and 616 bytes.
None of the methods needs static RAM: tables and weights are const.
Conclusion for one variable. The network turned out to be the slowest:
28 times slower than the table and 5.6 times slower than the polynomial. In memory it is
compact, but not more compact than the polynomial, and expf (600 bytes) is almost
three times larger than the function with its weights. The table is the fastest and
the easiest to verify: the error between points can be seen by eye. And if
the formula of the sensor is known, the simplest thing is to compute it directly: 104 instructions,
an error of 0.0001 °C.
Where a network makes sense. When there is more than one input: a pressure sensor with temperature compensation, a gas sensor with humidity, a thermocouple with a cold junction. A table grows as mᵈ, a network does not have to. On the function g(x, y) of 121к.3 an m × m table with bilinear interpolation: 5 × 5 — 25 numbers and 0.0429, 9 × 9 — 81 and 0.0116, 17 × 17 — 289 and 0.0030, 33 × 33 — 1089 numbers and 0.0008. A 2 → N → 1 network (Levenberg–Marquardt, the best of three starting points): N = 4 — 17 weights and 0.0195, 6 — 25 and 0.0107, 8 — 33 weights and 0.0009, 12 — 49 and 0.0005. At an error of about one thousandth the network needs 33 times fewer numbers than the table. And the second case: when there is no formula, only the calibration points of a particular instrument — a network gives a smooth curve through them, but it still has to be checked on every code, as here.
121к.7 Pitfalls
Outer bumps at the boundary. If the first bump starts exactly at 0 and the last ends exactly at 1, then at the edges the sigmoid equals one half, and the sum is half of what is needed. In the first run the error did not fall with N because of this. The outer steps are moved beyond the edges of the domain.
The corner of a cell with towers. At the point where four cells meet, both bumps equal one half, the sum is 1, and the threshold 1.5 is not passed by any tower: at m = 2 the output in the centre of the square is 0.000 instead of 0.554. The dip is narrow — the 400 × 400 grid in the experiment misses it — but it is there.
Training did not find the weights. A 1 → 6 → 1 network, Adam: 1.228 °C, although the same network can do 0.080. For small networks on the whole set a second-order method (Levenberg–Marquardt) is better than descent; and always — several starting points.
The error in float64 and in float32 differs. The coefficients of a high-degree polynomial and the network weights are no longer the same after conversion to float32; so all errors here are computed after conversion and checked in C — both on the computer and in QEMU.
Mean error instead of the largest. Training reduces the mean square, while the instrument cares about the largest error on any code. So the finished function is checked by going through all codes, as here.
121к.8 Summary
- A bump is two sigmoid neurons; N bumps approximate a function of one variable with an error of about slope/(2N): with 40 neurons 0.0818, with 400 — 0.0084.
- Towers give the same on the plane, but with m² neurons: at m = 20 — 400 towers and an error of 0.0300.
- The theorem does not say how many neurons, does not promise that training will find the weights (Adam — 1.228 °C, Levenberg–Marquardt — 0.080), and says nothing about new examples.
- Depth: 10 layers of 2 ReLU neurons give 1024 pieces; one layer needs at least 1023 neurons.
- Thermistor at 0.1 °C: the table — 241 points, 1032 bytes, 19 instructions;
a degree-16 polynomial — 144 bytes, 96 instructions; piecewise linear —
31 points, 410 bytes, 85 instructions; the 1 → 6 → 1 network — 216 bytes and
expf, 533 instructions. - For one variable the network loses to the table; with two inputs at an error of about one thousandth it needs 33 weights against 1089 table numbers.
Further reading: Michael Nielsen, Neural Networks and Deep Learning, neuralnetworksanddeeplearning.com.
Full sources
ntc121k.c — five ways to convert the thermistor ADC code to °C in C with tables and weights from model121k.h.
/* Раздел 121к: код АЦП термистора → °C пятью способами при одной точности 0,1 °C.
* t_lut — таблица через 2^LUT_SH кодов и линейная интерполяция (76.3, 96.3).
* t_poly — полином по коду, счёт Горнером.
* t_pwl — кусочно-линейная с неравными отрезками: двоичный поиск и готовый наклон.
* t_net — сеть 1 → NET_N → 1 с сигмоидой, обученная numpy.
* t_formula — само уравнение Стейнхарта — Харта через logf.
* Код — от NTC_C0 до NTC_C1 (−40…+125 °C). Таблицы и веса — model121k.h (train121k.py).
* На компьютере (-DML_HOST) main сравнивает каждый способ с формулой в double на всех кодах.
* Проверка — _verify/nn121k_check.py. */
#include <math.h>
#include <stdint.h>
#include "model121k.h"
float t_lut(uint16_t code)
{
unsigned d = code - NTC_C0, k = d >> LUT_SH;
float fr = (float)(d & ((1u << LUT_SH) - 1u)) * (1.0f / (1u << LUT_SH));
return LUT_T[k] + (LUT_T[k + 1] - LUT_T[k]) * fr;
}
float t_poly(uint16_t code)
{
float u = ((float)code - POLY_U0) * POLY_US, y = POLY_C[POLY_N - 1];
for (int i = POLY_N - 2; i >= 0; i--)
y = y * u + POLY_C[i];
return y;
}
float t_pwl(uint16_t code)
{
int lo = 0, hi = PWL_N - 1;
while (hi - lo > 1) {
int mid = (lo + hi) / 2;
if (PWL_C[mid] <= code)
lo = mid;
else
hi = mid;
}
return PWL_T[lo] + PWL_K[lo] * (float)(code - PWL_C[lo]);
}
float t_net(uint16_t code)
{
float u = ((float)code - POLY_U0) * POLY_US, y = NET_D;
for (int j = 0; j < NET_N; j++)
y += NET_V[j] / (1.0f + expf(-(NET_W[j] * u + NET_B[j])));
return y * NET_YS + NET_Y0;
}
float t_formula(uint16_t code)
{
float l = logf(10000.0f * (float)code / (4095.0f - (float)code));
return 1.0f / ((float)SH_A + (float)SH_B * l + (float)SH_C * l * l * l) - 273.15f;
}
double t_exact(uint16_t code)
{
double l = log(10000.0 * code / (4095.0 - code));
return 1.0 / (SH_A + SH_B * l + SH_C * l * l * l) - 273.15;
}
#ifdef ML_HOST
#include <stdio.h>
int main(void)
{
float (*fn[5])(uint16_t) = {t_lut, t_poly, t_pwl, t_net, t_formula};
const char *name[5] = {"lut", "poly", "pwl", "net", "formula"};
for (int f = 0; f < 5; f++) {
double e = 0.0;
for (unsigned c = NTC_C0; c <= NTC_C1; c++)
e = fmax(e, fabs(fn[f]((uint16_t)c) - t_exact((uint16_t)c)));
printf("err_%s=%.4f\n", name[f], e);
}
return 0;
}
#endif
Next: section 121л "Why deep networks are hard to train: vanishing and exploding gradients, ReLU, normalization, residual connections" — the series "Neural networks from the inside": why the gradient weakens from layer to layer, how norm clipping tames its explosion, why ReLU beats the sigmoid and where its dead neurons come from, how to fold batch normalization into the weights and why residual connections help — and what all of it costs on a Cortex-M4.