API reference

emlearn_trees - Decision tree ensembles

Tree-based models (Random Forest et.c.)

Implemented using eml_trees from the emlearn C library (https://github.com/emlearn/emlearn).

class emlearn_trees.Model[source]

A tree-based ensemble model

Note: Normally not constructed directly. Instead use

addleaf(value)[source]

Add a leaf node

Note: Usually not used directly. Instead use load_model().

Parameters:

value (int)

addnode(left, right, feature, value)[source]

Add a decision node

Note: Usually not used directly. Instead use load_model().

Parameters:
  • left (int) – Left child (node or leaf)

  • right (int) – Right child (node or leaf)

  • feature (int) – Feature index

  • value (int) – Threshold to compute feature to

addroot(root)[source]

Add a tree root

Note: Usually not used directly. Instead use load_model().

Parameters:

root – Offset into nodes for the initial decision node of a tree

outputs()[source]

Get the output dimensions/size of the model

Useful to know how large an array to pass to predict()

Return type:

int

predict(inputs, outputs)[source]

Run inference using the model

Parameters:
  • inputs (array.array) – the input data. Typecode ‘h’ (int16)

  • outputs (array.array) – where to put model outputs. Typecode ‘f’ (float)

setdata(features, classes)[source]

Set data about the model

Note: Usually not used directly. Instead use load_model().

Parameters:
  • features (int) – Number of input features

  • classes (int) – Number of classes

emlearn_trees.load_model(trees, file)[source]

Load model definition from a file

The model must be constructed with sufficient capacity (trees, nodes, leaves). Otherwise will raise exception.

Parameters:
emlearn_trees.new(max_trees, max_nodes, max_leaves)[source]

Construct an empty tree-based model

The model is created with a specified maximum capacity. Memory usage will be determined by this capacity.

Parameters:
  • max_trees (int) – Maximum number of trees in ensemble

  • max_nodes (int) – Maximum number of decision nodes (across all trees)

  • max_leaves (int) – Maximum number of leaves (across all trees)

Return type:

emlearn_trees.Model

emlearn_linreg - Linear regression

Linear Regression with support for training/learning/fitting as well as inference/predictions.

Supports combined L1 and L2 regularization, often called ElasticNet.

class emlearn_linreg.Model[source]

A linear-regression model

Note: Use emlearn_linreg.new to construct an instance

get_bias()[source]

Get the bias/intercept

Return type:

float

get_n_features()[source]

Get the number of features the model expects

Return type:

int

Returns:

Number of features

get_weights(weights)[source]

Access data of an item stored in the model

Parameters:

weights (array.array) – Where to copy the weights. Must be n_features long.

predict(inputs)[source]

Run inference using the model

Parameters:

inputs (array.array) – the input data. Typecode ‘f’ (float)

Return type:

float

Returns:

the predicted value

score_mse(X)[source]

Compute Mean Squared Error (MSE) on a set of samples.

Parameters:

X – Features for regression. Must be n_features*n_rows long

Return type:

float

Returns:

The MSE score

set_bias(bias)[source]

Set the bias/intercept

Parameters:

bias (float)

set_weights(weights)[source]

Access data of an item stored in the model

Parameters:

weights (array.array) – The weights to use. Must be n_features long.

step(X, y)[source]

Perform a single gradient decent step for training/fitting model.

Parameters:
  • X – Features for regression. Must be n_features*n_rows long

  • y – Targets for regression. Must be n_rows long

Return type:

None

emlearn_linreg.new(features, alpha, l1_ratio, learning_rate)[source]

Construct an new linear regression model

Parameters:
  • features (int) – Number of features in a data item

  • k_neighbors – Number of neighbors to consider

  • l1_ratio (float) – Balance between L2 and L1 loss

  • learning_rate (float) – Learning rate to use during optimization

  • alpha (float)

Return type:

emlearn_linreg.Model

emlearn_linreg.train(model, X_train, y_train, max_iterations=100, tolerance=1e-06, check_interval=10, divergence_factor=10.0, score_limit=None, verbose=0)[source]

Simple training loop using Mean Squared Error

Runs gradient decent iteratively until a tolerance has been achieved, a score reached, or max_iterations. For more complicated training needs, copy this code as an example starting point.

Parameters:
  • model – emlearn_linreg instance to train

  • X_train (array.array) – Features for regression. Must be n_features*n_rows long

  • y_train (array.array) – Targets for regression. Must be n_rows long

  • model – emlearn_linreg instance to train

  • max_iterations – Maximum number of training steps

  • tolerance – If change in score between checks is below this limit, consider converged.

  • check_interval – How many steps between each check of convergence/divergence

  • score_limit – If score is beow this limit, consider converged.

  • verbose – Whether to print/log outputs

emlearn_cnn - Convolutional Neural Networks

Convolutional Neural Network module.

Implemented using TinyMaix (https://github.com/sipeed/TinyMaix/).

Note that multiple variants of this module is provided. So the import should either be emlearn_cnn_fp32 (for 32 bit floating point), or emlearn_cnn_int8 (for 8 bit integers, quantized model).

class emlearn_cnn.Model[source]

A Convolutional Neural Network

Note: May not be constructed directly. Instead use the new() function.

output_dimensions()[source]

Get the output dimensions/size of the model

Useful to know how large an array to pass to run()

Return type:

tuple[int]

run(inputs, outputs)[source]

Run inference using the model

Parameters:
  • inputs (array.array) – the input data

  • outputs (array.array) – where to put model outputs

emlearn_cnn.new(model_data)[source]

Construct a new Convolutional Neural Network

Parameters:

model_data (array.array) – The model definition (.TMDL file, as bytes).

Return type:

emlearn_cnn.Model

emlearn_neighbors - K Nearest Neighbors (KNN)

K-nearest neighbors

Implemented using eml_neighbors from the emlearn C library (https://github.com/emlearn/emlearn).

class emlearn_neighbors.Model[source]

A nearest-neighbors model

additem(values, label)[source]

Add an item into the model

Parameters:
  • values (array.array) – the data/features of this item. Typecode ‘h’ (int16)

  • label (int) – the label/class to associate with this item

getitem(item, outputs)[source]

Access data of an item stored in the model

Parameters:
  • item (int) – Index of item

  • outputs (array.array) – Where to copy the data from the item. Typecode ‘h’ (int16)

getresult(idx)[source]

Get details on the comparisons between predict() data and items stored in model

Parameters:
  • item – Index of the comparison to retrieve. Smaller number are the nearest neighbors.

  • idx (int)

Return type:

tuple[int, int, int]

Returns:

Tuple with (item-index, distance-to-item, label-of-item)

predict(inputs)[source]

Run inference using the model

Parameters:

inputs (array.array) – the input data. Typecode ‘h’ (int16)

Return type:

int

Returns:

the resulting label/class

emlearn_neighbors.new(max_items, features, k_neighbors)[source]

Construct an empty neighbors model

The model is created with a specified maximum capacity. Memory usage will be determined by this capacity.

Parameters:
  • max_items (int) – Maximum number of items in the dataset

  • features (int) – Number of features in a data item

  • k_neighbors (int) – Number of neighbors to consider

Return type:

emlearn_neighbors.Model

emlearn_fft - Fast Fourier Transform

Fast Fourier Transform (FFT)

Implemented using eml_fft from the emlearn C library (https://github.com/emlearn/emlearn).

class emlearn_fft.FFT(length)[source]

Fast Fourier Transform (FFT)

Parameters:

length (int)

fill(sin, cos)[source]

Set up FFT coefficients

Note: Do not use this directly. Instead use the module-level fill() function.

Parameters:
  • sin (array.array) – Precomputed coefficients

  • cos (array.array) – Precomputed coefficients

run(real, imag)[source]

Perform the FFT transformation

Note: operates in-place, will modify both arrays.

To perform a real-only (RFFT), let imag be all zeroes.

Parameters:
  • real (array.array) – the real part of data. Typecode ‘f’ (float)

  • imag (array.array) – the imaginary part of data. Typecode ‘f’ (float)

emlearn_fft.fill(fft, n)[source]

Set up FFT coefficients

NB: Must be called before attempting to use FFT.run()

Parameters:
  • fft (emlearn_fft.FFT) – FFT instance

  • n (int) – Length of the FFT transform

emlearn_iir - Infinite Impulse Reponse filters

Infinite Impulse Response (IIR) filters

Uses a cascade of second-order filter sections (SOS). The conventions are designed to match that of scipy-signal (https://docs.scipy.org/doc/scipy/reference/signal.html), so one can use design tools such as scipy.signal.iirfilter or scipy.signal.iirdesign to create the IIR filter coefficients.

Implemented using eml_iir from the emlearn C library (https://github.com/emlearn/emlearn).

class emlearn_iir.IIR[source]

Infinite Impulse Response filter

run(values)[source]

Perform the filter

Note: operates in-place, will modify the input array data.

Parameters:

values (array.array) – the data to filter. Typecode ‘f’ (float)

emlearn_iir.new(coefficients)[source]

Create IIR filter

There must be 6 coefficients per second-order stage. The format of each stage is on form Transposed Direct Form II: (b0, b1, b2, 1.0, -a1, -a2). Multiple stages are formed by concatenating the coefficients of each stage. This is the same used by scipy.signal.sosfilt.

Parameters:

coefficients (array.array) – IIR filter coefficients

Return type:

emlearn_iir.IIR

emlearn_arrayutils - Efficient utilities for array.array

Array utility functions

Some simple operations on arrays, implemented in C for efficiency.

emlearn_arrayutils.linear_map(inputs, outputs, in_min, in_max, out_min, out_max)[source]

Compute an element-wise linear mapping/scaling.

The range (in_min, in_max) will be mapped to (out_min, out_max). The function supports in and out being different data widths (array typecodes).

The following pairs are supported: - float (f) to int16 (h) - int16 (h) to float (f)

Parameters:
  • inputs (array.array) – The input data

  • outputs (array.array) – Where output is placed

  • in_min (float)

  • in_max (float)

  • out_min (float)

  • out_max (float)