### Install Dependencies and Run Example on Device
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/har_trees/README.md
Installs required libraries and copies example code to the device using mpremote, then runs the evaluation script.
```console
mpremote mip install https://emlearn.github.io/emlearn-micropython/builds/latest/xtensawin_6.3/emlearn_trees.mpy
mpremote mip install github:jonnor/micropython-npyfile
mpremote mip install github:jonnor/micropython-zipfile
mpremote cp uci_har.trees.csv uci_har.testdata.npz uci_har.meta.json timebased.py :
mpremote run har_run.py
```
--------------------------------
### Install Dependencies and Run Example on Host
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/har_trees/README.md
Installs the necessary emlearn library and runs the HAR example script on a host machine with MicroPython Unix port.
```console
micropython -m mip install https://emlearn.github.io/emlearn-micropython/builds/latest/x64_6.3/emlearn_trees.mpy
micropython har_run.py
```
--------------------------------
### Run sound level example
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/soundlevel_iir/README.md
Execute the soundlevel_screen.py script on the device using mpremote to start the sound level visualization.
```console
mpremote run soundlevel_screen.py
```
--------------------------------
### Install emlearn-micropython modules
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/getting_started_host.md
Install the emlearn-micropython native modules, specifically the 'emlearn_trees' module for this example, using mip.
```console
micropython -m mip install https://emlearn.github.io/emlearn-micropython/builds/latest/x64_6.3/emlearn_trees.mpy
```
--------------------------------
### Copy example to device
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/soundlevel_iir/README.md
Copy the soundlevel.py example file to the device's root directory using mpremote.
```console
mpremote cp color_setup.py soundlevel.py :
```
--------------------------------
### Install UI framework and screen driver
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/soundlevel_iir/README.md
Install the micropython-nano-gui framework and its SSD1306 display driver using mpremote.
```console
mpremote mip install "github:peterhinch/micropython-nano-gui/drivers/ssd1306"
```
```console
mpremote mip install "github:peterhinch/micropython-nano-gui"
```
--------------------------------
### Install Python Dependencies
Source: https://github.com/emlearn/emlearn-micropython/blob/master/paper/README.md
Install necessary Python packages for running the examples and generating plots. Ensure Python 3.10 or later is installed.
```bash
pip install plotly numpy pandas scikit-learn emlearn setuptools pyarrow kaleido
```
--------------------------------
### Install emlearn on Device (ESP32)
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/xor_trees/README.md
Installs the emlearn library and copies the model to an ESP32 device using mpremote.
```console
mpremote mip install https://emlearn.github.io/emlearn-micropython/builds/latest/xtensawin_6.3/emlearn_trees.mpy
mpremote cp xor_model.csv :
```
--------------------------------
### Install emlearn Modules for Host
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/soundlevel_iir/README.md
Install the necessary emlearn modules for the x64 Unix port to process audio files on a host machine.
```console
micropython -m mip install https://emlearn.github.io/emlearn-micropython/builds/latest/x64_6.3/emlearn_arrayutils.mpy
micropython -m mip install https://emlearn.github.io/emlearn-micropython/builds/latest/x64_6.3/emlearn_iir.mpy
```
--------------------------------
### Install mpremote
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/getting_started_device.md
Install the `mpremote` tool, which is used for interacting with MicroPython devices.
```bash
pip install mpremote
```
--------------------------------
### Copy IoT example files to device
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/soundlevel_iir/README.md
Copies the secrets.py, iot_blynk.py, and soundlevel.py files to the device using mpremote for the IoT Blynk integration example.
```console
mpremote cp secrets.py iot_blynk.py soundlevel.py :
```
--------------------------------
### Install emlearn-micropython module for ESP32
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/getting_started_device.md
Install the `emlearn_trees` MicroPython module for ESP32 using `mpremote` and `mip`.
```bash
mpremote mip install https://emlearn.github.io/emlearn-micropython/builds/latest/xtensawin_6.3/emlearn_trees.mpy
```
--------------------------------
### Install Documentation Build Dependencies
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/developing.md
Install development dependencies required for building the documentation, including Sphinx.
```bash
pip install -r requirements.dev.txt
```
--------------------------------
### Install Dependencies for Live Classification
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/har_trees/README.md
Installs necessary libraries for live classification on the M5StickC PLUS 2 using mpremote.
```bash
mpremote mip install github:jonnor/micropython-mpu6886
mpremote mip install "github:peterhinch/micropython-nano-gui"
mpremote mip install "github:peterhinch/micropython-nano-gui/drivers/st7789"
mpremote cp windower.py color_setup.py :
```
--------------------------------
### Run Example Script
Source: https://github.com/emlearn/emlearn-micropython/blob/master/paper/README.md
Execute the main Python script to generate plots and run the Human Activity Recognition example. This command assumes native MicroPython modules are installed.
```bash
python create_plot.py
```
--------------------------------
### Install Python Requirements for Training
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/har_trees/README.md
Installs Python package requirements for training EMLearn models on a PC.
```bash
pip install .
```
--------------------------------
### Prepare Custom MicroPython Executable and Run
Source: https://github.com/emlearn/emlearn-micropython/blob/master/paper/README.md
Set up a custom MicroPython executable and run the example script. This method involves downloading a binary or using a locally built version and then executing the script.
```bash
export PATH=./:$PATH
```
```bash
echo which micropython
```
```bash
curl -o npyfile.py https://raw.githubusercontent.com/jonnor/micropython-npyfile/refs/heads/master/npyfile.py
```
```bash
python create_plot.py
```
--------------------------------
### Install scikit-learn
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/getting_started_host.md
Install the scikit-learn Python package, which is used for training machine learning models.
```console
pip install scikit-learn
```
--------------------------------
### Copy soundlevel.py to device
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/soundlevel_iir/README.md
Copies the soundlevel.py example script to the device's root directory using mpremote.
```console
mpremote cp soundlevel.py :
```
--------------------------------
### Install on Device (Manual)
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/mnist_cnn/README.md
Installs the emlearn CNN model on a MicroPython device using mpremote. Ensure the device is flashed with standard MicroPython firmware.
```console
mpremote mip install https://emlearn.github.io/emlearn-micropython/builds/latest/xtensawin_6.3/emlearn_cnn_int8.mpy
```
--------------------------------
### Install emlearn-micropython module for ARM Cortex
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/getting_started_device.md
Install the `emlearn_trees` MicroPython module for ARM Cortex M4F/M33/M7 devices using `mpremote` and `mip`.
```bash
mpremote mip install https://emlearn.github.io/emlearn-micropython/builds/latest/armv7emsp_6.3/emlearn_trees.mpy
```
--------------------------------
### Install emlearn_trees.mpy using mip
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
Install pre-built emlearn-micropython native modules using the 'mip' package manager. Ensure the correct URL pattern for your architecture and MicroPython ABI is used.
```console
# On host (x64, MicroPython 1.23–1.28, ABI 6.3)
micropython -m mip install https://emlearn.github.io/emlearn-micropython/builds/latest/x64_6.3/emlearn_trees.mpy
```
```console
# On ESP32 via mpremote
mpremote mip install https://emlearn.github.io/emlearn-micropython/builds/latest/xtensawin_6.3/emlearn_trees.mpy
```
```console
# On ARM Cortex-M4F / M7 via mpremote
mpremote mip install https://emlearn.github.io/emlearn-micropython/builds/latest/armv7emsp_6.3/emlearn_trees.mpy
```
```console
# On RISC-V (ESP32-C3 / ESP32-C6) via mpremote
mpremote mip install https://emlearn.github.io/emlearn-micropython/builds/latest/rv32imc_6.3/emlearn_trees.mpy
```
--------------------------------
### Download Prebuilt MicroPython Binary (Linux)
Source: https://github.com/emlearn/emlearn-micropython/blob/master/paper/README.md
Download a prebuilt MicroPython binary for Linux. This is an alternative method for running examples on Linux.
```bash
curl -o micropython https://emlearn.github.io/emlearn-micropython/builds/latest/ports/linux/micropython
```
--------------------------------
### Install emlearn
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/getting_started_host.md
Install the emlearn Python package, used to convert scikit-learn models into a format compatible with emlearn-micropython.
```console
pip install emlearn
```
--------------------------------
### Download Prebuilt MicroPython Binary (Mac OS)
Source: https://github.com/emlearn/emlearn-micropython/blob/master/paper/README.md
Download a prebuilt MicroPython binary for Mac OS. This is an alternative method for running examples on Mac OS.
```bash
curl -o micropython https://emlearn.github.io/emlearn-micropython/builds/latest/ports/macos/micropython
```
--------------------------------
### Install .mpy Module on Device
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/developing.md
Copy the built .mpy native module to the device using mpremote.
```bash
mpremote cp dist/armv6m*/emlearn_trees.mpy :emlearn_trees.mpy
```
--------------------------------
### Install Python Dependencies
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/developing.md
Install the necessary Python packages for development using pip. It is recommended to use a virtual environment.
```bash
pip install -r requirements.txt
```
--------------------------------
### HTML Setup for emlearn-micropython with PyScript
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/getting_started_browser.md
This HTML structure sets up a web page to run emlearn-micropython using PyScript. Ensure micropython.mjs and micropython.wasm are in the same directory.
```html
emlearn-micropython in browser with PyScript
interpreter = "/micropython.mjs"
```
--------------------------------
### Install Dependencies
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/mnist_cnn/README.md
Installs the necessary Python dependencies for the project. Ensure you are using Python 3.10 and have a compatible Tensorflow version.
```console
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```
--------------------------------
### Install emlearn modules for ESP32
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/soundlevel_iir/README.md
Installs the necessary emlearn modules for the ESP32 architecture using mpremote. Ensure your device is flashed with MicroPython and has an I2S microphone connected.
```console
mpremote mip install https://emlearn.github.io/emlearn-micropython/builds/latest/xtensawin_6.3/emlearn_arrayutils.mpy
```
```console
mpremote mip install https://emlearn.github.io/emlearn-micropython/builds/latest/xtensawin_6.3/emlearn_iir.mpy
```
--------------------------------
### Build JOSS Paper with Docker
Source: https://github.com/emlearn/emlearn-micropython/blob/master/paper/README.md
Use this command to build the JOSS paper locally. Requires Docker to be installed.
```bash
docker run --rm --volume $PWD/paper:/data --user $(id -u):$(id -g) --env JOURNAL=joss openjournals/inara
```
--------------------------------
### Run on Host
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/mnist_cnn/README.md
Installs the emlearn CNN model and runs the inference script on the host machine using the micropython interpreter.
```console
micropython -m mip install https://emlearn.github.io/emlearn-micropython/builds/latest/x64_6.3/emlearn_cnn_int8.mpy
micropython mnist_cnn_run.py
```
--------------------------------
### Run automated tests
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/soundlevel_iir/README.md
Execute the automated tests for the sound level example using the provided Python script.
```console
python test_soundlevel.py
```
--------------------------------
### Install MicroPython Modules (Native)
Source: https://github.com/emlearn/emlearn-micropython/blob/master/paper/README.md
Install required MicroPython modules using the 'mip' package manager for native execution. Note: Not supported on Mac OS.
```bash
micropython -m mip install github:jonnor/micropython-npyfile
```
```bash
micropython -m mip install https://emlearn.github.io/emlearn-micropython/builds/latest/x64_6.3/emlearn_trees.mpy
```
```bash
micropython -m mip install https://emlearn.github.io/emlearn-micropython/builds/latest/x64_6.3/emlearn_fft.mpy
```
--------------------------------
### Clone emlearn-micropython Repository
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/external_modules.md
Use this command to get a local copy of the emlearn-micropython project, typically as a git submodule.
```bash
git clone https://github.com/emlearn/emlearn-micropython.git
```
--------------------------------
### Configure WiFi and Blynk credentials
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/soundlevel_iir/README.md
Creates a secrets.py file to store WiFi credentials and Blynk authentication token. This file is used by the IoT example to connect to WiFi and the Blynk platform.
```python
BLYNK_AUTH_TOKEN = 'MY TOKEN HERE'
WIFI_SSID = 'MY WIFI SSID'
WIFI_PASSWORD = 'MY WIFI PASSWORD'
```
--------------------------------
### Build .mpy Native Module for Device
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/developing.md
Build the emlearn .mpy native module for a specific architecture (e.g., armv6m). Requires the toolchain for the target device to be installed.
```bash
make dist ARCH=armv6m MPY_DIR=../micropython
```
--------------------------------
### Run PC Tests with Dynamic Native Modules
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/developing.md
Build and run tests on PC using dynamic native modules (.mpy files) loaded at runtime. This requires the MicroPython Unix port to be installed and does not work on Mac OS.
```bash
make check
```
--------------------------------
### Build Documentation
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/developing.md
Build the HTML documentation using Sphinx. The output can be found in docs/_build/html/index.html.
```bash
make -C docs/ html
```
--------------------------------
### Initialize Git Submodules
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/developing.md
Fetch all git submodules required for the project, including MicroPython.
```bash
git submodule update --init
```
--------------------------------
### Run soundlevel_iot.py
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/soundlevel_iir/README.md
Executes the soundlevel_iot.py script on the MicroPython device to log sound levels to the Blynk platform over WiFi. This requires the secrets.py file to be present with valid credentials.
```console
mpremote run soundlevel_iot.py
```
--------------------------------
### Run soundlevel_live.py
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/soundlevel_iir/README.md
Executes the soundlevel_live.py script on the MicroPython device to display real-time sound levels. The script logs summarized sound levels every 10 seconds.
```console
mpremote run soundlevel_live.py
```
--------------------------------
### Run Device Tests with Mounted Filesystem
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/developing.md
Run tests on the device by mounting the host filesystem, allowing the device to access modules without copying. Assumes .mpy files are built.
```bash
mpremote mount . run tests/test_all.py
```
--------------------------------
### Run PC Tests with External Modules
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/developing.md
Build and run tests on PC by compiling emlearn modules as external C modules baked into the firmware. This is tested on Linux and Mac OS.
```bash
make check_unix
```
--------------------------------
### Copy Model and Run on Device (Manual)
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/mnist_cnn/README.md
Copies the trained model and test data to the MicroPython device, then executes the inference script using mpremote.
```console
mpremote cp mnist_cnn_int8.tmdl :
mpremote cp -r test_data/ :
mpremote run mnist_cnn_run.py
```
--------------------------------
### Linear Regression with On-Device Training using emlearn_linreg
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
Shows how to initialize a linear regression model with ElasticNet regularization and train it directly on the device using stochastic gradient descent. Inspect learned weights, bias, and perform inference.
```python
import emlearn_linreg
import array
# 2 features, alpha=0.01 regularization, l1_ratio=0.5 (ElasticNet), lr=0.001
model = emlearn_linreg.new(features=2, alpha=0.01, l1_ratio=0.5, learning_rate=0.001)
# Training data: y = 2*x0 + 3*x1 + 1
X_train = array.array('f', [
1.0, 2.0,
2.0, 1.0,
3.0, 4.0,
0.5, 1.5,
])
y_train = array.array('f', [2*1+3*2+1, 2*2+3*1+1, 2*3+3*4+1, 2*0.5+3*1.5+1])
# Train using built-in loop (runs on device, no host needed)
emlearn_linreg.train(model, X_train, y_train,
max_iterations=200,
tolerance=1e-5,
verbose=1,
)
# Inspect learned weights
weights = array.array('f', [0.0] * model.get_n_features())
model.get_weights(weights)
print('weights:', list(weights)) # -> close to [2.0, 3.0]
print('bias:', model.get_bias()) # -> close to 1.0
# Inference
sample = array.array('f', [2.0, 3.0])
prediction = model.predict(sample)
print('prediction:', prediction) # -> ~12.0 (2*2 + 3*3 + 1)
# Evaluate MSE
mse = model.score_mse(X_train)
print('train MSE:', mse)
```
--------------------------------
### Run Training Process
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/har_trees/README.md
Initiates the EMLearn model training process using the HAR UCI dataset.
```bash
python har_train.py
```
--------------------------------
### Add Training Data and Predict with eMLearn Model
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
Demonstrates how to add training data items and predict a new sample using an eMLearn model. It also shows how to inspect nearest neighbor details and retrieve stored item data.
```python
dataset = [
(array.array('h', [100, 200, 50, 80]), 0), # class 0
(array.array('h', [110, 195, 55, 85]), 0),
(array.array('h', [-100, -200, -50, -80]), 1), # class 1
(array.array('h', [-110, -190, -55, -75]), 1),
]
for features, label in dataset:
model.additem(features, label)
# Predict a new sample
query = array.array('h', [105, 198, 52, 82])
predicted_class = model.predict(query)
print('predicted class:', predicted_class) # -> 0
# Inspect nearest neighbor details
for i in range(3): # k=3
item_idx, distance, label = model.getresult(i)
print(f' neighbor {i}: item={item_idx}, dist={distance}, label={label}')
# Retrieve stored item data
stored = array.array('h', [0] * 4)
model.getitem(0, stored)
print('stored item 0:', list(stored))
```
--------------------------------
### Initialize and Query emlearn Trees Model
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
Shows how to create a new emlearn decision tree model with specified capacities and query its output class count. Loading models from files is the typical usage for inference.
```python
import emlearn_trees
import array
model = emlearn_trees.new(max_trees=10, max_nodes=1000, max_leaves=10)
# Query capacity
n_outputs = model.outputs()
print('number of output classes:', n_outputs)
# Load from file (typical usage)
with open('har_model.csv', 'r') as f:
emlearn_trees.load_model(model, f)
# Run inference on a feature vector (int16)
features = array.array('h', [100, -200, 50, 300, 120, 80, 60, 70, 40])
probs = array.array('f', [0.0] * model.outputs())
model.predict(features, probs)
# argmax to get predicted class
best = max(range(len(probs)), key=lambda i: probs[i])
print('predicted class:', best, 'with probability', probs[best])
```
--------------------------------
### Compile emlearn-micropython for custom firmware
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
For platforms without native .mpy support, compile emlearn-micropython directly into a custom MicroPython firmware. This involves cloning the repository and using 'make' with specific options.
```console
# Clone the repository as a submodule
git clone https://github.com/emlearn/emlearn-micropython.git
```
```console
# Build for cmake-based ports (ESP32, RP2, etc.)
make USER_C_MODULES=./emlearn-micropython/src/micropython.cmake \
FROZEN_MANIFEST=./emlearn-micropython/src/manifest.py \
CFLAGS_EXTRA='-Wno-unused-function'
```
```console
# Build for Makefile-based ports
make USER_C_MODULES=./emlearn-micropython/src/ \
FROZEN_MANIFEST=./emlearn-micropython/src/manifest.py \
CFLAGS_EXTRA='-Wno-unused-function'
```
--------------------------------
### Run with Live Camera Input
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/mnist_cnn/README.md
Executes the camera input script. This requires specific hardware (ESP32, OV2640 camera) and a custom firmware with the micropython-camera-API C module.
```console
mpremote run mnist_cnn_camera.py
```
--------------------------------
### Deploy Recorder as Main Script
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/har_trees/README.md
Copies `har_record.py` to `main.py` on the device and resets it, allowing it to run automatically.
```bash
mpremote cp har_record.py :main.py
mpremote reset
```
--------------------------------
### Build MicroPython with External Modules (Makefile)
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/external_modules.md
Integrate emlearn-micropython into a MicroPython build that uses a Makefile build system. Ensure you have a MicroPython build environment set up.
```bash
make USER_C_MODULES=./emlearn-micropython/src/ \
FROZEN_MANIFEST=./emlearn-micropython/src/manifest.py \
CFLAGS_EXTRA='-Wno-unused-function -Wno-unused-function'
```
--------------------------------
### Initialize K-Nearest Neighbors Model
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
Shows the initialization of an emlearn_neighbors model with specified capacities for items, features, and the number of neighbors (k). This model supports on-device learning via `additem()`.
```python
import emlearn_neighbors
import array
# max_items=50, features=4, k_neighbors=3
model = emlearn_neighbors.new(50, 4, 3)
```
--------------------------------
### Run Inference on ESP32 (Device Side)
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
Loads a pre-trained emlearn model from CSV on an ESP32, performs inference on sensor data chunks, and calculates accuracy. Requires emlearn_trees, npyfile, and zipfile modules.
```python
# ── DEVICE SIDE (MicroPython on ESP32) ────────────────────────────────
import emlearn_trees, npyfile, zipfile, array
N_FEATURES = 9
N_CLASSES = 6
model = emlearn_trees.new(max_trees=10, max_nodes=1000, max_leaves=N_CLASSES)
with open('har_model.csv', 'r') as f:
emlearn_trees.load_model(model, f)
probs = array.array('f', [0.0] * model.outputs())
correct = 0
total = 0
with zipfile.ZipFile('har_testdata.npz') as zf:
with npyfile.Reader(zf.open('X.npy')) as X_file:
with npyfile.Reader(zf.open('Y.npy')) as Y_file:
for feat_chunk, label_chunk in zip(
X_file.read_data_chunks(N_FEATURES),
Y_file.read_data_chunks(1)):
model.predict(feat_chunk, probs)
pred = max(range(len(probs)), key=lambda i: probs[i])
if pred == label_chunk[0]:
correct += 1
total += 1
print(f'Accuracy: {100*correct/total:.1f}%')
```
--------------------------------
### Run PC Tests with External Modules (Ignoring Warnings)
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/developing.md
Run PC tests with external modules, ignoring compilation warnings from MicroPython code. Use this if the build fails due to warnings.
```bash
make check_unix CFLAGS_EXTRA=-Wno-error
```
--------------------------------
### Run Live Classification
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/har_trees/README.md
Executes the live classification script on the MicroPython device.
```bash
mpremote run har_live.py
```
--------------------------------
### Combine Sensor Data and Labels
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/har_trees/README.md
Merges sensor data files with their corresponding labels from Label Studio to create a dataset in .parquet format.
```bash
python har_labelstudio2dataset.py
```
--------------------------------
### Native Module URL Structure
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/native_modules.md
This is the structure for accessing pre-built native modules. Replace placeholders with your specific version, architecture, ABI, and module name.
```text
https://emlearn.github.io/emlearn-micropython/builds/$VERSION/$ARCH_$ABI/$MODULE.mpy
where:
VERSION=latest|0.10.0
MODULE=emlearn_trees
ARCH=xtensawin
ABI=6.3
```
--------------------------------
### Design and Apply IIR Filter Coefficients
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
Demonstrates designing IIR filter coefficients on a host system using SciPy and then applying them to a signal on a device using emlearn_iir. The `run()` method modifies the signal array in-place.
```python
# ── HOST SIDE (Python) — design filter coefficients ───────────────────
from scipy.signal import butter, sosfilt
import numpy as np
# 4th-order Butterworth low-pass at 10 Hz, 100 Hz sample rate
sos = butter(4, 10, fs=100, output='sos')
# sos shape: (2, 6) — 2 second-order sections, flatten for emlearn
coefficients = sos.flatten().tolist()
print('coefficients:', coefficients)
# ── DEVICE SIDE (MicroPython) ─────────────────────────────────────────
import emlearn_iir
import array, math
# Paste or load the coefficients produced on the host
coefficients = [
1.0, 0.0, 0.0, 1.0, -0.01664, 6.93e-05, # stage 1
1.0, -2.0, 1.0, 1.0, -1.7070, 0.71746, # stage 2
]
coeff = array.array('f', coefficients)
iir = emlearn_iir.new(coeff)
# Synthesize a signal: mix of 2 Hz and 20 Hz tones
PI2 = 2 * math.pi
sr, dur = 100, 1.0
n = int(dur * sr)
signal = array.array('f', (math.sin(PI2*2*t/sr) + math.sin(PI2*20*t/sr) for t in range(n)))
# Apply filter in-place — 20 Hz component is attenuated
iir.run(signal)
print('filtered signal (first 5):', list(signal[:5]))
```
--------------------------------
### Load and Predict with emlearn Trees Model
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
Demonstrates loading a pre-trained decision tree model from a CSV file and performing predictions on sample data. Ensure the model file exists and the data format matches the model's input requirements.
```python
import emlearn_trees
import array
# Allocate model with capacity: max_trees=5, max_nodes=30, max_leaves=2 (classes)
model = emlearn_trees.new(5, 30, 2)
with open('xor_model.csv', 'r') as f:
emlearn_trees.load_model(model, f)
max_val = 2**15 - 1 # represents 1.0 in int16 space
examples = [
array.array('h', [0, 0]), # XOR -> False
array.array('h', [max_val, max_val]),# XOR -> False
array.array('h', [0, max_val]), # XOR -> True
array.array('h', [max_val, 0]), # XOR -> True
]
out = array.array('f', [0.0] * model.outputs())
for ex in examples:
model.predict(ex, out)
predicted_class = 1 if out[1] > 0.5 else 0
print(list(ex), '->', list(out), '=> class', predicted_class)
```
--------------------------------
### Run Inference on Host
Source: https://github.com/emlearn/emlearn-micropython/blob/master/examples/xor_trees/README.md
Executes the inference script on the host machine.
```console
micropython xor_run.py
```
--------------------------------
### Build MicroPython with External Modules (CMake)
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/external_modules.md
Integrate emlearn-micropython into a MicroPython build that uses a cmake build system. Ensure you have a MicroPython build environment set up.
```bash
make USER_C_MODULES=./emlearn-micropython/src/micropython.cmake \
FROZEN_MANIFEST=./emlearn-micropython/src/manifest.py \
CFLAGS_EXTRA='-Wno-unused-function -Wno-unused-function'
```
--------------------------------
### Export and load Random Forest model with emlearn
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
This snippet demonstrates exporting a trained scikit-learn RandomForestClassifier to a CSV file using emlearn on the host, and then shows the import statement for loading it on the device side.
```python
# ── HOST SIDE (Python) ──────────────────────────────────────────────────
import emlearn
from emlearn.preprocessing import Quantizer
import numpy as np
from sklearn.ensemble import RandomForestClassifier
# Generate XOR dataset (float -> int16 via Quantizer)
rng = np.random.RandomState(42)
X = rng.uniform(0, 1, size=(200, 2))
y = np.logical_xor(X[:, 0] > 0.5, X[:, 1] > 0.5)
X = Quantizer(max_value=1.0).fit_transform(X) # converts to int16
clf = RandomForestClassifier(n_estimators=3, max_depth=3, random_state=1)
clf.fit(X, y)
cmodel = emlearn.convert(clf, method='inline')
cmodel.save(file='xor_model.csv', name='xor', format='csv')
# => xor_model.csv written
# ── DEVICE SIDE (MicroPython) ──────────────────────────────────────────
import emlearn_trees
import array
```
--------------------------------
### Train and Convert Model (Host Side)
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
Trains a Random Forest classifier on host machine using scikit-learn, quantizes data, and exports the model to emlearn CSV format. Ensure X_train is converted to int16 before saving.
```python
# ── HOST SIDE ─────────────────────────────────────────────────────────
import emlearn
from emlearn.preprocessing.quantizer import Quantizer
from sklearn.ensemble import RandomForestClassifier
import numpy as np
import pickle
# Assume X_train (n_samples, n_features) float, y_train int labels
# X must be converted to int16 before saving
q = Quantizer(max_value=4.0) # 4g accelerometer range
X_int16 = q.fit_transform(X_train)
clf = RandomForestClassifier(n_estimators=10, max_depth=8, random_state=42)
clf.fit(X_int16, y_train)
# Export to emlearn CSV format
cmodel = emlearn.convert(clf)
cmodel.save(name='har', format='csv', file='har_model.csv')
# Also save test data as .npz for on-device validation
np.savez('har_testdata.npz', X=X_test_int16, Y=y_test)
```
--------------------------------
### Convolutional Neural Network Inference with emlearn_cnn
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
Demonstrates loading a pre-trained TinyMaix model (.tmdl) and performing inference on a MicroPython device using either 32-bit float or quantized int8 CNN models. Includes loading model data, running inference, and determining the predicted class.
```python
# ── HOST SIDE (Python) — train & convert CNN ──────────────────────────
# See examples/mnist_cnn/mnist_train.py for full Keras training pipeline.
# The generate_tinymaix_model() helper converts .h5 -> .tflite -> .tmdl
# ── DEVICE SIDE (MicroPython) ─────────────────────────────────────────
import emlearn_cnn_int8 # or emlearn_cnn_fp32
import array, gc
def argmax(arr):
idx, val = 0, arr[0]
for i in range(1, len(arr)):
if arr[i] > val:
val, idx = arr[i], i
return idx
# Load model binary (.tmdl file) from flash
with open('mnist_cnn_int8.tmdl', 'rb') as f:
model_data = array.array('B', f.read())
model = emlearn_cnn_int8.new(model_data)
# Query output shape (e.g., 10 classes for MNIST)
out_dims = model.output_dimensions()
print('output dimensions:', out_dims) # -> (10,)
probabilities = array.array('f', [-1.0] * out_dims[0])
# Load a 28x28 grayscale image stored as raw bytes
with open('test_data/mnist_example_0_7.bin', 'rb') as f:
img = array.array('B', f.read()) # 784 bytes
model.run(img, probabilities)
predicted_digit = argmax(probabilities)
print('predicted digit:', predicted_digit) # -> 7
gc.collect() # recommended after inference on constrained devices
```
--------------------------------
### Perform FFT on a Real Signal
Source: https://context7.com/emlearn/emlearn-micropython/llms.txt
Illustrates how to perform a Fast Fourier Transform on a real-valued signal using emlearn_fft. The FFT operates in-place on separate real and imaginary arrays. Ensure the FFT size (N) is a power of two.
```python
import emlearn_fft
import array, math
N = 256 # must be a power of two
# Create FFT instance and fill in twiddle factors
fft = emlearn_fft.FFT(N)
emlearn_fft.fill(fft, N)
# Build a real signal: 10 Hz sine at 256 Hz sample rate
PI2 = 2 * math.pi
real = array.array('f', (math.sin(PI2 * 10 * i / N) for i in range(N)))
imag = array.array('f', [0.0] * N) # imaginary part = 0 for real input
# Run FFT in-place
fft.run(real, imag)
# Compute magnitude spectrum for positive frequencies (bins 0 .. N//2)
magnitudes = [math.sqrt(real[k]**2 + imag[k]**2) for k in range(N // 2)]
peak_bin = max(range(len(magnitudes)), key=lambda i: magnitudes[i])
peak_freq = peak_bin * (N / N) # freq = bin * (sample_rate / N)
print('peak bin:', peak_bin, '-> ~10 Hz spike confirmed')
```
--------------------------------
### Run Python script to train model
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/getting_started_device.md
Command to execute the Python script that trains and saves the emlearn model.
```bash
python xor_train.py
```
--------------------------------
### Run MicroPython script on device
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/getting_started_device.md
Command to execute the MicroPython script on the connected hardware device using `mpremote run`.
```bash
mpremote run xor_host.py
```
--------------------------------
### Serve HTML files locally
Source: https://github.com/emlearn/emlearn-micropython/blob/master/docs/getting_started_browser.md
Use Python's built-in HTTP server to serve your HTML and MicroPython files. Access the application via http://localhost:8000.
```bash
python -m http.server
```
--------------------------------
### Compare IIR Filter Performance
Source: https://github.com/emlearn/emlearn-micropython/blob/master/benchmarks/iir/SimpleFilters.ipynb
Compares the spectral output of SciPy's sosfilt with emlearn's sosfilt_emlearn_q15. Requires noise data, filter coefficients, and plotting functions.
```python
noise = numpy.random.random(2000) - 0.5
out_scipy = scipy.signal.sosfilt(coeff, noise)
out_emlearn = sosfilt_emlearn_q15(numpy.array(coeff), noise)
fig, ax = plt.subplots(1, figsize=(10, 5))
plot_spectrum_difference(ax, noise, out_scipy, fs=fs, label='scipy')
plot_spectrum_difference(ax, noise, out_emlearn, fs=fs, label='emlearn')
ax.legend()
```