How to use EloquentTinyML for model inference
mainEloquentTinyML provides a simplified interface for loading TensorFlow Lite for Microcontrollers models and running predictions on Arduino.
Setup Workflow
- Include Headers: You must include your model header file before the runtime and the EloquentTinyML wrapper.
- Select Runtime: Include either
<tflm_esp32.h>or<tflm_cortexm.h>based on your board. - Include Wrapper: Include
<eloquent_tinyml.h>. - Define Arena Size: Define an
ARENA_SIZEconstant. This is the memory allocated for the tensor arena. Start with a high value (e.g.,10000) and decrease it until the model stops working to optimize memory usage. - Instantiate Model: Use
Eloquent::TF::Sequential<TF_NUM_OPS, ARENA_SIZE> tf;to create your model instance. - Initialize: In
setup(), calltf.begin(yourModelHeader)and check.isOk()to ensure the model loaded correctly. You can inspect errors viatf.exception.toString(). - Run Inference: Use
tf.predict(input)inloop(). The result is accessed viatf.classificationfor classification tasks.
Configuration Options
If your model was not generated using the everywhereml Python package, you may need to manually configure the following in setup():
tf.setNumInputs(n): Set the number of input features.tf.setNumOutputs(n): Set the number of output classes/values.tf.resolver.Add[OpName](): Manually add required operations (e.g.,tf.resolver.AddFullyConnected(),tf.resolver.AddSoftmax()).
Benchmarking
You can measure inference performance using tf.benchmark.microseconds(), which returns the time taken for a single prediction in microseconds.
/**
* Run a TensorFlow model to predict the IRIS dataset
*/
// replace with your own model
// include BEFORE <eloquent_tinyml.h>!
#include "irisModel.h"
// include the runtime specific for your board
#include <tflm_esp32.h>
// now you can include the eloquent tinyml wrapper
#include <eloquent_tinyml.h>
#define ARENA_SIZE 2000
Eloquent::TF::Sequential<TF_NUM_OPS, ARENA_SIZE> tf;
void setup() {
Serial.begin(115200);
// configure input/output
tf.setNumInputs(4);
tf.setNumOutputs(3);
// add required ops
tf.resolver.AddFullyConnected();
tf.resolver.AddSoftmax();
while (!tf.begin(irisModel).isOk()) {
Serial.println(tf.exception.toString());
}
}
void loop() {
if (!tf.predict(x0).isOk()) {
Serial.println(tf.exception.toString());
return;
}
Serial.print("predicted class ");
Serial.println(tf.classification);
Serial.print("Inference time: ");
Serial.print(tf.benchmark.microseconds());
Serial.println(" us");
delay(1000);
}