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
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
DirectEventCNN1DClassifierof the GeoNIRS repository (commit81f8995) 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_timesand \(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_conv1First temporal convolution. AConv1dwhose filters read all the rows (7 samples, 1.4 s at the 5 Hz of the GeoNIRS inputs),GroupNorm, GELU and aMaxPool1dthat halves the time axis.FNIRSCNN1D.temporal_conv2Second temporal convolution. AConv1d(5 samples, 2 s of the input at half rate),GroupNormand GELU.FNIRSCNN1D.time_pool,FNIRSCNN1D.flatten_layer,FNIRSCNN1D.head_dropout,FNIRSCNN1D.final_layerClassification head. An average over time (AdaptiveAvgPool1d), which lets the model take a window of any length, thenDropoutand oneLinear.
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_infois 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.chs_info (
list[dict] |None) – Information about each individual EEG channel. This should be filled withinfo["chs"]. Refer tomne.Infofor 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_dimin the reference).n_filters_conv2 (
int) – Filters of the second temporal convolution, and the feature size (embedding_dimin 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 bothGroupNormlayers. It must divide both filter counts.drop_prob (
float) – Dropout probability beforefinal_layer(dropoutin the reference).activation (
type[Module]) – Activation after eachGroupNorm.
- 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_hubpackage 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.scriptreturns features only on models whoseforwarddeclaresreturn_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:
- Returns:
Output tensor with shape (batch_size, n_outputs), or
{"features": (batch_size, n_filters_conv2), "cls_token": None}withreturn_features=True.- Return type:
- 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 ann_outputsthat differs from the saved config, and attaches a head to a model built withn_outputs=None. The default replaces the last linear or convolutional layer offinal_layerby a new one withn_outputsoutputs, and raisesNotImplementedErrorwhen that layer is constrained, whenfinal_layerholds 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 withself._update_init_kwargs, so that a saved model can be loaded back. Implementations requiring positive outputs can also useself._set_n_outputsto validate and record the new value.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.