Package: torcheeg
Documentation|TorchEEG
ExamplesTorchEEG is a library built on PyTorch for EEG signal analysis. TorchEEG
aims to provide a plug-and-play EEG analysis tool, so that researchers
can quickly reproduce EEG analysis work and start new EEG analysis
research without paying attention to technical details unrelated to the
research focus.TorchEEG specifies a unified data input-output format (IO) and implement
commonly used EEG databases, allowing users to quickly access benchmark
datasets and define new custom datasets. The datasets that have been
defined so far include emotion recognition and so on. According to
papers published in the field of EEG analysis, TorchEEG provides data
preprocessing methods commonly used for EEG signals, and provides
plug-and-play API for both offline and online pre-proocessing. Offline
processing allow users to process once and use any times, speeding up
the training process. Online processing allows users to save time when
creating new data processing methods. TorchEEG also provides deep
learning models following published papers for EEG analysis, including
convolutional neural networks, graph convolutional neural networks, and
Transformers.InstallationTorchEEG depends on PyTorch, please complete the installation of PyTorch
according to the system, CUDA version and other information:# Conda
# please refer to https://pytorch.org/get-started/locally/
# e.g. CPU versioncondainstallpytorch==1.11.0torchvisiontorchaudiocpuonly-cpytorch# e.g. GPU versioncondainstallpytorch==1.11.0torchvisiontorchaudiocudatoolkit=11.3-cpytorch# Pip
# please refer to https://pytorch.org/get-started/previous-versions/
# e.g. CPU versionpipinstalltorch==1.11.0+cputorchvision==0.12.0+cputorchaudio==0.11.0--extra-index-urlhttps://download.pytorch.org/whl/cpu# e.g. GPU versionpipinstalltorch==1.11.0+cu113torchvision==0.12.0+cu113torchaudio==0.11.0--extra-index-urlhttps://download.pytorch.org/whl/cu113AnacondaTorchEEG supports installing with conda! You can
simply install TorchEEG using Anaconda, just run the following command:condainstall-ctczhangzhi-cconda-forgetorcheegPipTorchEEG allows pip-based installation, please use the following
command:pipinstalltorcheegNightlyIn case you want to experiment with the latest TorchEEG features which
are not fully released yet, please run the following command to install
from the main branch on github:pipinstallgit+https://github.com/tczhangzhi/torcheeg.gitPluginTorchEEG provides plugins related to graph algorithms for converting EEG
in datasets into graph structures and analyzing them using graph neural
networks. This part of the implementation relies on PyG.If you do not use graph-related algorithms, you can skip this part of
the installation.# Conda
# please refer to https://pytorch-geometric.readthedocs.io/en/latest/notes/installation.htmlcondainstallpyg-cpyg# Pip
# please refer to https://pytorch-geometric.readthedocs.io/en/latest/notes/installation.html
# e.g. CPU versionpipinstalltorch-scattertorch-sparsetorch-clustertorch-spline-convtorch-geometric-fhttps://data.pyg.org/whl/torch-1.11.0+cpu.html# e.g. GPU versionpipinstalltorch-scattertorch-sparsetorch-clustertorch-spline-convtorch-geometric-fhttps://data.pyg.org/whl/torch-1.11.0+cu113.htmlMore About TorchEEGAt a granular level, PyTorch is a library that consists of the following
components:ComponentDescriptiontorcheeg.ioA set of unified input and
output API is used to store
the processing results of
various EEG databases for
more efficient and
convenient use.torcheeg.da
tasetsThe packaged benchmark
dataset implementation
provides a multi-process
preprocessing interface.torcheeg.transf
ormsExtensive EEG preprocessing
methods help users extract
features, construct EEG
signal representations, and
connect to commonly used
deep learning libraries.torcheeg.model_selectionExtensive dataset
partitioning methods for
users to experiment with
different settings.torchee
g.modelsExtensive baseline method
reproduction.Implemented ModulesWe list currently supported datasets, transforms, data splitting, and
deep learning models by category.Datasets:All datasets rely on a set of efficient IO APIs,torcheeg.io,
to store data preprocessing results on disk and read them quickly during
training. Data preprocessing and storage support multiprocessing (speed
up!).AMIGOS
datasetfrom Miranda-Correa et al.:AMIGOS: A dataset for affect,
personality and mood research on individuals and
groups.DREAMER
datasetfrom Katsigiannis et al.:DREAMER: A database for emotion
recognition through EEG and ECG signals from wireless low-cost
off-the-shelf
devices.SEED
datasetfrom Zheng et al.:Investigating critical frequency bands and
channels for EEG-based emotion recognition with deep neural
networks.DEAP
datasetfrom Koelstra et al.:DEAP: A database for emotion analysis; using
physiological
signals.MAHNOB
datasetfrom Soleymani et al.:A multimodal database for affect recognition
and implicit
tagging.Transforms:TorchEEG provides extensive data transformation tools to
help users build EEG data representations suitable for a variety of task
formulation and a variety of model structures.Feature Engineering:BandDifferentialEntropy,BandPowerSpectralDensity,BandMeanAbsoluteDeviation,BandKurtosis,BandSkewness,ConcatenateGeneral Operation:PickElectrode,MeanStdNormalize,MinMaxNormalizeFor CNN:To2d,ToGrid,ToInterpolatedGridFor GNN:ToGFor Augmentation:Resize,RandomNoise,RandomMaskFor Label Construction:Select,Binary,BinariesToCategoryData Splitting:In current research in the field of EEG analysis,
there are various settings based on different considerations for data
partitioning. Please choose a reasonable data division method according
to the research focus:Subject Dependent:KFoldPerSubjectGroupbyTrial,train_test_split_per_subject_groupby_trialSubject Independent:LeaveOneSubjectOutConventional:KFold,train_test_split,KFoldGroupbyTrial,train_test_split_groupby_trialModels:Coming soon after pushing to align with the official
implementation or description. If the current version ofCNNs,GNNsandTransformersis to be used, please refer to the implementation intorcheeg.models.QuickstartIn this quick tour, we highlight the ease of starting an EEG analysis
research with only a few lines.Thetorcheeg.datasetsmodule contains dataset classes for many
real-world EEG datasets. In this tutorial, we use theDEAPdataset.
We first go to the official website to apply for data download
permission according to the introduction ofDEAP
dataset, and
download the dataset. Next, we need to specify the download location of
the dataset in theroot_pathparameter. For the DEAP dataset, we
specify the path to thedata_preprocessed_pythonfolder,
e.g../tmp_in/data_preprocessed_python.fromtorcheeg.datasetsimportDEAPDatasetfromtorcheegimporttransformsfromtorcheeg.datasets.constants.emotion_recognition.deapimport\DEAP_CHANNEL_LOCATION_DICTdataset=DEAPDataset(io_path=f'./tmp_out/examples_pipeline/deap',root_path='./tmp_in/data_preprocessed_python',offline_transform=transforms.Compose([transforms.BandDifferentialEntropy(apply_to_baseline=True),transforms.ToGrid(DEAP_CHANNEL_LOCATION_DICT,apply_to_baseline=True)]),online_transform=transforms.Compose([transforms.BaselineRemoval(),transforms.ToTensor()]),label_transform=transforms.Compose([transforms.Select('valence'),transforms.Binary(5.0),]),num_worker=8)TheDEAPDatasetAPI further contains three parameters:online_transform,offline_transform, andlabel_transform,
which are used to modify samples and labels, respectively.Here,offline_transformwill only be called once when the dataset is
initialized to preprocess all samples in the dataset, and the processed
dataset will be stored inio_pathto avoid time-consuming repeated
transformations in subsequent use. If offline preprocessing is a
computationally intensive operation, we also recommend setting multi-CPU
parallelism for offline_transform, e.g., setnum_workerto 4.online_transformis used to transform samples on the fly. Please useonline_transformif you don’t want to wait for the preprocessing of
the entire dataset (suitable for scenarios where newtransformalgorithms are designed) or expect data transformation with randomness
each time a sample is indexed.Next, we need to divide the dataset into a training set and a test set.
In the field of EEG analysis, commonly used data partitioning methods
include k-fold cross-validation and leave-one-out cross-validation. In
this tutorial, we use k-fold cross-validation on the entire dataset
(KFold) as an example of dataset splitting.fromtorcheeg.model_selectionimportKFoldGroupbyTrialk_fold=KFoldGroupbyTrial(n_splits=10,split_path='./tmp_out/examples_pipeline/split',shuffle=True,random_state=42)We loop through each cross-validation set, and for each one, we
initialize the CCNN model and define its hyperparameters. For instance,
each EEG sample contains 4-channel features from 4 sub-bands, and the
grid size is 9x9. We then train the model for 50 epochs using theClassifierTrainer.fromtorch.utils.dataimportDataLoaderfromtorcheeg.modelsimportCCNNfromtorcheeg.trainersimportClassifierTrainerimportpytorch_lightningasplfori,(train_dataset,val_dataset)inenumerate(k_fold.split(dataset)):train_loader=DataLoader(train_dataset,batch_size=64,shuffle=True)val_loader=DataLoader(val_dataset,batch_size=64,shuffle=False)model=CCNN(num_classes=2,in_channels=4,grid_size=(9,9))trainer=ClassifierTrainer(model=model,num_classes=2,lr=1e-4,weight_decay=1e-4,accelerator="gpu")trainer.fit(train_loader,val_loader,max_epochs=50,default_root_dir=f'./tmp_out/examples_pipeline/model/{i}',callbacks=[pl.callbacks.ModelCheckpoint(save_last=True)],enable_progress_bar=True,enable_model_summary=True,limit_val_batches=0.0)score=trainer.test(val_loader,enable_progress_bar=True,enable_model_summary=True)[0]print(f'Fold{i}test accuracy:{score["test_accuracy"]:.4f}')For more specific usage of each module, please refer tothe
documentation.Releases and ContributingTorchEEG is currently in beta; Please let us know if you encounter a bug
by filing an issue. We also appreciate all contributions.If you would like to contribute new datasets, deep learning methods, and
extensions to the core, please first open an issue and then send a PR.
If you are planning to contribute back bug fixes, please do so without
any further discussion.LicenseTorchEEG has a MIT license, as found in theLICENSEfile.