coco_pipe.decoding.mil#

A scikit-learn classifier for bags of instances (e.g. the windows of one recording or subject): attention pooling from torchmil, trained with skorch. Bags are given by the groups metadata parameter.

Classes#

ABMILClassifier

Attention-based multiple-instance learning (ABMIL) binary classifier.

Module Contents#

class coco_pipe.decoding.mil.ABMILClassifier(att_dim=64, att_act='tanh', gated=True, hidden_dim=64, dropout=0.25, max_instances=None, max_epochs=200, patience=20, batch_size=32, lr=0.001, weight_decay=0.01, val_fraction=0.2, n_restarts=1, device='cpu', random_state=0)#

Bases: sklearn.base.ClassifierMixin, sklearn.base.BaseEstimator

Attention-based multiple-instance learning (ABMIL) binary classifier.

Each bag (the instances sharing a groups value) gets one score: its instances are projected, weighted by (gated) attention [1] and pooled. The network is torchmil.models.ABMIL, trained with skorch on AdamW and a class-weighted logistic loss. Instances are 2D rows; scaling or PCA runs upstream, e.g. in Experiment’s fold-local pipeline.

Parameters:
  • att_dim (int, default=64) – Hidden dimension of the attention network.

  • att_act ({"tanh", "relu", "gelu"}, default="tanh") – Activation inside the attention network.

  • gated (bool, default=True) – Use gated attention (tanh * sigmoid) [1].

  • hidden_dim (int or None, default=64) – Width of the instance projection (Linear -> ReLU -> Dropout); None uses the instances as they are.

  • dropout (float, default=0.25) – Dropout of the instance projection.

  • max_instances (int or None, default=None) – Instances drawn at random from each bag per training batch, to bound memory and vary the instances seen; None keeps all. Validation and prediction use every instance.

  • max_epochs (int, default=200) – Maximum training epochs.

  • patience (int, default=20) – Epochs without a lower validation loss before training stops; the best epoch’s weights are kept.

  • batch_size (int, default=32) – Bags per optimizer step.

  • lr (float, default=1e-3) – AdamW learning rate.

  • weight_decay (float, default=1e-2) – AdamW weight decay.

  • val_fraction (float, default=0.2) – Fraction of training bags held out (stratified) for early stopping. 0.0, or too few bags of a class, trains for max_epochs.

  • n_restarts (int, default=1) – Networks trained from different seeds whose probabilities are averaged (an addition to [1] that lowers seed variance on small samples).

  • device ({"cpu", "cuda", "auto"}, default="cpu") – Torch device; "auto" uses CUDA when available.

  • random_state (int or None, default=0) – Seed of restart 0; restart r uses random_state + r.

Variables:
  • nets (list of skorch.NeuralNetBinaryClassifier) – The fitted networks, one per restart.

  • classes (ndarray of shape (2,)) – Class labels; classes_[1] is the positive class.

  • last_attention (ndarray of shape (n_instances,) or None) – Attention weights of the last predict_proba() call (summing to 1 within each bag, averaged over restarts).

Notes

All bags are zero-padded to the longest one in memory, so one very long bag costs memory for every bag.

References

att_dim = 64#
att_act = 'tanh'#
gated = True#
hidden_dim = 64#
dropout = 0.25#
max_instances = None#
max_epochs = 200#
patience = 20#
batch_size = 32#
lr = 0.001#
weight_decay = 0.01#
val_fraction = 0.2#
n_restarts = 1#
device = 'cpu'#
random_state = 0#
get_metadata_routing()#

Request bag IDs (groups) on fit, predict and predict_proba.

fit(X, y, groups=None)#

Fit n_restarts networks on the bags given by groups.

Parameters:
  • X (array-like of shape (n_instances, n_features)) – Instance features.

  • y (array-like of shape (n_instances,)) – Binary labels, constant within each bag.

  • groups (array-like of shape (n_instances,)) – Bag ID of each instance.

Returns:

self – The fitted estimator.

Return type:

ABMILClassifier

Raises:

ValueError – If groups is missing or misaligned, X is not 2D, y is not binary, or a bag holds two labels.

predict_proba(X, groups=None)#

Probabilities of each instance’s bag, one row per instance.

Also stores each instance’s attention weight in last_attention_.

Parameters:
  • X (array-like of shape (n_instances, n_features)) – Instance features.

  • groups (array-like of shape (n_instances,)) – Bag ID of each instance.

Returns:

proba – Class probabilities, averaged over restarts.

Return type:

ndarray of shape (n_instances, 2)

predict(X, groups=None)#

Label of each instance’s bag (probability of classes_[1] >= 0.5).

Parameters:
  • X (Any)

  • groups (Any)

Return type:

numpy.ndarray

get_artifact_metadata()#

Attention weights of the last prediction, per instance.

Return type:

dict[str, Any]