braindecode.models.FNIRSNet#

class braindecode.models.FNIRSNet(n_outputs=None, n_chans=None, chs_info=None, n_times=None, input_window_seconds=None, sfreq=None, *, n_dhr_filters=4, n_pw_filters=8, dhr_kernel_length=None, activation=<class 'torch.nn.modules.activation.Sigmoid'>)[source]#

fNIRSNet from Wang et al. (2023).

Convolution

Added in version 2.1.

fNIRSNet architecture

Fig. 2 of Wang et al. (2023), cropped (CC BY 4.0).#

fNIRSNet [1] classifies HbO/HbR windows with three convolutions and one linear layer, without pooling or dropout. Delayed hemodynamic responses are slow, so the first convolution spans the whole window of one row and the second spans all rows. With 4 and 8 filters it has 498 parameters on mental arithmetic (Table III).

Architecture Overview

It has a delayed hemodynamic response module (DHR Module) and a global module (Section II-B, Table I). With \(C\) = n_chans rows, \(S\) = n_times samples, \(F_1\) and \(F_2\) filters, and \(S' = S - k + 1\) (1 for the paper’s kernel width \(k = S\)):

x                                       (batch, C, S)
- to_fnirs_tensor                       (batch, 1, C, S)
- conv1 (1 x k), bn1, act1              (batch, F_1, C, S')
- conv2.depth_conv (C x 1)              (batch, F_1, 1, S')
- conv2.point_conv (1 x 1), bn2, act2   (batch, F_2, 1, S')
- flatten, final_layer                  (batch, n_outputs)

Macro Components

  • conv1, bn1, act1 DHR Module. The delayed hemodynamic response convolution (DHRConv) is a standard convolution with \(F_1\) filters of \(1 \times k\): one filter reads the whole slow response of one row (Guideline 1), and it is not depthwise separable, which performs poorly in low dimension (Guideline 2). Batch normalization and a saturating activation follow (Guideline 3: sigmoid, tanh and ELU beat ReLU and leaky ReLU in Table VI; the paper uses the sigmoid).

  • conv2, bn2, act2 Global Module. A depthwise separable convolution: depth_conv has one \(C \times 1\) filter per DHR map, a global receptive field over the rows without stacking layers, and point_conv projects the \(F_1\) maps onto \(F_2\). It costs \(F_1 (C + F_2)\) multiply-adds per output position instead of the \(F_1 C F_2\) of a standard convolution (Eqs. (2) and (3)), so a longer input only adds to the cost of DHRConv. Batch normalization and the activation follow. Table I lists \(F_2\) filters for DWConv, but the authors’ DWSConv has \(F_1\) depthwise filters and an \(F_1 \to F_2\) PWConv; this module follows the code, which gives Table III’s parameter counts (498 and 419 subject-specific, 2,370 and 2,051 subject-independent).

  • final_layer Classifier. One linear layer on the flattened maps. The paper’s softmax is left to the loss, so the model returns logits. The modules keep the authors’ names (conv1, bn1, conv2.depth_conv, conv2.point_conv, bn2) except fc, now final_layer.

Temporal, Spatial, and Spectral Encoding

  • Temporal. One window of \(S\) samples, 3 s in the paper (30 at 10 Hz, 40 at 13.3 Hz). DHRConv covers all of it, and the kernel counts samples, so the model takes no sampling rate.

  • Spatial. No montage or optode geometry: DWConv has one weight per row, so the rows keep the order of training. chs_info is not read.

  • Spectral. None in the model; the paper band-passes the concentration changes to 0.01-0.1 Hz beforehand (third-order Butterworth, zero-phase), corrects the baseline and z-scores each 3 s window, cut with a 1 s step (Section III-B).

  • Chromophores. \(C\) is twice the number of fNIRS channels (HbO and HbR, Section II-B); as in Fig. 2(a) and the authors’ loaders, all HbO rows come first, then all HbR rows.

Additional Mechanisms

  • Reference. In the authors’ training loops on UFFT (seeds 0-2) the port and the authors’ fNIRSNet agree within 0.01 point of accuracy and macro-F1 (#1579); the subject-independent runs use the \(F_1 = 8\), \(F_2 = 16\) of the authors’ LOSO_Train.py, not the paper’s 16 and 32.

  • Pretrained weights. None: the authors release code, not weights, and the paper trains one model per subject or per left-out subject. There is no ch_mask.

License

Parameters:
  • n_outputs (int | None) – Number of outputs of the model. This is the number of classes in the case of classification.

  • n_chans (int | None) – Number of EEG channels.

  • chs_info (list[dict] | None) – Information about each individual EEG channel. This should be filled with info["chs"]. Refer to mne.Info for more details.

  • n_times (int | None) – Number of time samples of the input window.

  • input_window_seconds (float | None) – Length of the input window in seconds.

  • sfreq (float | None) – Sampling frequency of the EEG recordings.

  • n_dhr_filters (int) – \(F_1\), the DHRConv filters (num_DHRConv in the reference): 4 for subject-specific and 16 for subject-independent training in the paper (Section III-D).

  • n_pw_filters (int) – \(F_2\), the PWConv filters (num_DWConv in the reference): 8 and 32 in the paper, which recommends at least \(2 F_1\) (Section IV-F).

  • dhr_kernel_length (int | None) – DHRConv width \(k\) (DHRConv_width in the reference), 1 <= k <= n_times; None uses \(S\) (Guideline 1). A shorter kernel is an addition to the paper’s linear layer, which fits only \(k = S\) (Table IV tries 10, 20 and 30 on UFFT): the layer then reads \(F_2 (S - k + 1)\) values.

  • activation (type[Module]) – Activation after each batch normalization (act in the reference).

Raises:

ValueError – If some input signal-related parameters are not specified: and can not be inferred.

Notes

If some input signal-related parameters are not specified, there will be an attempt to infer them from the other parameters.

References

Hugging Face Hub integration

When the optional huggingface_hub package is installed, all models automatically gain the ability to be pushed to and loaded from the Hugging Face Hub. Install with:

pip install braindecode[hub]

Pushing a model to the Hub:

from braindecode.models import FNIRSNet

# Train your model
model = FNIRSNet(n_chans=22, n_outputs=4, n_times=1000)
# ... training code ...

# Push to the Hub; ``datasets`` and ``base_model`` go to the card
model.push_to_hub(
    repo_id="username/my-fnirsnet-model",
    commit_message="Initial model upload",
    model_card_kwargs={"datasets": ["BNCI2014_001"]},
)

Loading a model from the Hub:

from braindecode.models import FNIRSNet

# Load pretrained model
model = FNIRSNet.from_pretrained("username/my-fnirsnet-model")
# Data the weights were trained on, from the Hub model card
print(model.card_data.datasets if model.card_data else None)

# Load with a different number of outputs (head is rebuilt automatically)
model = FNIRSNet.from_pretrained("username/my-fnirsnet-model", n_outputs=4)

Extracting features and replacing the head:

import torch

x = torch.randn(1, model.n_chans, model.n_times)
# Extract encoder features and a mean-pooled 2-D embedding
out = model(x, return_features=True)
embedding = out["embedding"]  # (batch, dim)
features = out["features"]

# Replace the classification head
model.reset_head(n_outputs=10)

Note that torch.jit.script returns features only on models whose forward declares return_features.

Saving and restoring full configuration:

import json

config = model.get_config()            # all __init__ params
with open("config.json", "w") as f:
    json.dump(config, f)

model2 = FNIRSNet.from_config(config)    # reconstruct (no weights)

All model parameters (both EEG-specific and model-specific such as dropout rates, activation functions, number of filters) are automatically saved to the Hub and restored when loading.

See Loading and Adapting Pretrained Foundation Models for a complete tutorial.

Methods

forward(x, return_features=False)[source]#

Forward pass of the fNIRSNet model.

Parameters:
  • x (Tensor) – Input tensor with shape (batch_size, n_chans, n_times).

  • return_features (bool) – If True, return the flattened features that feed the FC layer.

Returns:

Logits with shape (batch_size, n_outputs), or with return_features=True the dict {"features", "cls_token"}, features of shape (batch_size, n_pw_filters * time') and cls_token None.

Return type:

Tensor | dict[str, Tensor | None]

reset_head(n_outputs)[source]#

Replace the classification head for a new number of outputs.

This is called automatically by from_pretrained() when the user passes an n_outputs that differs from the saved config, and attaches a head to a model built with n_outputs=None. The default replaces the last linear or convolutional layer of final_layer by a new one with n_outputs outputs, and raises NotImplementedError when that layer is constrained, when final_layer holds more than one such layer, or when it does not end with one. Override in subclasses that need a model-specific head structure. Implementations keep changed constructor arguments in sync with self._update_init_kwargs, so that a saved model can be loaded back. Implementations requiring positive outputs can also use self._set_n_outputs to validate and record the new value.

Parameters:

n_outputs (int) – New number of output classes.

Return type:

None

Examples

>>> from braindecode.models import BENDR
>>> model = BENDR(n_chans=22, n_times=1000, n_outputs=4)
>>> model.reset_head(10)
>>> model.n_outputs
10

Added in version 1.4.