EEG Classification with EEGSPDNet#

This tutorial demonstrates how to use EEGSPDNet for motor imagery EEG classification. EEGSPDNet combines channel-specific convolution with SPD matrix learning for robust EEG decoding.

Introduction#

EEGSPDNet [Wilson et al., 2025] is a deep Riemannian network designed specifically for EEG decoding. It extends the SPDNet architecture with:

  • Channel-specific convolution: Learns temporal filters independently for each EEG channel using grouped convolutions

  • Covariance pooling: Computes SPD covariance matrices from the filtered signals

  • Scalable BiMap layers: Progressively reduces dimensionality on the SPD manifold

  • SPD Dropout: Structured dropout that maintains positive definiteness

Setup and Imports#

import warnings

import matplotlib.pyplot as plt
import torch

from braindecode import EEGClassifier
from moabb.datasets import BNCI2014_001
from moabb.paradigms import MotorImagery
from sklearn.metrics import (
    ConfusionMatrixDisplay,
    accuracy_score,
    balanced_accuracy_score,
    confusion_matrix,
)
from sklearn.preprocessing import LabelEncoder
from skorch.callbacks import EpochScoring, GradientNormClipping
from skorch.dataset import ValidSplit

from spd_learn.models import EEGSPDNet


warnings.filterwarnings("ignore")

Loading the Dataset#

We use the BCI Competition IV Dataset 2a for motor imagery classification.

dataset = BNCI2014_001()
paradigm = MotorImagery(n_classes=4)

print(f"Dataset: {dataset.code}")
print(f"Number of subjects: {len(dataset.subject_list)}")
Choosing from all possible events
Dataset: BNCI2014-001
Number of subjects: 9

Understanding EEGSPDNet Architecture#

EEGSPDNet processes EEG in the following stages:

  1. Channel-specific Conv1d: Each channel gets its own set of filters

    \[X_{conv} = \text{GroupedConv1d}(X), \quad X \in \mathbb{R}^{C \times T}\]

    Output shape: (n_chans * n_filters, time - filter_length + 1)

  2. Covariance Pooling: Compute SPD covariance matrix

    \[\Sigma = \frac{1}{T-1} X_{conv} X_{conv}^T\]
  3. BiMap + ReEig blocks: Learn spatial filters while preserving SPD

    \[Y = W^T \Sigma W, \quad Y = U \max(\Lambda, \epsilon) U^T\]
  4. LogEig: Project to tangent space for classification

Creating the EEGSPDNet Model#

Key parameters:

  • n_filters: Number of temporal filters per channel

  • bimap_sizes: Tuple (k, n_layers) defining scaling factor and depth

  • filter_time_length: Length of temporal convolution kernel

  • spd_drop_prob: Dropout probability for SPD dropout layers

n_chans = 22
n_outputs = 4

# Create EEGSPDNet model
model = EEGSPDNet(
    n_chans=n_chans,
    n_outputs=n_outputs,
    n_filters=4,  # 4 filters per channel → 88 total
    bimap_sizes=(2, 2),  # Scale by 2x, 2 BiMap layers: 88→44→22
    filter_time_length=25,  # 100ms filter at 250Hz
    spd_drop_prob=0.0,  # No SPD dropout (can cause instability)
    spd_drop_scaling=True,  # Scale remaining channels
    final_layer_drop_prob=0.5,  # 50% dropout before classifier
)

print("EEGSPDNet Architecture:")
print(model)

# Show BiMap layer dimensions
print("\nBiMap Layer Dimensions:")
print("Input: 88 x 88 (22 channels x 4 filters)")
print("→ BiMap0: 88 → 44")
print("→ BiMap1: 44 → 22")
print("→ LogEig: 22 x 22 → 253 (upper triangular)")
EEGSPDNet Architecture:
EEGSPDNet(
  (conv): Conv1d(22, 88, kernel_size=(25,), stride=(1,), groups=22)
  (cov_pool): CovLayer()
  (spdnet): Sequential(
    (bimap0): ParametrizedBiMap(
      (parametrizations): ModuleDict(
        (weight): ParametrizationList(
          (0): _Orthogonal()
        )
      )
    )
    (reeig0): ReEig()
    (bimap1): ParametrizedBiMap(
      (parametrizations): ModuleDict(
        (weight): ParametrizationList(
          (0): _Orthogonal()
        )
      )
    )
    (reeig1): ReEig()
    (logeig): LogEig()
  )
  (dropout): Dropout(p=0.5, inplace=False)
  (linear): Linear(in_features=253, out_features=4, bias=True)
)

