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 indexvalue (
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
- 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:
trees (
emlearn_trees.Model)file (
typing.BinaryIO)
- 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 ensemblemax_nodes (
int) – Maximum number of decision nodes (across all trees)max_leaves (
int) – Maximum number of leaves (across all trees)
- Return type:
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_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
- 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 itemk_neighbors – Number of neighbors to consider
l1_ratio (
float) – Balance between L2 and L1 losslearning_rate (
float) – Learning rate to use during optimizationalpha (
float)
- Return type:
- 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 longy_train (
array.array) – Targets for regression. Must be n_rows longmodel – 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.
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 itemoutputs (
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)
- 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 datasetfeatures (
int) – Number of features in a data itemk_neighbors (
int) – Number of neighbors to consider
- Return type:
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 coefficientscos (
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 instancen (
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).
- 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_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 dataoutputs (
array.array) – Where output is placedin_min (
float)in_max (
float)out_min (
float)out_max (
float)