braindecode.models.FNIRSPreT#
- class braindecode.models.FNIRSPreT(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'>, preprocessing_kernel_sizes=(5, 13, 7))[source]#
fNIRS-PreT from Wang et al. (2022).
Convolution Attention/Transformer
Added in version 2.1.
The figure of the authors’ repository (
fig/model.pngof wzhlearning/fNIRS-Transformer at6ebe987f, MIT); fNIRS-PreT is its right-hand input path.#fNIRS-T expects signals that were band-pass filtered and baseline-corrected by hand. fNIRS-PreT [1] replaces these steps by a preprocessing module of one-dimensional average pooling and layer normalization, which makes the network end-to-end.
Architecture Overview
This is
FNIRSTwith the preprocessing module (pre) first, as the authors’fNIRS_PreT(PreBlock, thenfNIRS_T, inmodel.py). With \(H\) =n_chans // 2channels and \(W\) =n_timessamples:input: H HbO rows and H HbR rows (batch, 2 H, W) to_chromophore_planes (batch, 2, H, W) pre: per plane, average_pooling, norms[i] (batch, 2, H, W) fNIRS-T levels, Concat, head (batch, n_outputs)
Macro Components
pre.average_poolingAverage pooling. Moving averages along time, oneAvgPool1dper entry ofpreprocessing_kernel_sizes(kernels \(k\) = 5, 13 and 7 by default, the authors’pool1,pool2andpool3), stride 1 and “same” zero padding, shared by HbO and HbR. With \(k = 2r + 1\), each is\[m_k(x)[t] = \frac{1}{k} \sum_{j=-r}^{r} x[t + j] .\]pre.normsLayer normalization. OneLayerNormover the \(W\) samples per chromophore (the authors’ln_0,ln_1): each channel row is centred and scaled over the window, then given a learned scale and shift per sample, so the weights are tied ton_times.Every other module, the input layout, the logits and the other parameters are those of
FNIRST.
Temporal, Spatial, and Spectral Encoding
The rest is as in
FNIRST; the preprocessing module adds:Temporal. The module keeps the \(W\) samples: the moving averages run along time and the LayerNorms normalize over them.
Spatial. Every channel row is treated alike.
Spectral. No explicit frequency decomposition: the module stands in for the filtering and baseline correction, so the inputs are raw segmented concentration changes.
Chromophores. HbO and HbR share the moving averages and have their own LayerNorm.
Additional Mechanisms
Reference. For the same weights the port and the authors’ model agree to float32 rounding (max-abs below 1e-6 on the dataset A, B and C configurations). The port indexes each chromophore plane, where the authors’
PreBlockcallssqueeze(), which also drops the batch axis for a batch of one. The dataset C replication is the fNIRS-PreT result ofFNIRST(72.50 % for the port and for the authors’ code); both received the filtered, baseline-corrected windows of fNIRS-T, as the releasedLoad_Dataset_Chas no raw-data path (#1584).Raw input. The README disables the filtering and baseline correction of
B_mat2xls.mandC_mat2xls.mfor fNIRS-PreT, andLoad_Dataset_Askips the dataset A filters.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).preprocessing_kernel_sizes (
tuple[int,...]) – Kernel of each moving average of the preprocessing module, in samples, each odd so that the paddingk // 2keepsn_times; the default is that ofPreBlockin the authors’model.py.
- 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 FNIRSPreT # Train your model model = FNIRSPreT(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-fnirspret-model", commit_message="Initial model upload", model_card_kwargs={"datasets": ["BNCI2014_001"]}, )
Loading a model from the Hub:
from braindecode.models import FNIRSPreT # Load pretrained model model = FNIRSPreT.from_pretrained("username/my-fnirspret-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 = FNIRSPreT.from_pretrained("username/my-fnirspret-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 = FNIRSPreT.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.