BiMap Layer Dimensions:
Input: 88 x 88 (22 channels x 4 filters)
→ BiMap0: 88 → 44
→ BiMap1: 44 → 22
→ LogEig: 22 x 22 → 253 (upper triangular)

Setting up the Classifier#

batch_size = 32
max_epochs = 100
learning_rate = 1e-4  # Low learning rate for stable SPD learning

device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"\nUsing device: {device}")

# Note: SPD networks benefit from gradient clipping to prevent
# divergence during training on the Riemannian manifold.
clf = EEGClassifier(
    model,
    criterion=torch.nn.CrossEntropyLoss,
    optimizer=torch.optim.Adam,
    optimizer__lr=learning_rate,
    train_split=ValidSplit(0.1, stratified=True, random_state=42),
    batch_size=batch_size,
    max_epochs=max_epochs,
    callbacks=[
        (
            "train_acc",
            EpochScoring(
                "accuracy", lower_is_better=False, on_train=True, name="train_acc"
            ),
        ),
        ("gradient_clip", GradientNormClipping(gradient_clip_value=1.0)),
    ],
    device=device,
    verbose=1,
)
Using device: cpu

Training and Evaluation#

subject_id = 1

# Cache configuration
cache_config = dict(
    save_raw=True,
    save_epochs=True,
    save_array=True,
    use=True,
    overwrite_raw=False,
    overwrite_epochs=False,
    overwrite_array=False,
)

# Load data
X, labels, meta = paradigm.get_data(
    dataset=dataset, subjects=[subject_id], cache_config=cache_config
)

# Encode labels
le = LabelEncoder()
y = le.fit_transform(labels)

print(f"\nData shape: {X.shape}")
print(f"Classes: {le.classes_}")

# Split by session
train_idx = meta.query("session == '0train'").index.to_numpy()
test_idx = meta.query("session == '1test'").index.to_numpy()

print(f"Training samples: {len(train_idx)}")
print(f"Test samples: {len(test_idx)}")

# Train
clf.fit(X[train_idx], y[train_idx])

# Evaluate
y_pred_train = clf.predict(X[train_idx])
y_pred_test = clf.predict(X[test_idx])

train_acc = accuracy_score(y[train_idx], y_pred_train)
test_acc = accuracy_score(y[test_idx], y_pred_test)
test_bal_acc = balanced_accuracy_score(y[test_idx], y_pred_test)

print(f"\n{'=' * 50}")
print(f"Results for Subject {subject_id}")
print(f"{'=' * 50}")
print(f"Train Accuracy:    {train_acc * 100:.2f}%")
print(f"Test Accuracy:     {test_acc * 100:.2f}%")
print(f"Test Balanced Acc: {test_bal_acc * 100:.2f}%")
Data shape: (528, 22, 1001)
Classes: ['feet' 'left_hand' 'right_hand' 'tongue']
Training samples: 240
Test samples: 288
  epoch    train_acc    train_loss    valid_acc    valid_loss     dur
