API reference
emlearn_trees - Decision tree ensemble inference
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: int)[source]
Add a leaf node
Note: Usually not used directly. Instead use load_model().
- Parameters:
value
- addnode(left: int, right: int, feature: int, value: int)[source]
Add a decision node
Note: Usually not used directly. Instead use load_model().
- Parameters:
left – Left child (node or leaf)
right – Right child (node or leaf)
feature – Feature index
value – 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() int[source]
Get the output dimensions/size of the model
Useful to know how large an array to pass to predict()
- emlearn_trees.load_model(trees: Model, file: BinaryIO)[source]
Load model definition from a file
The model must be constructed with sufficient capacity (trees, nodes, leaves). Otherwise will raise exception.
- emlearn_trees.new(max_trees: int, max_nodes: int, max_leaves: int) Model[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 – Maximum number of trees in ensemble
max_nodes – Maximum number of decision nodes (across all trees)
max_leaves – Maximum number of leaves (across all trees)
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() int[source]
Get the number of features the model expects
- Returns:
Number of features
- get_weights(weights: array.array)[source]
Access data of an item stored in the model
- Parameters:
weights – Where to copy the weights. Must be n_features long.
- predict(inputs: array.array) float[source]
Run inference using the model
- Parameters:
inputs – the input data. Typecode ‘f’ (float)
- Returns:
the predicted value
- score_mse(X) float[source]
Compute Mean Squared Error (MSE) on a set of samples.
- Parameters:
X – Features for regression. Must be n_features*n_rows long
- Returns:
The MSE score
- emlearn_linreg.new(features: int, alpha: float, l1_ratio: float, learning_rate: float) Model[source]
Construct an new linear regression model
- Parameters:
features – Number of features in a data item
k_neighbors – Number of neighbors to consider
l1_ratio – Balance between L2 and L1 loss
learning_rate – Learning rate to use during optimization
- emlearn_linreg.train(model, X_train: array.array, y_train: array.array, 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 – Features for regression. Must be n_features*n_rows long
y_train – 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_logreg - Logistic regression classification
Logistic Regression (binary and multiclass).
For more complicated training needs, use the train or train_batches helper functions.
- class emlearn_logreg.Model[source]
A logistic regression model
Note: Use emlearn_logreg.new to construct an instance
- get_bias(out: array.array) None[source]
Copy the model biases into an output buffer.
- Parameters:
out – Float32 buffer of n_classes (modified in-place)
- get_weights(out: array.array) None[source]
Copy the model weights into an output buffer.
- Parameters:
out – Float32 buffer of n_features * n_classes (modified in-place)
- predict(features: array.array, probs: array.array, logits: array.array) int[source]
Run prediction and return the predicted class index.
- Parameters:
features – Input features, float32 array of n_features
probs – Output buffer for probabilities, float32 array of n_classes (modified in-place)
logits – Output buffer for logits, float32 array of n_classes (modified in-place)
- Returns:
Index of the predicted class
- score_logloss(X: array.array, y: array.array, logits: array.array, probs: array.array) float[source]
Compute the log-loss on a dataset.
- Parameters:
X – Features, float32 array of n_samples * n_features
y – Targets (one-hot), float32 array of n_samples * n_classes
logits – Workspace buffer, float32 array of n_classes
probs – Workspace buffer, float32 array of n_classes
- Returns:
The log-loss value
- set_bias(bias: array.array) None[source]
Set the model biases.
- Parameters:
bias – Float32 array of n_classes
- set_weights(weights: array.array) None[source]
Set the model weights from a buffer.
- Parameters:
weights – Float32 array of n_features * n_classes
- step(X: array.array, y: array.array, logits: array.array, probs: array.array, bias_grads: array.array) None[source]
Perform a single training iteration.
- Parameters:
X – Batch features, float32 array of n_samples * n_features
y – Batch targets (one-hot), float32 array of n_samples * n_classes
logits – Workspace buffer, float32 array of n_classes
probs – Workspace buffer, float32 array of n_classes
bias_grads – Workspace buffer, float32 array of n_classes
- emlearn_logreg.new(n_features: int, n_classes: int, learning_rate: float, lambda_l2: float, lambda_l1: float) Model[source]
Construct a new logistic regression model.
- Parameters:
n_features – Number of input features
n_classes – Number of output classes
learning_rate – Learning rate for gradient descent
lambda_l2 – L2 regularization strength
lambda_l1 – L1 regularization strength
- emlearn_logreg.train(model: Model, X_train: array.array, y_train: array.array, max_iterations: int = ..., tolerance: float = ..., check_interval: int = ..., divergence_factor: float = ..., score_limit: float | None = ..., verbose: int = ...) Tuple[int, float][source]
Full-dataset training loop for logistic regression.
- Parameters:
model – Logistic regression model instance
X_train – Training features, float32 array of n_samples * n_features
y_train – Training targets (one-hot), float32 array of n_samples * n_classes
max_iterations – Maximum number of training steps
tolerance – Convergence tolerance
check_interval – Check convergence every N iterations
divergence_factor – Divergence detection factor
score_limit – Stop training if score reaches this value
verbose – Verbosity level
- Returns:
Tuple of (iterations_completed, final_loss)
- emlearn_logreg.train_batches(model: Model, batch_iter_factory: Callable[[], Iterator[Tuple[array.array, array.array]]], max_iterations: int = ..., tolerance: float = ..., check_interval: int = ..., divergence_factor: float = ..., score_limit: float | None = ..., verbose: int = ..., score_batches: Callable[[Model], float] | None = ...) Tuple[int, float][source]
Train logistic regression model using externally provided batches.
- Parameters:
model – Logistic regression model instance
batch_iter_factory – Callable returning a fresh iterator over (X_batch, y_batch) tuples
max_iterations – Maximum number of training epochs
tolerance – Convergence tolerance
check_interval – Check convergence every N epochs
divergence_factor – Divergence detection factor
score_limit – Stop training if score reaches this value
verbose – Verbosity level
score_batches – Optional callable computing score from the model
- Returns:
Tuple of (iterations_completed, final_loss)
emlearn_extratrees - Learning decision tree ensembles
Extra Trees (Extremely Randomized Trees) classification.
Tree-based ensemble classifier with randomized splits.
- class emlearn_extratrees.Model[source]
An ExtraTrees ensemble model
Note: Use emlearn_extratrees.new to construct an instance
- predict(features: array.array, probabilities: array.array) int[source]
Make a prediction and fill the probabilities buffer.
- Parameters:
features – Input features, int16 array of n_features
probabilities – Output buffer, float32 array of n_classes (modified in-place)
- Returns:
Predicted class index
- train(X: array.array, y: array.array) None[source]
Train the model on the given data.
- Parameters:
X – Training features, int16 array of n_samples * n_features
y – Training labels, int16 array of n_samples
- emlearn_extratrees.new(n_features: int, n_classes: int, *, n_trees: int = ..., max_depth: int = ..., min_samples_leaf: int = ..., n_thresholds: int = ..., subsample_ratio: float = ..., feature_subsample_ratio: float = ..., max_nodes: int = ..., max_samples: int = ..., rng_seed: int = ..., use_global_feature_range: bool = ...) Model[source]
Construct a new ExtraTrees model.
- Parameters:
n_features – Number of input features
n_classes – Number of output classes
n_trees – Number of trees in the ensemble
max_depth – Maximum tree depth
min_samples_leaf – Minimum samples at a leaf node
n_thresholds – Random thresholds drawn per feature split
subsample_ratio – Fraction of samples used per tree (0.0-1.0)
feature_subsample_ratio – Fraction of features considered per split
max_nodes – Maximum pre-allocated nodes
max_samples – Maximum pre-allocated samples
rng_seed – Random number generator seed
use_global_feature_range – Use global feature range
- emlearn_extratrees.train_steps(model: Model, X: array.array, y: array.array) Iterator[int][source]
Generator for step-by-step training.
Yields the number of trees trained so far after each step. Returns when training is complete.
- Parameters:
model – ExtraTrees model instance
X – Training features, int16 array of n_samples * n_features
y – Training labels, int16 array of n_samples
- Returns:
Iterator yielding trees_trained count
emlearn_plsr - Partial Least Squares Regression (PLSR)
Partial Least Squares Regression (PLSR)
Implemented using eml_plsr from the emlearn C library (https://github.com/emlearn/emlearn).
- class emlearn_plsr.Model[source]
A PLSR model
Note: Use emlearn_plsr.new to construct an instance
- fit_start(X: array.array, y: array.array) None[source]
Start iterative fitting of the model.
- Parameters:
X – Training input data, float32 array of n_samples * n_features
y – Training target data, float32 array of n_samples
- predict(x: array.array) float[source]
Predict the target value for a single sample.
- Parameters:
x – Input features, float32 array of n_features
- Returns:
Predicted target value
- emlearn_plsr.fit(model: Model, X_train: array.array, y_train: array.array, max_iterations: int = ..., tolerance: float = ..., check_interval: int = ..., verbose: int = ...) Tuple[int, float][source]
Train the PLSR model using a NIPALS iterative fitting loop.
- Parameters:
model – PLSR model instance
X_train – Training input data, float32 array of n_samples * n_features
y_train – Training target data, float32 array of n_samples
max_iterations – Maximum iterations per component
tolerance – Convergence tolerance
check_interval – Check convergence every N iterations
verbose – Verbosity level
- Returns:
Tuple of (total_iterations, final_convergence_metric)
emlearn_cnn - Convolutional Neural Networks inference
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).
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: array.array, label: int)[source]
Add an item into the model
- Parameters:
values – the data/features of this item. Typecode ‘h’ (int16)
label – the label/class to associate with this item
- getitem(item: int, outputs: array.array)[source]
Access data of an item stored in the model
- Parameters:
item – Index of item
outputs – Where to copy the data from the item. Typecode ‘h’ (int16)
- emlearn_neighbors.new(max_items: int, features: int, k_neighbors: int) Model[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 – Maximum number of items in the dataset
features – Number of features in a data item
k_neighbors – Number of neighbors to consider
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: int)[source]
Fast Fourier Transform (FFT)
- fill(sin: array.array, cos: array.array)[source]
Set up FFT coefficients
Note: Do not use this directly. Instead use the module-level fill() function.
- Parameters:
sin – Precomputed coefficients
cos – Precomputed coefficients
- run(real: array.array, imag: array.array)[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 – the real part of data. Typecode ‘f’ (float)
imag – the imaginary part of data. Typecode ‘f’ (float)
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: array.array) IIR[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 – IIR filter coefficients
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: array.array, outputs: array.array, in_min: float, in_max: float, out_min: float, out_max: float)[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 – The input data
outputs – Where output is placed
in_min
in_max
out_min
out_max