Arduino Machine Learning Classifier Training

Are you starting machine learning on Arduino development cards and similar microprocessors?Would you like to run the python-trained model in any C++ project, such as Arduino, STM32, ESP32?

In this content we will show you how easy it is.

Loading Data

We need some data to train a classifier.If you're starting from scratch and don't already have your preferred folder structure, we recommend creating a folder to hold the data you collect.

Inside this folder, create a custom file with a .csv extension by placing an example on each line for each class you want to classify.If you have done so, you can use the next function to load this data.

import numpy as np
from glob import glob
from os.path import basename

def load_features(folder):
    dataset = None
    classmap = {}
    for class_idx, filename in enumerate(glob('%s/*.csv' % folder)):
        class_name = basename(filename)[:-4]
        classmap[class_idx] = class_name
        samples = np.loadtxt(filename, dtype=float, delimiter=',')
        labels = np.ones((len(samples), 1)) * class_idx
        samples = np.hstack((samples, labels))
        dataset = samples if dataset is None else np.vstack((dataset, samples))

    return dataset, classmap

Training the Classifier

When we have the data, we can train the classifier.

The micromlgenpackage (which can move machine learning classifiers to plain C code) supports the following classes:

In this article we will use the Random Forest class, but you can replace it with other classes without changing the rest of the code.

from sklearn.ensemble import RandomForestClassifier

def get_classifier(features):
    X, y = features[:, :-1], features[:, -1]

    return RandomForestClassifier(20, max_depth=10).fit(X, y)

Exporting Plain C Code

Now we can convert the trained classifier to plain C code using the micromlgenpackage.

pip install micromlgen
from micromlgen import port

if  __name__ == '__main__':
    features, classmap = load_features('your-data-folder')
    classifier = get_model(features)
    c_code = port(classifier, classmap=classmap)

This is the code you need to transfer to your Arduino project.To ensure integrity with the tutorials in this content, save this code as a file named model.h.

Using in a Project

We now have the code we need to run Machine Learning directly on our microcontroller.

// Put the code you received in step 3 in this file#include if you used another classifier type"model.h"// this class will be different, check model.h
Eloquent::ML::P ort::RandomForest classifier;

void classify() {
    float x_sample[] = { /* fill this vector with sample values */ };

Serial.print("Predicted class: ");

If everything went smoothly, your microprocessor will be running machine learning smoothly.