-------  -----------  ------------  -----------  ------------  ------
      1       0.2240        1.4735       0.2500        1.3942  0.8021
      2       0.2240        1.4229       0.2500        1.3760  0.8747
      3       0.2031        1.4380       0.3333        1.3644  0.8585
      4       0.3698        1.3631       0.3333        1.3577  0.7499
      5       0.2812        1.3855       0.2917        1.3528  0.7390
      6       0.2969        1.3998       0.2917        1.3477  0.7428
      7       0.2865        1.3710       0.3333        1.3429  0.5746
      8       0.2917        1.4110       0.3750        1.3382  0.5465
      9       0.2812        1.3838       0.4583        1.3339  0.5414
     10       0.3073        1.3870       0.4583        1.3293  0.5383
     11       0.3125        1.3629       0.4167        1.3246  0.5497
     12       0.2708        1.3733       0.3750        1.3200  0.5472
     13       0.3125        1.3424       0.3750        1.3161  0.5511
     14       0.3021        1.3698       0.4167        1.3122  0.5377
     15       0.3490        1.3412       0.4167        1.3084  0.5350
     16       0.3281        1.3453       0.5000        1.3043  0.5459
     17       0.3333        1.3368       0.4583        1.3007  0.5381
     18       0.2969        1.3452       0.5000        1.2970  0.5418
     19       0.3490        1.3194       0.4583        1.2934  0.5723
     20       0.3906        1.3003       0.5000        1.2896  0.5492
     21       0.3750        1.3276       0.5417        1.2855  0.5753
     22       0.3594        1.3174       0.5417        1.2817  0.5380
     23       0.3542        1.3213       0.5000        1.2781  0.5445
     24       0.3490        1.3064       0.5000        1.2744  0.5669
     25       0.3073        1.3370       0.5417        1.2710  0.5535
     26       0.3542        1.3057       0.5000        1.2680  0.5429
     27       0.3854        1.2944       0.5000        1.2649  0.5533
     28       0.4167        1.2562       0.5000        1.2605  0.5404
     29       0.4375        1.2866       0.5833        1.2562  0.5408
     30       0.4531        1.2646       0.6250        1.2525  0.5540
     31       0.4323        1.2539       0.6250        1.2491  0.5562
     32       0.4323        1.2411       0.6250        1.2458  0.5481
     33       0.4271        1.2840       0.6250        1.2423  0.5355
     34       0.3750        1.2817       0.6250        1.2391  0.5490
     35       0.4323        1.2561       0.6250        1.2358  0.5894
     36       0.4219        1.2429       0.5833        1.2325  0.5545
     37       0.3750        1.2474       0.6250        1.2288  0.5496
     38       0.3646        1.2707       0.6667        1.2254  0.5489
     39       0.4792        1.2429       0.6250        1.2219  0.5496
     40       0.4010        1.2402       0.6667        1.2183  0.5580
     41       0.4062        1.2395       0.6250        1.2150  0.5490
     42       0.4010        1.2533       0.5833        1.2115  0.5475
     43       0.5052        1.2319       0.5833        1.2082  0.5741
     44       0.4115        1.2426       0.5833        1.2052  0.5616
     45       0.5000        1.2033       0.5833        1.2023  0.5502
     46       0.5208        1.1849       0.6250        1.1992  0.5463
     47       0.4375        1.2159       0.6250        1.1960  0.5638
     48       0.4896        1.1979       0.6250        1.1930  0.5491
     49       0.4635        1.2078       0.6250        1.1901  0.5572
     50       0.5052        1.1724       0.6250        1.1869  0.5668
     51       0.4792        1.1685       0.6250        1.1836  0.6221
     52       0.4688        1.2009       0.5833        1.1800  0.7574
     53       0.4688        1.1978       0.5833        1.1770  0.8096
     54       0.4688        1.1840       0.6250        1.1742  0.7891
     55       0.4688        1.1922       0.6250        1.1718  0.7868
     56       0.5052        1.1765       0.6250        1.1685  0.7879
     57       0.4635        1.1724       0.6667        1.1651  0.7948
     58       0.4688        1.1805       0.6667        1.1623  0.6528
     59       0.5260        1.1782       0.6250        1.1595  0.5272
     60       0.4531        1.1763       0.6250        1.1561  0.7537
     61       0.4844        1.1601       0.6667        1.1530  0.7597
     62       0.5365        1.1532       0.6250        1.1505  0.7496
     63       0.4323        1.1639       0.6667        1.1474  0.7526
     64       0.5052        1.1304       0.6250        1.1442  0.5490
     65       0.5573        1.1439       0.6250        1.1413  0.6320
     66       0.5208        1.1487       0.6667        1.1383  0.7646
     67       0.5104        1.1533       0.6667        1.1353  0.7576
     68       0.4948        1.1579       0.6667        1.1321  0.7517
     69       0.4948        1.1443       0.6250        1.1290  0.7535
     70       0.5312        1.1147       0.6667        1.1255  0.7565
     71       0.5365        1.1199       0.6250        1.1224  0.7592
     72       0.5521        1.1012       0.6250        1.1190  0.7582
     73       0.5417        1.1283       0.6667        1.1156  0.7486
     74       0.4948        1.1081       0.6667        1.1123  0.7535
     75       0.4948        1.1360       0.6250        1.1089  0.7477
     76       0.5312        1.1388       0.6250        1.1062  0.7439
     77       0.5573        1.1179       0.6667        1.1038  0.7603
     78       0.5469        1.1104       0.7083        1.1012  0.7519
     79       0.6302        1.0710       0.7083        1.0983  0.7480
     80       0.5573        1.0864       0.7083        1.0956  0.7509
     81       0.5677        1.0913       0.6250        1.0928  0.7518
     82       0.5156        1.1221       0.6250        1.0900  0.7545
     83       0.5938        1.0885       0.7083        1.0871  0.7478
     84       0.5729        1.0666       0.7083        1.0844  0.7479
     85       0.5052        1.0985       0.7083        1.0815  0.7502
     86       0.5677        1.0787       0.7083        1.0790  0.7602
     87       0.5208        1.0845       0.6667        1.0768  0.7618
     88       0.5677        1.0800       0.7500        1.0741  0.7542
     89       0.5365        1.1054       0.7083        1.0715  0.7508
     90       0.5312        1.0759       0.6667        1.0689  0.7540
     91       0.5677        1.0765       0.7083        1.0666  0.7441
     92       0.5990        1.0852       0.7083        1.0639  0.7487
     93       0.5625        1.0547       0.7083        1.0614  0.7536
     94       0.5625        1.0577       0.7083        1.0588  0.7521
     95       0.6094        1.0530       0.7083        1.0557  0.7508
     96       0.5833        1.0631       0.6667        1.0523  0.7516
     97       0.6615        1.0289       0.7083        1.0495  0.7509
     98       0.6042        1.0540       0.7083        1.0473  0.7498
     99       0.5885        1.0573       0.7083        1.0446  0.7500
    100       0.5781        1.0489       0.7083        1.0422  0.7485

