braindecode.models.FNIRST#
- class braindecode.models.FNIRST(n_outputs=None, n_chans=None, chs_info=None, n_times=None, input_window_seconds=None, sfreq=None, *, embed_dim=64, depth=6, num_heads=8, mlp_dim=64, pool='cls', head_dim=64, n_conv_filters=8, spatial_kernel_size=5, temporal_kernel_size=30, temporal_stride=4, channel_order=None, drop_prob=0.0, embed_drop_prob=0.0, activation=<class 'torch.nn.modules.activation.GELU'>)[source]#
fNIRS-T from Wang et al. (2022).
Convolution Attention/Transformer
Added in version 2.1.
Figure of the authors’ repository (
fig/model.png, wzhlearning/fNIRS-Transformer at6ebe987f, MIT).#fNIRS-T [1] classifies fNIRS windows with a Transformer over two levels of tokens. A convolution turns the time course of each fNIRS channel (channel level) or of a group of consecutive channels (spatial level) into one token, and a Transformer lets these tokens attend to each other; time never becomes a token axis.
FNIRSPreTadds a learned preprocessing module in front. The description follows the authors’ code (model.py,KFold_Train.py,LOSO_Train.py), as the paper is not open access.Architecture Overview
In the figure’s symbols, \(H\) =
n_chans // 2fNIRS channels, \(W\) =n_times, \(C\) = 2 chromophores, \(H_S = H - k_s + 1\) spatial tokens, \(H_C = H\) channel tokens and \(D\) =embed_dim:input: H HbO rows and H HbR rows (batch, 2 H, W) to_chromophore_planes (batch, 2, H, W) Spatial level (to_patch_embedding, transformer_patch): Conv_S, Rearrange, Linear, LayerNorm (batch, H_S, D) prepend CLS, add positions, encoder (batch, H_S + 1, D) Channel level (to_channel_embedding, transformer_channel): Conv_C, Rearrange, Linear, LayerNorm (batch, H_C, D) prepend CLS, add positions, encoder (batch, H_C + 1, D) CLS token of each level, Concat (batch, 2 D) final_norm, final_layer (batch, n_outputs)
Macro Components
to_chromophore_planesInput. The rows ofxare split into the HbO and the HbR plane, from the stacked or MNE’s interleaved order.to_patch_embeddingSpatial level (“fNIRS Spatial Embedding”). \(\mathrm{Conv}_S\) maps the two planes to \(C_S\) =n_conv_filtersmaps with a \(k_s \times k_t\) kernel and stride \(1 \times s_t\), so each token covers \(k_s\) consecutive channels in the dataset’s order. The \(C_S \times W_S\) responses of a token are flattened, projected to \(D\) and layer-normalized.to_channel_embeddingChannel level (“fNIRS Channel Embedding”). The same with a \(1 \times k_t\) kernel (\(\mathrm{Conv}_C\)): one token per fNIRS channel.cls_token_*,pos_embedding_*,transformer_*Transformer Encoder. Each level prepends a learned class token, adds a learned positional embedding (one row per token, the token’s only identity), applies dropout and runsdepthpre-norm blocks of multi-head self-attention, with bias-free query, key and value maps, and a feed-forward layer of widthmlp_dim. Each of thenum_headsheads of width \(d_h\) =head_dimcomputes, as in the authors’Attention,\[\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\left( \frac{Q K^{\top}}{\sqrt{d_h}} \right) V .\]final_norm,final_layerHead. The class token of each level (or, withpool="mean", the mean of its tokens) is taken, and the two vectors are concatenated, layer-normalized and classified by a linear layer (the authors’mlp_head). The figure draws a head per level before the concatenation; the authors’ code, followed here, concatenates first.
Temporal, Spatial, and Spectral Encoding
Temporal. The convolutions slide a \(k_t\)-sample kernel with stride \(s_t\) along time, and the resulting values become the features of a token. The README’s segments are 140 samples (dataset A), 200 (B) and 256 (C). Kernels count samples, so
sfreqis unused. The authors’ datasets are A (mental arithmetic vs rest, 8 subjects, 52 channels), B (Shin et al. 2017, same task, 29 subjects, 36 channels) and C (Bak et al. 2019, finger and foot tapping, 3 classes, 30 subjects, 20 channels).Spatial. Channels, or groups of \(k_s\) consecutive channels, identified by their position in the token sequence: no montage or optode geometry, so the channels keep the order of training.
Spectral. None in the model: fNIRS-T expects segments band-passed (third-order Butterworth, 0.01-0.1 Hz,
filtfilt, on datasets B and C), baseline-corrected and z-scored per window;FNIRSPreTlearns that step.Chromophores. HbO and HbR are the two input planes, mixed by both convolutions from the first layer.
Additional Mechanisms
Reference. For the same weights the port matches the authors’ model to float32 rounding (max-abs below 1e-6 on their dataset A, B and C configurations). The positional tables have one row per token (the authors allocate 101 rows and slice). The attention always projects its output (the authors skip it when
num_heads=1andhead_dim=embed_dim). On dataset C with the authors’KFold_Train.py(seeds 0-2) the port gives 75.03 % accuracy against 74.73 % for the authors’ code and 75.49 % in the paper; forFNIRSPreTboth give 72.50 % (#1584).Read-out.
poolpicks the class token or the mean of the tokens; the output is logits. There is noch_mask: the spatial kernel and the positional tables span the whole montage.Pretrained weights. None: the authors release code, not weights.
- 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.embed_dim (
int) – \(D\), the width of the tokens (dimin the reference; 64 for its datasets A and B, 128 for C).depth (
int) – Transformer blocks per level.num_heads (
int) – Attention heads (headsin the reference).mlp_dim (
int) – Hidden width of the feed-forward layers.pool (
Literal['cls','mean']) – Read-out of each level: its class token, or the mean over its tokens (class token included).head_dim (
int) – \(d_h\), the width of each attention head (dim_headin the reference).n_conv_filters (
int) – \(C_S = C_C\), feature maps of both convolutions (authors: 8).spatial_kernel_size (
int) – \(k_s\), height of \(\mathrm{Conv}_S\) in HbO/HbR pairs (authors: 5), at mostn_chans // 2.temporal_kernel_size (
int) – \(k_t\), temporal kernel of both convolutions, in samples (authors: 30), at mostn_times.temporal_stride (
int) – \(s_t\), temporal stride of both convolutions, in samples (authors: 4).channel_order (
Optional[Literal['stacked','interleaved']]) –[HbO_1..HbO_H, HbR_1..HbR_H]or MNE’s[HbO_1, HbR_1, ...];Nonereads it fromchs_info.drop_prob (
float) – Dropout in the attention and feed-forward sub-layers (dropoutin the reference).embed_drop_prob (
float) – Dropout of the token embeddings (emb_dropoutin the reference).activation (
type[Module]) – Activation of the feed-forward sub-layers (authors: GELU).
- 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 FNIRST # Train your model model = FNIRST(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-fnirst-model", commit_message="Initial model upload", model_card_kwargs={"datasets": ["BNCI2014_001"]}, )
Loading a model from the Hub:
from braindecode.models import FNIRST # Load pretrained model model = FNIRST.from_pretrained("username/my-fnirst-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 = FNIRST.from_pretrained("username/my-fnirst-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 = FNIRST.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 fNIRS-T (and fNIRS-PreT) model.
- Parameters:
- Returns:
Logits with shape
(batch_size, n_outputs), or withreturn_features=Truethe dict{"features", "cls_token"}, both of shape(batch_size, 2 * embed_dim).- 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.