braindecode.models.EEGModuleMixin#

class braindecode.models.EEGModuleMixin(n_outputs=None, n_chans=None, chs_info=None, n_times=None, input_window_seconds=None, sfreq=None, channel_strategy='native', channel_strategy_kwargs=None)[source]#

Mixin class for all EEG models in braindecode.

This class integrates with Hugging Face Hub when the huggingface_hub package is installed, enabling models to be pushed to and loaded from the Hub using push_to_hub() and from_pretrained() methods.

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

  • n_chans (Optional[int]) – Number of EEG channels.

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

  • n_times (Optional[int]) – Number of time samples of the input window.

  • input_window_seconds (Optional[float]) – Length of the input window in seconds.

  • sfreq (Optional[float]) – Sampling frequency of the EEG recordings.

  • channel_strategy (str) – How any montage reaches the backbone (pretrained models only; see Channel strategies: any montage in). "native" keeps the model as it is. "exact", "zero", "nearest", "idw", "spline", "field", "source", "region", "wiener" (call model.channel_layer.fit first) or "latent" map the montage of chs_info (or of the chs_info given to forward) onto the backbone’s channels with a ChannelLayer. Saved in the config. model(x) and model.forward(x) both apply the layer.

  • channel_strategy_kwargs (Optional[dict]) – Options of the strategy (e.g. {"reg": 1e-2} for "spline").

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.

Methods

classmethod from_config(config)[source]#

Create a model instance from a configuration dict.

This is the inverse of get_config(). Weights are not loaded – use from_pretrained() for that.

Parameters:

config (dict) – Configuration dict as returned by get_config().

Returns:

A new model instance.

Return type:

EEGModuleMixin

Examples

>>> import json
>>> from braindecode.models import EEGNet
>>> model = EEGNet(n_chans=22, n_times=1000, n_outputs=4, F1=16)
>>> config = model.get_config()
>>> # Reconstruct (without weights)
>>> model2 = EEGNet.from_config(config)
>>> model2.F1
16
>>> # Or from a JSON file
>>> with open("config.json") as f:
...     config = json.load(f)
>>> model3 = EEGNet.from_config(config)

Added in version 1.4.

classmethod from_pretrained(*args, **kwargs)[source]#

Download a model from the Huggingface Hub and instantiate it.

Parameters:
  • pretrained_model_name_or_path (str, Path) –

    • Either the model_id (string) of a model hosted on the Hub, e.g. bigscience/bloom.

    • Or a path to a directory containing model weights saved using

      [~transformers.PreTrainedModel.save_pretrained], e.g., ../path/to/my_model_directory/.

  • revision (str, optional) – Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the latest commit on main branch.

  • force_download (bool, optional, defaults to False) – Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding the existing cache.

  • token (str or bool, optional) – The token to use as HTTP bearer authorization for remote files. By default, it will use the token cached when running hf auth login.

  • cache_dir (str, Path, optional) – Path to the folder where cached files are stored.

  • local_files_only (bool, optional, defaults to False) – If True, avoid downloading the file and return the path to the local cached file if it exists.

  • model_kwargs (dict, optional) – Additional kwargs to pass to the model during initialization.

  • *args – The description is missing.

  • **kwargs – The description is missing.

get_config()[source]#

Return a JSON-serializable dict of all __init__ parameters.

The returned dictionary can be saved to a JSON file and later used with from_config() to reconstruct the model (without weights). It is also used internally by push_to_hub() to persist the full model configuration.

Returns:

All __init__ parameters, JSON-serializable. type[nn.Module] parameters (e.g. activation) are encoded as importable dotted-path strings.

Return type:

dict

Examples

>>> import json
>>> from braindecode.models import EEGNet
>>> model = EEGNet(n_chans=22, n_times=1000, n_outputs=4, F1=16)
>>> config = model.get_config()
>>> config["F1"]
16
>>> # Save to disk
>>> with open("config.json", "w") as f:
...     json.dump(config, f)

Added in version 1.4.

get_output_shape()[source]#

Returns shape of neural network output for batch size equal 1.

Returns:

output_shape – shape of the network output for batch_size==1 (1, …)

Return type:

tuple[int, ...]

get_torchinfo_statistics(col_names=('input_size', 'output_size', 'num_params', 'kernel_size'), row_settings=('var_names', 'depth'))[source]#

Generate table describing the model using torchinfo.summary.

Parameters:
  • col_names (Optional[Iterable[str]]) – Specify which columns to show in the output, see torchinfo for details, by default (“input_size”, “output_size”, “num_params”, “kernel_size”)

  • row_settings (Optional[Iterable[str]]) – Specify which features to show in a row, see torchinfo for details, by default (“var_names”, “depth”)

Returns:

ModelStatistics generated by torchinfo.summary.

Return type:

ModelStatistics

load_state_dict(state_dict, *args, **kwargs)[source]#
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. 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.

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.

to_dense_prediction_model(axis=(2, 3))[source]#

Transform a sequential model with strides to a model that outputs.

dense predictions by removing the strides and instead inserting dilations. Modifies model in-place.

Parameters:

axis (tuple[int, ...] | int) – Axis to transform (in terms of intermediate output axes) can either be 2, 3, or (2,3).

Return type:

None

Notes

Does not yet work correctly for average pooling. Prior to version 0.1.7, there had been a bug that could move strides backwards one layer.

Examples using braindecode.models.EEGModuleMixin#

Simple training on MNE epochs

Simple training on MNE epochs

Cleaning EEG Data with EEGPrep for Trialwise Decoding

Cleaning EEG Data with EEGPrep for Trialwise Decoding

Cropped Decoding on BCIC IV 2a Dataset

Cropped Decoding on BCIC IV 2a Dataset

Basic Brain Decoding on EEG Data

Basic Brain Decoding on EEG Data

Running a Pretrained Model on Any Channel Set with the Channel Layer

Running a Pretrained Model on Any Channel Set with the Channel Layer

How to train, test and tune your model?

How to train, test and tune your model?

Hyperparameter tuning with scikit-learn

Hyperparameter tuning with scikit-learn

Loading and Adapting Pretrained Foundation Models

Loading and Adapting Pretrained Foundation Models

Convolutional neural network regression model on fake data.

Convolutional neural network regression model on fake data.

Training a Braindecode model in PyTorch

Training a Braindecode model in PyTorch

Data Augmentation on BCIC IV 2a Dataset

Data Augmentation on BCIC IV 2a Dataset

Searching the best data augmentation on BCIC IV 2a Dataset

Searching the best data augmentation on BCIC IV 2a Dataset

Interpretability of EEG Decoders

Interpretability of EEG Decoders

Cross-session motor imagery with deep learning EEGNet v4 model

Cross-session motor imagery with deep learning EEGNet v4 model

Self-supervised learning on EEG with relative positioning

Self-supervised learning on EEG with relative positioning

Sparse autoencoders on the activations of a motor-imagery decoder

Sparse autoencoders on the activations of a motor-imagery decoder

Transfer learning across EEG pathology datasets

Transfer learning across EEG pathology datasets

From window labels to events: asynchronous EEG decoding with DANCE

From window labels to events: asynchronous EEG decoding with DANCE

Sleep staging on the Sleep Physionet dataset using Chambon2018 network

Sleep staging on the Sleep Physionet dataset using Chambon2018 network

Sleep staging on the Sleep Physionet dataset using Eldele2021

Sleep staging on the Sleep Physionet dataset using Eldele2021

Sleep staging on the Sleep Physionet dataset using U-Sleep network

Sleep staging on the Sleep Physionet dataset using U-Sleep network