braindecode.models.CareSleepNet#
- class braindecode.models.CareSleepNet(n_outputs=None, n_chans=None, chs_info=None, n_times=None, input_window_seconds=None, sfreq=None, *, n_epochs=20, n_eog_chans=2, n_heads=8, encoder_widths=(64, 128, 256, 512), encoder_kernel_sizes=(49, 9, 9, 9), encoder_strides=(12, 1, 1, 1), encoder_pool_kernel_sizes=(9, 2, 2, 2), encoder_pool_strides=(2, 2, 2, 2), msd_dilations=(1, 2, 4), transformer_n_heads=8, transformer_mlp_ratio=4.0, drop_prob=0.1, activation=<class 'torch.nn.modules.activation.GELU'>, norm_eps=1e-06, transformer_norm_eps=1e-12, init_std=0.02, bias_init_std=1e-06)[source]#
CareSleepNet from Wang et al. (2024) [caresleepnet2024].
Convolution Attention/Transformer
Added in version 2.1.
Architecture Overview
A sequence-to-sequence sleep stager: it reads
n_epochsconsecutive sleep epochs of EEG and EOG and returns one prediction per epoch:(batch, n_chans, n_times) -> split into n_epochs epochs -> EEG and EOG epoch encoders -> (batch, n_epochs, D) each -> cross-modal blocks, summed -> positional encoding -> sequence encoder -> linear classifier per epoch -> (batch, n_outputs, n_epochs)
with
D = encoder_widths[-1], 512 by default.Macro Components
CareSleepNet.eeg_encoderandCareSleepNet.eog_encoderOperations. One stage per entry of the
encoder_*tuples, four by default. A stage is a multi-scale dilated convolution block (one convolution per entry ofmsd_dilations, 1, 2 and 4 by default, and a 1x1 shortcut, summed and layer-normalized) followed by max pooling; every stage but the first is then followed by a post-norm transformer layer over time. The average over time ends the encoder. Role. OneD-dimensional vector per epoch, from the EEG channels and from the EOG channels.CareSleepNet.eog_to_eegandCareSleepNet.eeg_to_eogOperations. Pre-norm blocks of multi-head attention and an MLP: the queries come from one signal, the keys, values and residual from the other. The two outputs are summed. Role. Cross-modal fusion.
CareSleepNet.positional_encodingandCareSleepNet.sequence_encoderOperations. A learned positional encoding over the epochs and one pre-norm transformer layer. Role. Context across the epochs.
CareSleepNet.sequence_normandCareSleepNet.final_layerOperations. A layer norm and a linear classifier, applied to each epoch. Role. One row of stage logits per epoch.
Temporal, Spatial, and Spectral Encoding
Temporal: dilated convolutions and transformer layers within each epoch, then a transformer over the epochs of the sequence.
Spatial: EEG and EOG channels are encoded apart, each mixed by the first convolution of its encoder, then fused by cross-modal attention.
Spectral: learned by the multi-scale dilated convolutions.
Additional Mechanisms
The input holds the epochs one after the other in time,
n_times = n_epochs * epoch_samples, so each epoch spansn_times // n_epochssamples. The lastn_eog_chanschannels are EOG and the others EEG.The transformer layers of the epoch encoders are BERT layers (post-norm,
eps=transformer_norm_eps, no dropout between the GELU and the second linear layer); the reference’s all-ones attention mask is a no-op and is left out. The initialization follows the reference.
Important
The reference code [caresleepnetcode] takes signals resampled to 100 Hz (ISRUC also band-passed at 0.3-40 Hz), cut into sequences of 20 epochs of 30 s, with 5 classes (W, N1, N2, N3, REM) and, on ISRUC, 6 EEG and 2 EOG channels. No trained weights were released.
- Parameters:
n_outputs (int) – Number of outputs of the model. This is the number of classes in the case of classification.
n_chans (int) – Number of EEG channels.
chs_info (list of dict) – Information about each individual EEG channel. This should be filled with
info["chs"]. Refer tomne.Infofor more details.n_times (int) – Number of time samples of the input window.
input_window_seconds (float) – Length of the input window in seconds.
sfreq (float) – Sampling frequency of the EEG recordings.
n_epochs (
int) – Number of sleep epochs in one input sequence;n_timesmust be a multiple of it. The reference uses 20 epochs of 30 s at 100 Hz.n_eog_chans (
int) – Number of EOG channels, at the end of the channel axis. The reference uses 6 EEG and 2 EOG channels on ISRUC.n_heads (
int) – Attention heads of the cross-modal and sequence blocks. They must divideencoder_widths[-1].encoder_widths (
Sequence[int]) – Output channels of each stage of the epoch encoder. Its length sets the number of stages, and the four tuples below have one entry per stage. The last entry is also the width of the epoch vectors, of the cross-modal and sequence blocks and of the classifier input (512 in the reference).encoder_kernel_sizes (
Sequence[int]) – Kernel size of the multi-scale convolutions of each stage. It must be odd, so that the padding(kernel_size - 1) // 2times the dilation keeps every branch the length of the strided shortcut.encoder_strides (
Sequence[int]) – Stride of the multi-scale convolutions of each stage.encoder_pool_kernel_sizes (
Sequence[int]) – Kernel size of the max pooling after each stage, with padding(kernel_size - 1) // 2.encoder_pool_strides (
Sequence[int]) – Stride of the max pooling after each stage.msd_dilations (
Sequence[int]) – Dilation of each convolution branch of a multi-scale block, the same in every stage.transformer_n_heads (
int) – Attention heads of the epoch encoder’s transformer layers. The reference sets them in a BERT config of their own, apart from then_headsof the other blocks. They must divide every entry ofencoder_widths[1:].transformer_mlp_ratio (
float) – Width of the feed-forward layer of the epoch encoder’s transformer layers over their width (intermediate_sizein the reference). The cross-modal and sequence blocks have a feed-forward layer as wide as themselves,encoder_widths[-1].drop_prob (
float) – Dropout rate of every dropout layer; every dropout rate of the reference is 0.1.activation (
type[Module]) – Activation of every convolution branch and transformer MLP.norm_eps (
float) – Epsilon of the layer norms outside the epoch encoder’s transformer layers: those of the multi-scale blocks, the cross-modal blocks and the sequence encoder (eps=1e-6in the reference).transformer_norm_eps (
float) – Epsilon of the layer norms of the epoch encoder’s transformer layers (BertLayerNormin the reference).init_std (
float) – Std of the normal initialization of the weights of the epoch encoder’s transformer layers (initializer_rangein the reference) and of the positional encoding.bias_init_std (
float) – Std of the normal initialization of the biases of the MLPs of the cross-modal and sequence blocks.
- 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
[caresleepnet2024]Wang, J., Zhao, S., Jiang, H., Zhou, Y., Yu, Z., Li, T., Li, S., & Pan, G. (2024). CareSleepNet: A Hybrid Deep Learning Network for Automatic Sleep Staging. IEEE Journal of Biomedical and Health Informatics, 28(12), 7392-7405. https://doi.org/10.1109/JBHI.2024.3426939
[caresleepnetcode]Wang, J. CareSleepNet source code. wjq-learning/CareSleepNet
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 CareSleepNet # Train your model model = CareSleepNet(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-caresleepnet-model", commit_message="Initial model upload", model_card_kwargs={"datasets": ["BNCI2014_001"]}, )
Loading a model from the Hub:
from braindecode.models import CareSleepNet # Load pretrained model model = CareSleepNet.from_pretrained("username/my-caresleepnet-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 = CareSleepNet.from_pretrained("username/my-caresleepnet-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 = CareSleepNet.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