Arduino Machine Learning Quickstart

Arduino Machine Learning Quickstart cover

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
1

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'))
1 2 3 4 5 6 7 8 9 10 11 12

The last line prints the Random Forest classifier C++ code to the console. Here's what it looks like.

See source

#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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491

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:

  1. the file has column headers
  2. all data is numeric
  3. 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'))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

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));
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

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.

Subscribe to my newsletter

Join 1175 businesses and hobbysts skyrocketing their Arduino + ESP32 skills twice a month