==================================================
Results for Subject 1
==================================================
Train Accuracy:    74.58%
Test Accuracy:     67.01%
Test Balanced Acc: 67.01%

Visualizing Results#

fig, axes = plt.subplots(1, 3, figsize=(15, 4))

history = clf.history
epochs = range(1, len(history) + 1)

# Loss
ax1 = axes[0]
ax1.plot(epochs, history[:, "train_loss"], "b-", label="Train Loss", linewidth=2)
ax1.plot(epochs, history[:, "valid_loss"], "r--", label="Valid Loss", linewidth=2)
ax1.set_xlabel("Epoch", fontsize=12)
ax1.set_ylabel("Loss", fontsize=12)
ax1.set_title("Training and Validation Loss", fontsize=14)
ax1.legend(fontsize=10)
ax1.grid(True, alpha=0.3)

# Accuracy
ax2 = axes[1]
ax2.plot(epochs, history[:, "train_acc"], "b-", label="Train Acc", linewidth=2)
ax2.plot(epochs, history[:, "valid_acc"], "r--", label="Valid Acc", linewidth=2)
ax2.set_xlabel("Epoch", fontsize=12)
ax2.set_ylabel("Accuracy", fontsize=12)
ax2.set_title("Training and Validation Accuracy", fontsize=14)
ax2.legend(fontsize=10)
ax2.grid(True, alpha=0.3)
ax2.set_ylim([0, 1])

# Confusion Matrix
ax3 = axes[2]
cm = confusion_matrix(y[test_idx], y_pred_test)
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=le.classes_)
disp.plot(ax=ax3, cmap="Blues", values_format="d")
ax3.set_title(f"Test Confusion Matrix\nAccuracy: {test_acc * 100:.1f}%", fontsize=14)

plt.tight_layout()
plt.show()
Training and Validation Loss, Training and Validation Accuracy, Test Confusion Matrix Accuracy: 67.0%

Comparing with Different Configurations#

Let’s compare different EEGSPDNet configurations to understand the impact of hyperparameters.

configs = {
    "Small (k=2, depth=1)": {"bimap_sizes": (2, 1), "n_filters": 4},
    "Medium (k=2, depth=2)": {"bimap_sizes": (2, 2), "n_filters": 4},
    "Large (k=2, depth=3)": {"bimap_sizes": (2, 3), "n_filters": 6},
}

print("\nModel Size Comparison:")
print("-" * 60)
for name, config in configs.items():
    temp_model = EEGSPDNet(n_chans=n_chans, n_outputs=n_outputs, **config)
    n_params = sum(p.numel() for p in temp_model.parameters())
    print(f"{name}: {n_params:,} parameters")
Model Size Comparison:
------------------------------------------------------------
Small (k=2, depth=1): 10,124 parameters
Medium (k=2, depth=2): 8,144 parameters
Large (k=2, depth=3): 15,398 parameters

Summary#

In this tutorial, we demonstrated how to:

  1. Create and configure an EEGSPDNet model

  2. Understand the architecture’s channel-specific processing

  3. Train and evaluate on motor imagery data

  4. Compare different model configurations

EEGSPDNet’s channel-specific convolution allows it to learn independent temporal features for each electrode, which is particularly useful for spatially distributed brain signals.

Total running time of the script: (1 minutes 7.735 seconds)