Running Machine Learning on your Arduino board (a.k.a TinyML) can seem like an advanced topic meant for experienced programmers.
It is actually much easier than you think!
You don't have to either master machine learning nor C++ to successfully train, convert and deploy a machine learning model to your Arduino board starting from scratch.
In this post, I'll show you how to do it step by step.
What is TinyML?
TinyML is machine learning aimed at embedded devices.
It actually covers a wide range of devices (from microcontrollers to Raspberry Pis and smartphones), but in the context of this post we'll focus on microcontrollers with limited resources.
TinyML job is to learn a classification / prediction pattern from training data and use the generated model to classify / predict unseen data. Due to the resources constraints of our target devices, not all machine learning algorithms are suitable for TinyML.
If you already read a few tutorials online, you may have the idea that TinyML = TensorFlow for Microcontrollers.
Wrong.
TensorFlow is arguably on the boundary of TinyML and standard machine learning because of its complexity and huge resource consumption. I'll show you what truly TinyML means.
Truly TinyML™ for Arduino
To train a TinyML model, we will make use of Python and the everywhereml package, which is a wrapper around the well-known scikit-learn package.
In a real project, you will have a dataset you want to learn from. In this short example, I will use the IRIS toy dataset. All the training and exporting code will remain valid when you'll plug your own data into the script.
I chose Random Forest classifier in the example below because it's fast and accurate (it's my personal default for new TinyML projects)
First of all, install the everywhereml
package.
pip install everywhereml
Then create a new Python project to train your classifier.
from sklearn.datasets import load_iris
from everywhereml.sklearn.ensemble import RandomForestClassifier
X, y = load_iris(return_X_y=True) # replace this with your own data!
clf = RandomForestClassifier(n_estimators=5).fit(X, y)
'''
Now we convert the classifier to C++ with a single line of code
- instance_name will create an instance of the classifier in the produced code
(you will use this name later)
'''
print(clf.to_arduino(instance_name='irisClassifier'))
The last line prints the Random Forest classifier C++ code to the console. Here's what it looks like.
#ifndef UUID4903236816
#define UUID4903236816
/**
* RandomForestClassifier(base_estimator=deprecated, bootstrap=True, ccp_alpha=0.0, class_name=RandomForestClassifier, class_weight=None, criterion=gini, estimator=DecisionTreeClassifier(), estimator_params=('criterion', 'max_depth', 'min_samples_split', 'min_samples_leaf', 'min_weight_fraction_leaf', 'max_features', 'max_leaf_nodes', 'min_impurity_decrease', 'random_state', 'ccp_alpha'), max_depth=None, max_features=sqrt, max_leaf_nodes=None, max_samples=None, min_impurity_decrease=0.0, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=5, n_jobs=None, num_outputs=3, oob_score=False, package_name=everywhereml.sklearn.ensemble, random_state=None, template_folder=everywhereml/sklearn/ensemble, verbose=0, warm_start=False)
*/
class RandomForestClassifier {
public:
/**
* Predict class from features
*/
int predict(float * x) {
int predictedValue = 0;
size_t startedAt = micros();
uint16_t votes[3] = {
0
};
uint8_t classIdx = 0;
float classScore = 0;
tree0(x, & classIdx, & classScore);
votes[classIdx] += classScore;
tree1(x, & classIdx, & classScore);
votes[classIdx] += classScore;
tree2(x, & classIdx, & classScore);
votes[classIdx] += classScore;
tree3(x, & classIdx, & classScore);
votes[classIdx] += classScore;
tree4(x, & classIdx, & classScore);
votes[classIdx] += classScore;
uint8_t maxClassIdx = 0;
float maxVote = votes[0];
for (uint8_t i = 1; i < 3; i++) {
if (votes[i] > maxVote) {
maxClassIdx = i;
maxVote = votes[i];
}
}
predictedValue = maxClassIdx;
latency = micros() - startedAt;
return (lastPrediction = predictedValue);
}
/**
* Get latency in micros
*/
uint32_t latencyInMicros() {
return latency;
}
/**
* Get latency in millis
*/
uint16_t latencyInMillis() {
return latency / 1000;
}
protected: float latency = 0;
int lastPrediction = 0;
/**
* Random forest's tree #0
*/
void tree0(float * x, uint8_t * classIdx, float * classScore) {
if (x[0] < 5.450000047683716) {
if (x[2] < 2.599999964237213) {
* classIdx = 0;
* classScore = 50.0;
return;
} else {
if (x[3] < 1.600000023841858) {
* classIdx = 1;
* classScore = 59.0;
return;
} else {
* classIdx = 2;
* classScore = 41.0;
return;
}
}
} else {
if (x[2] < 4.75) {
if (x[3] < 0.7000000029802322) {
* classIdx = 0;
* classScore = 50.0;
return;
} else {
* classIdx = 1;
* classScore = 59.0;
return;
}
} else {
if (x[0] < 5.950000047683716) {
if (x[2] < 4.8500001430511475) {
* classIdx = 1;
* classScore = 59.0;
return;
} else {
* classIdx = 2;
* classScore = 41.0;
return;
}
} else {
if (x[3] < 1.699999988079071) {
if (x[0] < 7.049999952316284) {
if (x[1] < 2.450000047683716) {
* classIdx = 2;
* classScore = 41.0;
return;
} else {
* classIdx = 1;
* classScore = 59.0;
return;
}
} else {
* classIdx = 2;
* classScore = 41.0;
return;
}
} else {
* classIdx = 2;
* classScore = 41.0;
return;
}
}
}
}
}
/**
* Random forest's tree #1
*/
void tree1(float * x, uint8_t * classIdx, float * classScore) {
if (x[3] < 1.75) {
if (x[3] < 0.800000011920929) {
* classIdx = 0;
* classScore = 42.0;
return;
} else {
if (x[3] < 1.3499999642372131) {
* classIdx = 1;
* classScore = 47.0;
return;
} else {
if (x[2] < 5.049999952316284) {
* classIdx = 1;
* classScore = 47.0;
return;
} else {
* classIdx = 2;
* classScore = 61.0;
return;
}
}
}
} else {
if (x[2] < 4.8500001430511475) {
* classIdx = 1;
* classScore = 47.0;
return;
} else {
* classIdx = 2;
* classScore = 61.0;
return;
}
}
}
/**
* Random forest's tree #2
*/
void tree2(float * x, uint8_t * classIdx, float * classScore) {
if (x[2] < 2.600000023841858) {
* classIdx = 0;
* classScore = 49.0;
return;
} else {
if (x[2] < 4.75) {
* classIdx = 1;
* classScore = 54.0;
return;
} else {
if (x[3] < 1.75) {
if (x[1] < 2.649999976158142) {
* classIdx = 2;
* classScore = 47.0;
return;
} else {
if (x[1] < 2.850000023841858) {
* classIdx = 1;
* classScore = 54.0;
return;
} else {
if (x[2] < 5.400000095367432) {
* classIdx = 1;
* classScore = 54.0;
return;
} else {
* classIdx = 2;
* classScore = 47.0;
return;
}
}
}
} else {
if (x[0] < 6.049999952316284) {
if (x[3] < 1.8499999642372131) {
* classIdx = 1;
* classScore = 54.0;
return;
} else {
* classIdx = 2;
* classScore = 47.0;
return;
}
} else {
* classIdx = 2;
* classScore = 47.0;
return;
}
}
}
}
}
/**
* Random forest's tree #3
*/
void tree3(float * x, uint8_t * classIdx, float * classScore) {
if (x[3] < 0.800000011920929) {
* classIdx = 0;
* classScore = 53.0;
return;
} else {
if (x[2] < 4.75) {
* classIdx = 1;
* classScore = 43.0;
return;
} else {
if (x[2] < 5.1499998569488525) {
if (x[3] < 1.699999988079071) {
if (x[1] < 2.75) {
* classIdx = 1;
* classScore = 43.0;
return;
} else {
* classIdx = 2;
* classScore = 54.0;
return;
}
} else {
if (x[2] < 4.8500001430511475) {
if (x[0] < 5.950000047683716) {
* classIdx = 1;
* classScore = 43.0;
return;
} else {
* classIdx = 2;
* classScore = 54.0;
return;
}
} else {
* classIdx = 2;
* classScore = 54.0;
return;
}
}
} else {
* classIdx = 2;
* classScore = 54.0;
return;
}
}
}
}
/**
* Random forest's tree #4
*/
void tree4(float * x, uint8_t * classIdx, float * classScore) {
if (x[2] < 2.449999988079071) {
* classIdx = 0;
* classScore = 52.0;
return;
} else {
if (x[2] < 4.950000047683716) {
if (x[3] < 1.699999988079071) {
* classIdx = 1;
* classScore = 51.0;
return;
} else {
* classIdx = 2;
* classScore = 47.0;
return;
}
} else {
if (x[3] < 1.699999988079071) {
if (x[3] < 1.550000011920929) {
* classIdx = 2;
* classScore = 47.0;
return;
} else {
if (x[2] < 5.450000047683716) {
* classIdx = 1;
* classScore = 51.0;
return;
} else {
* classIdx = 2;
* classScore = 47.0;
return;
}
}
} else {
* classIdx = 2;
* classScore = 47.0;
return;
}
}
}
}
};
static RandomForestClassifier irisClassifier;
#endif
Load CSV file
The following Python script will train a model that is able to classify the data inside a CSV file. It makes the following assumptions:
- the file has column headers
- all data is numeric
- the class column is of string type
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from everywhereml.sklearn.ensemble import RandomForestClassifier
def load_data_from_csv(filename: str, label_column: str) -> tuple:
"""
Convert csv file to X and y
:param label_column:
:param filename:
:return:
"""
df = pd.read_csv(filename)
x_columns = [c for c in df.columns if c != label_column]
X = df[x_columns].to_numpy(dtype=float)
y_string = df[label_column]
label_encoder = LabelEncoder().fit(y_string)
y_numeric = label_encoder.transform(y_string)
print('Label mapping', {label: i for i, label in enumerate(label_encoder.classes_)})
return X, y_numeric
X, y = load_data_from_csv('iris.csv', label_column='variety')
clf = RandomForestClassifier(n_estimators=5).fit(X, y)
print(clf.to_arduino(instance_name='irisClassifier'))
Arduino sketch
Copy the produced code into your sketch, preferably into its own file (eg. IrisClassifier.h
), then grab the following code to run the classification.
#include "IrisClassifier.h"
// IrisClassifier.h creates a irisClassifier object
// that you can use to classify a feature vector
// no setup is required
void setup() {
Serial.begin(115200);
}
void loop() {
// replace with your actual feature vector
float input[4] = {5.1, 3.5, 1.4, 0.2};
Serial.print("Prediction: ");
Serial.println(irisClassifier.predict(input));
}
How much tiny is it?
Depending on the algorithm you choose, truly TinyML can be extremely tiny! And fast.
To give you some real figures, a Random Forest classifier can execute in ~10 microseconds on an input of 1000 features and it requires less then 1 kb of RAM.
Conclusions
If you were able to follow the entire tutorial, you should have the basic knowledge required to implement your very own machine learning on Arduino. The Random Forest classifier showcased above is one of the best (both in terms of accuracy and speed) to get started.
To implement your own model, you only have to copy the Python script and load your very own data. That's it!
If you're stuck, don't be shy and use the form below to ask for help.