braindecode.models.TCCNet#

class braindecode.models.TCCNet(n_outputs=None, n_chans=None, chs_info=None, n_times=None, input_window_seconds=None, sfreq=None, *, filters=((32, 32), (32, 32), (64, 64), (128, )), kernel_size=3, dilation_growth=2, drop_prob=0.05, activation=<class 'torch.nn.modules.activation.ReLU'>, classification_head='att', mask_value=-10.0, eps=1e-07)[source]#

TCCNet from Tsinganos et al. (2019) [tccnet2019].

Convolution Recurrent Attention/Transformer

Added in version 2.1.

TCCNet architecture

“Proposed model” panel of the authors’ ICASSP 2019 poster (MIT, from [tccnetcode]): dilated causal convolutions, read out by an average over time (AoT) or an attention (Att) head. Braindecode returns the logits, without the softmax.#

A temporal convolutional network that classifies a whole sEMG gesture. The reference trains one model per subject of NinaPro DB1 (27 subjects, 10 sEMG channels at 100 Hz, 53 classes including rest).

Architecture Overview

Residual blocks of causal convolutions map the gesture to a sequence of features, and a pooling over time reduces it to one vector for a linear classifier. Inputs may have any length:

(batch, n_chans, n_times) -> residual blocks
-> (batch, filters[-1][-1], n_times) -> pooling over the valid steps
-> (batch, filters[-1][-1]) -> final_layer -> (batch, n_outputs)

The defaults build the best model of the paper: the attention head and a receptive field of 255 samples (2550 ms at 100 Hz). Pass classification_head="aot" and/or filters=((32, 64), (64, 128)) (31 samples, 310 ms) for its other three models. With 10 channels and 53 classes the four models have 60,117 (AoT, 310 ms), 72,245 (AoT, 2550 ms), 76,629 (Att, 310 ms) and 88,757 (Att, 2550 ms) parameters; the authors’ poster lists them as 60K, 70K, 75K and 85K, and names the receptive fields 300 and 2500 ms.

Macro Components

TCCNet.feature_extractor

Operations. One residual block per inner sequence of filters: its causal convolutions, each followed by the activation and a channel-wise dropout, plus a kernel-size-1 projection of the block input that is added to the last convolution. The dilation grows by the factor dilation_growth at every convolution, across blocks too; it doubles by default, so n convolutions of kernel size k see \(1 + (k - 1)(2^n - 1)\) samples. Role. One feature vector per time step, computed from the past only.

TCCNet.attention

Operations. With classification_head="att": a score tanh(h W) u for each time step h, a softmax of the scores over the valid steps, and the sum of the steps weighted by it. It is None with "aot", which averages the valid steps instead. Role. Pools the sequence into one vector per gesture.

TCCNet.final_layer

Operations. One Linear on the pooled vector. Role. The logits, without the softmax of the reference.

Temporal, Spatial, and Spectral Encoding

  • Temporal: causal convolutions with dilations 1, 2, 4, … by default: each step sees only the past, and the receptive field grows exponentially.

  • Spatial: every convolution mixes all its input channels; there is no per-channel branch.

  • Spectral: not modelled. The reference rectifies each channel and low-pass filters it, so the network reads an amplitude envelope.

Additional Mechanisms

  • Masking. A time step where every channel equals mask_value is padding: every convolution reads it as zero and the pooling leaves it out, as the reference’s Keras Masking layer does. As in its CausalConv1D, a convolution adds its bias only where its output is non-zero.

  • Attention. The softmax over the scores s is the reference’s exp(s) / (sum(exp(s)) + eps), computed as exp(s - m) / (sum(exp(s - m)) + eps * exp(-m)) with m the row maximum, at least 0 so that a fully padded gesture stays finite. The values are the same, without the reference’s overflow to NaN once the context vector grows large.

  • Reference parity. The reference sums every time step, padded ones included, and divides by the number of valid steps; this port leaves padded steps out. The two agree for pre-padding with an activation that maps 0 to 0, such as the reference’s ReLU. The bias rule changes the result only where a convolution gives exactly zero at a valid step. Initialisation follows Keras 2.2.4: truncated Glorot normal kernels, zero biases, Glorot uniform attention weights.

Important

The reference code [tccnetcode] rectifies each channel, low-passes it at 1 Hz (first-order Butterworth, filtfilt) and pre-pads the gestures of a batch with -10. The masked average over time equals its average for that padding only; a fully padded gesture gives NaN with "aot", as there. The min-max normalisation of the reference’s generator is off in its released configurations.

License

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 to mne.Info for 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.

  • filters (Sequence[Sequence[int]]) – Output filters of each causal convolution, one inner sequence per residual block. It sets the number of blocks and of convolutions per block.

  • kernel_size (int) – Temporal kernel size of every causal convolution.

  • dilation_growth (int) – Factor by which the dilation grows at every causal convolution, across blocks too: 1, 2, 4, … for 2.

  • drop_prob (float) – Channel-wise dropout after each activated convolution, as Keras SpatialDropout1D.

  • activation (type[Module]) – Activation after each causal convolution.

  • classification_head (str) – "att": context-vector attention; "aot": average over the valid time steps.

  • mask_value (float | None) – Value of every channel at a padded time step. None turns masking off.

  • eps (float) – Epsilon of the attention normalisation (keras.backend.epsilon() in the reference). Not used with classification_head="aot".

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

[tccnet2019]

Tsinganos, P., Cornelis, B., Cornelis, J., Jansen, B., & Skodras, A. (2019). Improved Gesture Recognition Based on sEMG Signals and TCN. ICASSP 2019, 1169-1173. https://doi.org/10.1109/ICASSP.2019.8683239

[tccnetcode] (1,2)

Tsinganos, P. et al. ICASSP2019_TCN source code. DSIP-UPatras/ICASSP2019_TCN

Hugging Face Hub integration

When the optional huggingface_hub package 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 TCCNet

# Train your model
model = TCCNet(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-tccnet-model",
    commit_message="Initial model upload",
    model_card_kwargs={"datasets": ["BNCI2014_001"]},
)

Loading a model from the Hub:

from braindecode.models import TCCNet

# Load pretrained model
model = TCCNet.from_pretrained("username/my-tccnet-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 = TCCNet.from_pretrained("username/my-tccnet-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.script returns features only on models whose forward declares return_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 = TCCNet.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)[source]#

Return logits for a batch of sEMG gestures.

Parameters:

x (Tensor) – sEMG of shape (batch, n_chans, n_times), of any length. Padded steps hold mask_value in every channel.

Returns:

Logits of shape (batch, n_outputs).

Return type:

Tensor

reset_head(n_outputs)[source]#

Swap the classifier for a new number of outputs.

Parameters:

n_outputs (int) – New number of output classes.

Return type:

None

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.