coco_pipe.decoding.mil ====================== .. py:module:: coco_pipe.decoding.mil .. autoapi-nested-parse:: Multiple-Instance Learning Estimators ===================================== 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 ------- .. autoapisummary:: coco_pipe.decoding.mil.ABMILClassifier Module Contents --------------- .. py:class:: 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: :py:obj:`sklearn.base.ClassifierMixin`, :py:obj:`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 :class:`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 :class:`~coco_pipe.decoding.Experiment`'s fold-local pipeline. :param att_dim: Hidden dimension of the attention network. :type att_dim: int, default=64 :param att_act: Activation inside the attention network. :type att_act: {"tanh", "relu", "gelu"}, default="tanh" :param gated: Use gated attention (``tanh * sigmoid``) [1]_. :type gated: bool, default=True :param hidden_dim: Width of the instance projection (``Linear -> ReLU -> Dropout``); ``None`` uses the instances as they are. :type hidden_dim: int or None, default=64 :param dropout: Dropout of the instance projection. :type dropout: float, default=0.25 :param max_instances: 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. :type max_instances: int or None, default=None :param max_epochs: Maximum training epochs. :type max_epochs: int, default=200 :param patience: Epochs without a lower validation loss before training stops; the best epoch's weights are kept. :type patience: int, default=20 :param batch_size: Bags per optimizer step. :type batch_size: int, default=32 :param lr: AdamW learning rate. :type lr: float, default=1e-3 :param weight_decay: AdamW weight decay. :type weight_decay: float, default=1e-2 :param val_fraction: Fraction of training bags held out (stratified) for early stopping. ``0.0``, or too few bags of a class, trains for ``max_epochs``. :type val_fraction: float, default=0.2 :param n_restarts: Networks trained from different seeds whose probabilities are averaged (an addition to [1]_ that lowers seed variance on small samples). :type n_restarts: int, default=1 :param device: Torch device; ``"auto"`` uses CUDA when available. :type device: {"cpu", "cuda", "auto"}, default="cpu" :param random_state: Seed of restart 0; restart ``r`` uses ``random_state + r``. :type random_state: int or None, default=0 :ivar nets_: The fitted networks, one per restart. :vartype nets_: list of skorch.NeuralNetBinaryClassifier :ivar classes_: Class labels; ``classes_[1]`` is the positive class. :vartype classes_: ndarray of shape (2,) :ivar last_attention_: Attention weights of the last :meth:`predict_proba` call (summing to 1 within each bag, averaged over restarts). :vartype last_attention_: ndarray of shape (n_instances,) or None .. rubric:: Notes All bags are zero-padded to the longest one in memory, so one very long bag costs memory for every bag. .. rubric:: References .. [1] Ilse, M., Tomczak, J. M., & Welling, M. (2018). Attention-based deep multiple instance learning. ICML. .. py:attribute:: att_dim :value: 64 .. py:attribute:: att_act :value: 'tanh' .. py:attribute:: gated :value: True .. py:attribute:: hidden_dim :value: 64 .. py:attribute:: dropout :value: 0.25 .. py:attribute:: max_instances :value: None .. py:attribute:: max_epochs :value: 200 .. py:attribute:: patience :value: 20 .. py:attribute:: batch_size :value: 32 .. py:attribute:: lr :value: 0.001 .. py:attribute:: weight_decay :value: 0.01 .. py:attribute:: val_fraction :value: 0.2 .. py:attribute:: n_restarts :value: 1 .. py:attribute:: device :value: 'cpu' .. py:attribute:: random_state :value: 0 .. py:method:: get_metadata_routing() Request bag IDs (``groups``) on fit, predict and predict_proba. .. py:method:: fit(X, y, groups = None) Fit ``n_restarts`` networks on the bags given by *groups*. :param X: Instance features. :type X: array-like of shape (n_instances, n_features) :param y: Binary labels, constant within each bag. :type y: array-like of shape (n_instances,) :param groups: Bag ID of each instance. :type groups: array-like of shape (n_instances,) :returns: **self** -- The fitted estimator. :rtype: ABMILClassifier :raises ValueError: If *groups* is missing or misaligned, *X* is not 2D, *y* is not binary, or a bag holds two labels. .. py:method:: predict_proba(X, groups = None) Probabilities of each instance's bag, one row per instance. Also stores each instance's attention weight in :attr:`last_attention_`. :param X: Instance features. :type X: array-like of shape (n_instances, n_features) :param groups: Bag ID of each instance. :type groups: array-like of shape (n_instances,) :returns: **proba** -- Class probabilities, averaged over restarts. :rtype: ndarray of shape (n_instances, 2) .. py:method:: predict(X, groups = None) Label of each instance's bag (probability of ``classes_[1]`` >= 0.5). .. py:method:: get_artifact_metadata() Attention weights of the last prediction, per instance.