braindecode.models.FNIRSCNN1D#

class braindecode.models.FNIRSCNN1D(n_outputs=None, n_chans=None, chs_info=None, n_times=None, input_window_seconds=None, sfreq=None, *, n_filters_conv1=64, n_filters_conv2=128, kernel_size_conv1=7, kernel_size_conv2=5, pool_size=2, n_norm_groups=8, drop_prob=0.5, activation=<class 'torch.nn.modules.activation.GELU'>)[source]#

FNIRSCNN1D, the 1D-CNN of Trakoolwilaiwan et al. (2018), as in GeoNIRS.

Convolution

FNIRSCNN1D architecture

Input of the CNN of Trakoolwilaiwan et al.: a filter spanning all HbO and HbR channels slides along time, reproduced from [1] (CC BY 3.0).#

Added in version 2.1.

Two temporal convolutions, an average over time and a linear layer: the 1D-CNN baseline of the GeoNIRS benchmark [2] (Section 3.1; the “1D-CNN” rows of Tables 1, 14 and 15, and 88.4 K parameters in Table 10), after the fNIRS networks of Trakoolwilaiwan et al. [1] for rest, right- and left-hand motor execution. This class ports the DirectEventCNN1DClassifier of the GeoNIRS repository (commit 81f8995) as its benchmark builds it, one classifier per event window. Its GroupNorm and GELU stages are the GeoNIRS authors’ own; the networks of Trakoolwilaiwan et al. use one or three convolutions of kernel 3 with max pooling and dropout.

Architecture Overview

With \(B\) the batch size, \(C\) = n_chans, \(T\) = n_times and \(F_1\), \(F_2\) the two filter counts:

x                                                     (B, C, T)
- temporal_conv1: Conv1d, GroupNorm, GELU, MaxPool1d  (B, F_1, T // 2)
- temporal_conv2: Conv1d, GroupNorm, GELU             (B, F_2, T // 2)
- time_pool, flatten_layer, head_dropout              (B, F_2)
- final_layer                                         (B, n_outputs)

Macro Components

  • FNIRSCNN1D.temporal_conv1 First temporal convolution. A Conv1d whose filters read all the rows (7 samples, 1.4 s at the 5 Hz of the GeoNIRS inputs), GroupNorm, GELU and a MaxPool1d that halves the time axis.

  • FNIRSCNN1D.temporal_conv2 Second temporal convolution. A Conv1d (5 samples, 2 s of the input at half rate), GroupNorm and GELU.

  • FNIRSCNN1D.time_pool, FNIRSCNN1D.flatten_layer, FNIRSCNN1D.head_dropout, FNIRSCNN1D.final_layer Classification head. An average over time (AdaptiveAvgPool1d), which lets the model take a window of any length, then Dropout and one Linear.

Temporal, Spatial, and Spectral Encoding

  • Temporal. Two short kernels and one halving of the rate. The final average discards the position of a response, so the window is read as a bag of short patterns.

  • Spatial. None: the first convolution mixes every row and chs_info is not read.

  • Spectral. None.

  • Chromophores. HbO and HbR are ordinary rows, in the order used in training: the GeoNIRS benchmark stacks all HbO rows before the HbR rows, HbO_1, ..., HbO_C, HbR_1, ..., HbR_C.

Additional Mechanisms

  • Missing samples. A NaN or inf marks a missing sample and is read as zero, as the reference does with its validity mask; that mask covers both chromophores of a pair, so a sample missing in one of them should be NaN in both. There is no ch_mask: the first convolution spans every row.

  • Reference. With the same seed this class and the authors’ module draw the same weights, and the same weights give the same logits (max-abs 0.0), in eval mode and in train mode. Through the authors’ training loop it gives 55.85 and 50.22 macro-F1 on DS42 and DS19, against 55.53 and 50.05 in the paper, and AUROC within 1.1 points (#1592). The reference’s event_pair_mode (events of a pair aggregated before the head) is off in the benchmark and absent here.

  • Inputs. The benchmark feeds HbO and HbR in µmol/L, resampled to 5 Hz and z-scored per recording (GeoNIRS Appendix B.1.1; its baselines get the same inputs, Appendix B.5.3).

  • Pretrained weights. None: the baseline is trained from scratch on each task.

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_filters_conv1 (int) – Filters of the first temporal convolution (conv_dim in the reference).

  • n_filters_conv2 (int) – Filters of the second temporal convolution, and the feature size (embedding_dim in the reference).

  • kernel_size_conv1 (int) – Kernel length of the first temporal convolution, in samples; an odd length keeps the reference’s symmetric padding.

  • kernel_size_conv2 (int) – Kernel length of the second temporal convolution, in samples; an odd length keeps the reference’s symmetric padding.

  • pool_size (int) – Length and stride of the max pooling after the first convolution.

  • n_norm_groups (int) – Groups of both GroupNorm layers. It must divide both filter counts.

  • drop_prob (float) – Dropout probability before final_layer (dropout in the reference).

  • activation (type[Module]) – Activation after each GroupNorm.

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 FNIRSCNN1D

# Train your model
model = FNIRSCNN1D(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-fnirscnn1d-model",
    commit_message="Initial model upload",
    model_card_kwargs={"datasets": ["BNCI2014_001"]},
)

Loading a model from the Hub:

from braindecode.models import FNIRSCNN1D

# Load pretrained model
model = FNIRSCNN1D.from_pretrained("username/my-fnirscnn1d-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 = FNIRSCNN1D.from_pretrained("username/my-fnirscnn1d-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 = FNIRSCNN1D.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 FNIRSCNN1D model.

Parameters:
  • x (Tensor) – Input tensor with shape (batch_size, n_chans, n_times). A non-finite value (NaN or inf) marks a missing sample and is read as zero.

  • return_features (bool) – If True, return the input of final_layer instead of the logits.

Returns:

Output tensor with shape (batch_size, n_outputs), or {"features": (batch_size, n_filters_conv2), "cls_token": None} with return_features=True.

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.