Skip to content
GitHub · 2.7.0

Guides

Add a custom model

Pipeline accepts any pickleable model, including Sklearn, CatBoost, PyTorch, state machines and lookup tables. For unpickleable models, provide save_model / load_model.

The protocol uses three decorators on plain functions. No inheritance is required.

Python
from myogestic.ml import Pipeline, save_pickle, load_pickle
from myogestic.session import iter_labeled_windows
pipeline = Pipeline(app, predict_hz=20)
pipeline.save_model = save_pickle # or your own
pipeline.load_model = load_pickle
@pipeline.extract
def extract(windows):
return windows["emg"] # whatever shape downstream wants
@pipeline.train
def train(data):
X, y = [], []
for window, ts, cls in iter_labeled_windows(data.paths, "emg", window_ms=200, hop_ms=100):
X.append(rms_features(window))
y.append(cls)
model = MyClassifier().fit(np.array(X), np.array(y))
return model
@pipeline.predict
def predict(model, features):
pred = model.predict(features.reshape(1, -1))[0]
return {"class": int(pred)}

Case 1: scikit-learn / CatBoost / XGBoost

Train returns a fitted estimator; predict calls it. See examples/synthetic/emg_classification.py for the reference pattern.

Python
@pipeline.train
def train(data):
if data.is_empty:
raise ValueError("Tick at least one session.")
X, y = build_dataset(data.paths)
model = CatBoostClassifier(iterations=500, depth=6, verbose=False)
model.fit(X, y)
return model # whatever you return goes to predict() unchanged
@pipeline.predict
def predict(model, features):
cls = int(model.predict(features.reshape(1, -1))[0])
return {"class": cls, "name": CLASSES[cls]}

save_pickle saves and loads CatBoost / sklearn / XGBoost models.

Case 2: PyTorch model

PyTorch models can pickle their weights. Handle CUDA-vs-CPU device selection on load:

Python
import torch
@pipeline.train
def train(data):
X, y = build_dataset(data.paths)
X_t = torch.tensor(X, dtype=torch.float32, device="cuda")
y_t = torch.tensor(y, dtype=torch.long, device="cuda")
net = MyNet(n_in=X.shape[1], n_classes=N).cuda()
optim = torch.optim.Adam(net.parameters(), lr=1e-3)
for _ in range(100):
... # standard training loop
net.eval()
return net
@pipeline.predict
def predict(model, features):
x = torch.tensor(features, dtype=torch.float32, device="cuda")
with torch.no_grad():
logits = model(x.unsqueeze(0))
cls = int(logits.argmax(-1).cpu().item())
return {"class": cls}

Custom save/load to handle device:

Python
def save_torch(model, path):
torch.save(
{
"state_dict": model.state_dict(),
"config": {"n_in": model.n_in, "n_classes": model.n_classes},
},
path,
)
def load_torch(path):
blob = torch.load(path, map_location="cuda")
net = MyNet(**blob["config"]).cuda()
net.load_state_dict(blob["state_dict"])
net.eval()
return net
pipeline.save_model = save_torch
pipeline.load_model = load_torch

Case 3: regression (continuous targets)

Use iter_aligned_windows to pair each EMG window with a synchronized target vector. iter_labeled_windows supplies class labels.

Python
from myogestic.session import iter_aligned_windows
@pipeline.train
def train(data):
X, Y = [], []
for window, targets, ts in iter_aligned_windows(
data.paths,
primary_stream_name="emg",
aligned_stream_names=["vhi_guide"],
window_ms=200,
hop_ms=50,
):
X.append(rms_features(window))
Y.append(targets["vhi_guide"])
return MultiOutputRegressor().fit(np.array(X), np.array(Y))

See examples/synthetic/emg_regression.py for the complete regression example, including a fallback to iter_labeled_windows when no aligned target stream was recorded.

Pushing predictions to outputs

The returned dict goes into pipeline.predictions for widgets. To drive a device, also push to its ControlBus from inside predict(). This example assumes the map has a continuous grip alias:

Python
@pipeline.predict
def predict(model, features):
pose = model.predict(features.reshape(1, -1))[0]
pose_smooth = pose_filter(pose, timestamp=time.monotonic())
bus.push({"grip": float(pose_smooth[0])}) # to the target
return {"pose": pose_smooth} # to widgets / pipeline.predictions

Both run on the predict thread; no synchronization is needed.

Stale-tick guard

If your model is stateful, accept timestamps and ignore stale ticks:

Python
@pipeline.extract
def extract(windows):
emg, ts = emg_stream.get_window()
last_ts = float(ts[-1]) if ts.size > 0 else None
return (emg, last_ts)
@pipeline.predict
def predict(model, features):
emg, last_ts = features
return {"state": model.step(emg, last_ts=last_ts)}

The model’s step should return the previous state if last_ts <= self._last_ts.

Common mistakes

See Troubleshooting for errors by symptom.

  • Returning a non-dict from predict(). Silently dropped. Always return {...}.
  • Forgetting to set pipeline.save_model. The Save button stays disabled until a model and save callback are available.
  • Share feature extraction. Putting it only in train() leaves predict() running different code on the same window shape. Use one extract() for training and prediction, or a shared featurize(window) -> features helper.
  • Train on the training thread. Call model.fit() from train(). Calling it from predict() blocks prediction. Training has its own thread and state.
  • Separate effort and direction for a two-directional DOF. Amplitude alone gives effort without direction. A regressor on raw features can learn the louder cue and move the output the wrong way as contraction increases. Use directional_decoder to estimate effort and direction separately and multiply them.
  • Profile predict(). predict_hz sets a target rate. A model that takes 100 ms cannot keep up with predict_hz=50, a 20 ms interval. Lower predict_hz or speed up the model.