TinyML: AI on tiny chipsMiddleLesson 2776 min read

Training a tiny model

Turn each window into a few useful numbers, such as the mean and the energy, and train a small classifier. Then measure it honestly on held-out data.

Lesson in motion

In 60 seconds

Training a tiny model

Turn each window into a few useful numbers, such as the mean and the energy, and train a small classifier. Then measure it honestly on held-out data.

1/4
In simple words
A doctor does not need a whole video of you to check if you have a fever. One number, your temperature, says a lot. Features are like that: a few well-chosen numbers that sum up a whole second of sensor data, so a small model can decide quickly.
A window of 50 readings on 3 axes is 150 numbers. A tiny chip could use all of them, but a smaller input means a smaller, faster model. So we often compute a few features per window first.

Two simple, powerful features

FeatureHow to compute itWhat it tells you
Mean (per axis)The average of the readings in the windowWhich way gravity points, so how the device is tilted or lying
Energy (per axis)The average of (reading − mean)², also called the varianceHow much the device is moving or shaking
Others you may addMinimum, maximum, peaks per second, frequency featuresSpeed of a rhythm, sharp hits, steps
Python: mean and energy for a still window and a walking windowpython
import numpy as np

rng = np.random.default_rng(1)
t = np.arange(50) / 50
still = np.column_stack([rng.normal(0, 0.02, 50), rng.normal(0, 0.02, 50), 1 + rng.normal(0, 0.02, 50)])
walk = still.copy()
walk[:, 2] += 0.3 * np.sin(2 * np.pi * 1.8 * t)

def features(window):
    mean = window.mean(axis=0)                     # where gravity points
    energy = ((window - mean) ** 2).mean(axis=0)   # how much it moves
    return np.concatenate([mean, energy])

np.set_printoptions(precision=4, suppress=True)
print("still:  ", features(still))
print("walking:", features(walk))
The means are almost the same, because both windows have gravity on z. The z energy is very different, because walking moves up and down. Neither number alone separates every class, but together they often do.

Choosing a small classifier

ModelWhy it suits a tiny chipWatch out for
Decision tree (small depth)Just a few comparisons; easy to read and to write in CDeep trees overfit
Logistic regressionOne weight per feature per class; very smallOnly draws straight boundaries
Small neural networkLearns more complex patterns; well supported by TinyML runtimesNeeds more data and care
In this track we use scikit-learn in Python for the ideas. Many TinyML tools train small neural networks with other libraries and then convert them for the chip. The steps are the same: features in, labels out, test on held-out data.

Honest testing

  1. 1

    Split before training

    Keep a test set from other people or sessions, and do not look at it while you tune.
  2. 2

    Train on the training set

    Fit the model and choose settings using only training data (or a separate validation set).
  3. 3

    Test once

    Measure accuracy on the held-out test set.
  4. 4

    Read the confusion matrix

    See which classes get mixed up. That tells you what data or features to add.
Note
The labs use clean, made-up data, so scores come out very high. Real data from real people is messier. A model that scores near perfect on your first real test is a reason to check for leaks between training and test data, not to celebrate.
Watch out
Accuracy alone can hide problems. If 95% of windows are "still", a model that always says "still" gets 95% and is useless. Look at each class, and at the kinds of mistakes that matter for your use.
Real example
A college team in Coimbatore builds a band that tells a weaver's hand movements from rest, to count work cycles. The first model reaches high accuracy on their own recordings. On new weavers it fails often. The fix was not a bigger model: they recorded more people and added a feature for the rhythm of the movement.
Try this. In the lab, first use only the mean as the feature. Which classes get mixed up in the confusion matrix? Then add energy and compare.

Watch and read more

Lab

A feature function that lets a small decision tree reach 90% or more on held-out data.

~25 min

The problem

The starter makes made-up accelerometer windows for four classes: flat, tilted, walking and shaking. Training and test data come from different random seeds, so the test windows are new.

  1. Write features(window). It gets one window of shape (50, 3) and returns a short list of numbers (between 2 and 12).
  2. Start with only the mean of each axis. Run it and read the confusion matrix. Which classes get confused?
  3. Add the energy of each axis: the mean of (reading − mean)². Run again.
  4. Aim for 90% or more held-out accuracy. Write one sentence on what each feature adds.

Practice lab

Edit the code and run it. Python runs in your browser — nothing is sent to our server.

Output

No output. Add print(...) to see values.

You are done when

Hard questions

Try to answer before you reveal. If you can answer these, you understood the lesson.

Q1The mean-only model confuses "flat" with "walking" and "shaking". Why, and why does energy fix it?Reveal

All three have gravity mainly on the z axis, so their average readings are similar. What differs is movement: flat hardly changes, walking goes up and down, shaking moves a lot on all axes. Energy measures how much the readings move around their mean, so it separates them. The mean still matters for telling flat from tilted.

Q2Your features work in Python, but on the board the model predicts "shaking" for everything. What would you check?Reveal

Compare the feature numbers on the board and in Python for the same recorded window. Common causes: a different unit (raw sensor counts instead of g), a different axis order, a different window length or sampling rate, or a missing scaling step. The model must get exactly the same kind of numbers it was trained on.

Please sign in to continue.

Questions people ask

Why not feed the raw window straight into a neural network?

You can, and many TinyML projects do, especially with small convolutional networks. It needs more data and a bigger model. Features are a good first step: small, fast, and easy to understand. Try features first, then compare.

Should I compute features on the chip?

Yes, the same features must be computed on the board, in exactly the same way as in training. If your Python code and your C code compute "energy" differently, the model gets inputs it never saw. Test both on the same window and compare the numbers.

What is a confusion matrix?

A table with the true class in each row and the predicted class in each column. Numbers on the diagonal are correct; everything else shows which class was mistaken for which.

How do I know if my model is overfitting?

If training accuracy is much higher than held-out accuracy, the model learned details of the training data that do not carry over. Use a smaller model (for example a shallower tree), more varied data or fewer features.

Lesson test

5 questions. Get 3 right (60%) to pass and complete this lesson.

Sign in to take the test and save your progress