Features for TinyML
Windows, RMS and band energy, Goertzel, normalisation and a nearest-centroid classifier.
Features first, model second
A model on a microcontroller rarely sees raw samples. One second of accelerometer data at 1 kHz is 3000 numbers, too many for a tiny network and full of noise that has nothing to do with the answer. Instead, firmware cuts the signal into windows, computes a handful of features per window (energy, peaks, the strength of certain frequencies), and gives those to the model. Good features make a small model accurate; bad ones make no model good enough. On a microcontroller, feature extraction often takes more CPU time than the inference itself.
Windows
Samples arrive continuously, so the firmware groups them:
- Window length: long enough to contain the pattern (one gesture, one machine cycle, a spoken word), typically 0.5 to 2 seconds.
- Hop (stride): how far the next window starts after this one. A 50 % overlap catches events that straddle a boundary, at twice the compute cost.
- A ring buffer filled by DMA or an ISR holds the samples, and a task processes each complete window.
Common features
| Feature | Computed as | Tells you |
|---|---|---|
| Mean | Sum / N | Offset, orientation (gravity on an accelerometer) |
| RMS | √(Σx² / N), after removing the mean | Overall vibration or loudness |
| Peak-to-peak | max − min | Shocks, impacts |
| Zero-crossing rate | Sign changes per window | A rough dominant frequency |
| Band energy | Energy near chosen frequencies (FFT bins or the Goertzel algorithm) | Which machine fault, which tone, which vowel |
| Spectrogram / MFCCs | Many FFT frames, mel-scaled | The standard input for keyword spotting |
When only a few frequencies matter, the Goertzel algorithm measures the energy at one frequency with one multiply and two additions per sample, much cheaper than a whole FFT.
A complete pipeline in C
This detects a bearing fault on a motor: a healthy motor vibrates at 50 Hz, a damaged bearing adds a component at 180 Hz. The "model" is a nearest-centroid classifier: the average feature vector of each class, from training data, and each new window is labelled with the closest one.
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#define FS 1000.0 /* sample rate, Hz */
#define N 200 /* window: 0.2 s */
#define PI 3.14159265358979
static uint32_t seed = 12345;
static double noise(void) { /* small pseudo-random noise, -0.1..0.1 */
seed = seed * 1103515245u + 12345u;
return ((double)((seed >> 16) & 0x7FFF) / 32767.0 - 0.5) * 0.2;
}
/* Make one window of vibration; fault adds a 180 Hz component. */
static void capture(double *x, int fault) {
for (int i = 0; i < N; i++) {
double t = i / FS;
x[i] = sin(2 * PI * 50 * t) + noise();
if (fault) x[i] += 0.6 * sin(2 * PI * 180 * t);
}
}
/* Goertzel: energy of one frequency in the window. */
static double band_energy(const double *x, double freq) {
double k = 2 * cos(2 * PI * freq / FS), s1 = 0, s2 = 0;
for (int i = 0; i < N; i++) { double s0 = x[i] + k * s1 - s2; s2 = s1; s1 = s0; }
return (s1 * s1 + s2 * s2 - k * s1 * s2) / (N * N / 4.0); /* scaled: amplitude squared */
}
typedef struct { double rms, e180; } features_t;
static features_t extract(const double *x) {
double mean = 0, sq = 0;
for (int i = 0; i < N; i++) mean += x[i];
mean /= N;
for (int i = 0; i < N; i++) sq += (x[i] - mean) * (x[i] - mean);
features_t f = { sqrt(sq / N), band_energy(x, 180) };
return f;
}
/* Centroids learned offline from labelled windows (rms, 180 Hz energy). */
static const features_t centroid[2] = { { 0.71, 0.00 }, { 0.83, 0.36 } };
static const char *label[2] = { "healthy", "BEARING FAULT" };
static int classify(features_t f) {
int best = 0; double best_d = 1e9;
for (int c = 0; c < 2; c++) {
double dr = f.rms - centroid[c].rms, de = f.e180 - centroid[c].e180;
double d = dr * dr + de * de;
if (d < best_d) { best_d = d; best = c; }
}
return best;
}
int main(void) {
double x[N];
const int truth[] = { 0, 0, 1, 0, 1, 1 };
for (int w = 0; w < 6; w++) {
capture(x, truth[w]);
features_t f = extract(x);
printf("window %d: rms %.2f, energy at 180 Hz %.3f -> %s\n",
w, f.rms, f.e180, label[classify(f)]);
}
return 0;
}
Notice that RMS alone separates the classes poorly (0.71 against 0.83, and real noise and load changes would blur that), while the 180 Hz energy separates them clearly. Choosing that feature is the domain knowledge; the classifier is trivial. With features this good, a neural network may not be needed at all.
Normalise like the training did
Features have different scales: RMS around 1, a band energy around 0.001, a temperature around 40. A model trained on normalised features (each one shifted and scaled, usually to mean 0 and standard deviation 1) must receive exactly the same normalisation on the device, using the mean and standard deviation from the training data, stored as constants in the firmware. Getting this wrong is the most common reason a model that scored 98 % on the laptop guesses randomly on the board.
The same applies to everything before the model: sample rate, filter, window length, units (g or m/s², raw ADC counts or volts), and the axis order of the sensor. Ideally the feature code is the same C code in the training pipeline and the firmware, or tested against it with recorded data.
From features to a model
| Approach | Size | When |
|---|---|---|
| Thresholds on one feature | Bytes | One feature clearly separates the classes |
| Nearest centroid, decision tree | Hundreds of bytes | A few features, a few classes, explainable results |
| Small dense network on features | A few KB | Several features with non-linear boundaries |
| Convolutional network on a spectrogram | 20 to 200 KB | Keyword spotting, complex audio or image patterns |
Start at the top of the table and move down only when the simpler approach measurably fails.
Pitfall: Training data recorded on one device, in one place, does not cover the field. Mounting, temperature, a different motor or a different microphone shift the features. Collect data from several devices and conditions, and keep a test set that the model never trained on.
Interview question: How would you design anomaly detection for a vibrating machine on a microcontroller?
Answer: I would sample the accelerometer with a timer or DMA into a ring buffer, process overlapping windows of around a second, and compute features chosen with the domain in mind: RMS, peak-to-peak, and energy in the frequency bands where faults appear, such as bearing frequencies or multiples of the running speed. Because faults are rare, I would train on healthy data only, for example learning the normal range or clusters of the features, and flag windows that fall far outside. The device reports features and alarms rather than raw data, which saves bandwidth and power. I would validate across machines, loads and temperatures.
Build it: features exactly as the model was trained on
This is step 2, the last of the module project. The gesture remote's model (step 1) never sees raw accelerometer samples: it was trained on three features of each half-second window of the X axis, normalised with the training data's means and standard deviations, then quantised to int8. The firmware has to produce the same numbers from the same window, in integers, or the model that scored 97% on the laptop guesses.
Lab: Window features, normalised and quantised like the training
features(x, n, f) computes, for a window of n samples in mg:
f[0], the RMS about the mean: with the integer meanm = sum / n(C division),isqrt(Σ (x − m)² / n), the integer square root rounded down;f[1], the zero crossings: how many times the sign ofx − mchanges from one sample to the next, counting a sample equal tomas positive;f[2], the peak to peak: largest minus smallest sample.
model_input(f, q) normalises each feature with the training constants and quantises it into the model's int8 input, whose scale is 1/32 of a standard deviation and zero point 0: q = round((f − MEAN) × 32 / STD), rounding halves away from zero, saturated to −128 … 127.
Use 64 bits for the sum of squares.
Going deeper
Interview question: How would you detect breaking glass on a doorbell's microphone with a tiny model?
Answer: Compute compact features from short windows of audio, such as log-mel spectrograms, in fixed point, and feed them to a small quantised neural network. Train it on many recordings of glass and of everyday sounds that could be confused with it, measure false alarms per day as carefully as detections, and run it only when a cheap energy detector sees a loud event.
Interview question: Why is feature extraction often the bigger cost on a microcontroller, not the model?
Answer: Features run on every sample or every window: filtering, an FFT or MFCC computation per frame, and buffering, often hundreds of times per second. A small model on a few dozen features is only a few thousand multiply-accumulates per inference. Optimising feature extraction with fixed-point arithmetic, CMSIS-DSP functions, Goertzel instead of a full FFT, and windows with sensible overlap often saves more time and energy than shrinking the model.
Interview question: What is the difference between classification and anomaly detection, and when do you need the second?
Answer: Classification assigns each input to one of several known classes and needs labelled examples of every class. Anomaly detection learns only what normal looks like and flags inputs that differ from it. It is needed when the abnormal cases are rare, varied or unknown in advance, as with machine faults, where you cannot collect examples of every failure but have plenty of healthy data.
Explain it: In your own words, explain why a TinyML model is usually given features rather than raw samples.
Answer: Raw samples are many numbers, mostly noise and details that do not matter for the answer, so a model working on them must be large, which a microcontroller cannot afford. Features such as the RMS, peak values and the energy at important frequencies condense a window of samples into a few numbers that describe what matters. A tiny model, or even a simple threshold or nearest-centroid rule, can then decide accurately. The features must be computed exactly the same way on the device as during training.