Professional Documents
Culture Documents
Search Medium
Listen Share
TinyML is a sub-field of Machine Learning that studies the way to run ML models on small and
low-powered devices.
In this article, I will show an easy way to get started with TinyML: implementing a Machine
Learning model on an Arduino board while creating something cool: a gesture recognition
system based on an accelerometer.
Gesture recognition is a process that attempts to recognize human gestures through the use of
mathematical algorithms.
To make the experiment simpler, the system is designed to recognize only two gestures: a punch
and a flex movement.
This, in the data science field, is called binary classification.
The biggest challenge of this experiment is trying to run the prediction model on a very tiny
device: an 8-bit microcontroller.
To achieve this, you can use Neuton.
Neuton is a TinyML framework. It allows to automatically build neural networks without any
coding and with little machine learning experience and embed them into small compute
devices.
It supports 8, 16, and 32-bit microcontrollers, unlike TensorFlow Lite TinyML framework which
only supports 32-bit. You don’t need a powerful machine to use Neuton, it is an online software
tool which runs on a web browser.
Using the free plan, you can train and download an unlimited number of models.
…Let’s start!
Arduino Mega 2560 is a microcontroller board based on the ATmega2560: a low-power 8-bit
MCU with 256KB flash memory, 32 general purpose working registers, UART interfaces, 10-bit
A/D converter, and many other peripherals.
Mega 2560 board is designed for complex projects: it has a larger space than other Arduino
boards (Uno, Nano, Micro, etc.). This makes it ideal for machine learning applications where
there are large amounts of data to process.
The GY-521 module is built around the InvenSense MPU-6050: a sensor containing, in a single IC,
a 3-axis MEMS accelerometer and 3-axis MEMS gyroscope.
Its operation is very precise since it contains for each channel an accurate digital converter. It is
able to capture the values of the X, Y and Z axes at the same time. Communication with MCU
takes place using the I2C interface.
To verify if the GY-521 module is correctly supplied, connect the USB cable of the Arduino board
and check if the LED mounted on the sensor board is turning on.
After verifying the sensor power supply, check if the I2C communication is working properly by
downloading the Adafruit MPU6050 Arduino library and opening the “plotter” example.
Upload the example sketch on the Arduino board, open the “Serial Plotter” within the Tools menu,
set 115200 in the baud drop-down menu and “shake” the sensor board. The expected result will
be the following:
Serial Plotter of MPU6050 plotter example. Image by author.
The easiest way to achieve this is to repeat several times the same two motions (punch and flex),
by capturing acceleration and gyroscope measurements and storing the result in a file.
To do this, you create an Arduino sketch dedicated to sensor data acquisition. The program will
acquire the measurements of each motion and will print the sensor measurements output on
the serial port console.
You will perform at least 60 motions: 30 for the first movement (punch) and 30 for the second
one (flex). For each motion, you will acquire 50 acceleration and 50 gyroscope measures in a 1
second time window (Sampling time: 20ms —50Hz). In this experiment, 60 motions are enough.
By increasing the number of motion measurements, you can improve the predictive power of
the model. However, a large dataset can lead to an over-fitted model. There is no “correct” dataset
size, but a “trial and error” approach is recommended.
The serial port output of the Arduino sketch will be formatted according to Neuton training
dataset requirements:
CSV format: it is a database file format. Each line of the file is a data record consisting of one
or more fields, separated by commas.
At least 50 data records (for binary classification task means at least 25 data records per
group).
First row must contain the column names (e.g., ax0, ay0, az0, gx0, gy0, gz0, …).
A target variable column must be present. Each row must be assigned to a specific target
group (in this experiment: ‘0’ for punch, ‘1’ for flex).
#define NUM_SAMPLES 50
Adafruit_MPU6050 mpu;
void setup() {
// init serial port
Serial.begin(115200);
while (!Serial) {
delay(10);
}
// init IMU sensor
if (!mpu.begin()) {
while (1) {
delay(10);
}
}
#define NUM_GESTURES 30
#define GESTURE_0 0
#define GESTURE_1 1
#define GESTURE_TARGET GESTURE_0
//#define GESTURE_TARGET GESTURE_1
void loop() {
sensors_event_t a, g, temp;
samplesRead++;
delay(10);
}
gesturesRead++;
}
}
Firstly, run the above sketch with the serial monitor opened and GESTURE_TARGET set to
GESTURE_0. Then, run with GESTURE_TARGET set to GESTURE_1. For each execution, perform
the same motion 30 times, ensuring, as far as possible, that the motion is performed in the same
way.
Copy the serial monitor output of the two motions in a text file and rename it to
“trainingdata.csv”.
The process of training a model involves providing a Machine Learning algorithm with training data to
learn from. It is the phase where you try to fit the best combination of weights and bias to a ML
algorithm to minimize a loss function.
Neuton performs training automatically and without any user interaction.
Train a Neural Network with Neuton is quick and easy and is divided into three phases:
2. Training: Auto ML
If the CSV file meets the requirements a green check will appear, otherwise an error
message will be shown.
Neuton: validated dataset. Image by author.
Select the column name of the target variable (e.g., target) and click “Next”.
Training: Auto ML
Now, let’s get to the heart of training!
Neuton analyzes the content of the training dataset and defines the ML task type. With this
dataset, the binary classification task is automatically detected.
Enable TinyML option to allow Neuton to build a tiny model for microcontroller.
In the TinyML settings page, select “8-bit” in the drop-down menu and enable “Float
datatype support” option. This, because the microcontroller used in the experiment is an 8-
bit MCU with floating point number support.
Neuton: TinyML settings. Image by author.
After pressing the “Start Training” button, you will see the process progress bar and the
percentage of completion.
The first step is the data preprocessing. It is the process of preparing (cleaning, organizing,
transforming, etc.) the raw dataset to make it suitable for training and building ML models.
After data preprocessing completion, model training starts. Process can take a long time;
you can close the window and come back when the process is finished. During training you
can monitor the real-time model performance by observing model status (“consistent” or “not
consistent”) and Target metric value.
Upon training is complete, the “Status” will change to “Training completed”. Model is
consistent and has reached the best predictive power.
Neuton: Training completed. Image by author.
After the training procedure is completed, you will be redirected to the «Prediction» section.
In this experiment, the model has reached an accuracy of 98%. It means that from 100 predicted
records, 98 had been assigned to the correct class… that’s impressive!
Moreover, the size of the model to embed is less than 3KB.
This is a very small size, considering that the Arduino board in use is 256KB memory size and a
typical memory size for an 8-bit microcontroller is 64KB÷256KB.
The model archive downloaded from Neuton includes the following files and folders:
/model: the neural network model in a compact form (HEX and binary).
/neuton: a set of functions used to perform predictions, calculation, data transferring, result
management, etc.
user_app.c: a file in which you can set the logic of your application to manage the
predictions.
First, you modify the user_app.c file adding functions to initialize model and run inference.
/*
* Function: model_init
* ----------------------------
*
* returns: result of initialization (bool)
*/
uint8_t model_init() {
uint8_t res;
if (size_in != neuralNet.inputsDim)
return NULL;
*size_out = neuralNet.outputsDim;
After that, you create the user_app.h header file to allow the main application using the user
functions.
uint8_t model_init();
float* model_run_inference(float* sample,
uint32_t size_in,
uint32_t* size_out);
Model initialization
samplesRead++;
delay(10);
// check the end of gesture acquisition
if (samplesRead == NUM_SAMPLES) {
uint32_t size_out = 0;
Model in action!
Project and code are ready!
/neuton_gesturerecognition
|- /src
| |- /Gesture Recognition_v1
| |- /model
| |- /neuton
| |- user_app.c
| |- user_app.h
|- neuton_gesturerecognition.ino
Grab your hardware system in the hand and perform some motions.
For each detected motion, the model will try to guess what type of movement is (0-punch or 1-
flex) and how accurate the prediction is. If the accuracy of the prediction is low (0.5), the model
does not make a decision.
…Already done?
Doing Machine learning with Neuton is simple and fast. Model accuracy and performance
achieved on a low-power 8-bit microcontroller are impressive!
Neuton is suitable for fast-prototyping development. It allows user to focus on the application,
avoiding wasting time in complex and manual statistical analysis.
Here, you can find all Arduino sketches described in this article!
Follow
555 5
Dominik Polzer in Towards Data Science
4K 38
Kenneth Leung in Towards Data Science
1.92K 25
Leonardo Cavagnis
134
Simsangcheol
ONNX
ONNX (Open Neural Network Exchange) is an open-source format for representing machine learning
models. It was developed by Microsoft and…
3
Sheeza Shabbir
Lists
14
Juan F. Palomeque-Gonzalez
15
Denaya