{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# CCNN with the DEAP Dataset\nIn this case, we introduce how to use TorchEEG to train a Continuous Convolutional Neural Network (CCNN) on the DEAP dataset for emotion classification.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import logging\nimport os\nimport random\nimport time\n\nimport numpy as np\nimport torch\nfrom torch.utils.data.dataloader import DataLoader\nfrom torcheeg import transforms\nfrom torcheeg.datasets import DEAPDataset\nfrom torcheeg.datasets.constants.emotion_recognition.deap import \\\n    DEAP_CHANNEL_LOCATION_DICT\nfrom torcheeg.model_selection import KFoldGroupbyTrial\nfrom torcheeg.models import CCNN\nfrom torcheeg.trainers import ClassificationTrainer"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Pre-experiment Preparation to Ensure Reproducibility\nUse the logging module to store output in a log file for easy reference while printing it to the screen.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "os.makedirs('./tmp_out/examples_deap_ccnn/log', exist_ok=True)\nlogger = logging.getLogger('CCNN with the DEAP Dataset')\nlogger.setLevel(logging.DEBUG)\nconsole_handler = logging.StreamHandler()\ntimeticks = time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime())\nfile_handler = logging.FileHandler(\n    os.path.join('./tmp_out/examples_deap_ccnn/log', f'{timeticks}.log'))\nlogger.addHandler(console_handler)\nlogger.addHandler(file_handler)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Set the random number seed in all modules to guarantee the same result when running again.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def seed_everything(seed):\n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = False\n\n\nseed_everything(42)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Customize Trainer\nTorchEEG provides a large number of trainers to help complete the training of classification models, generative models and cross-domain methods. Here we choose the simplest classification trainer, inherit the trainer and overload the log function to save the log using our own defined method; other hook functions can also be overloaded to meet special needs.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class MyClassificationTrainer(ClassificationTrainer):\n    def log(self, *args, **kwargs):\n        if self.is_main:\n            logger.info(*args, **kwargs)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Building Deep Learning Pipelines Using TorchEEG\nStep 1: Initialize the Dataset\n\nWe use the DEAP dataset supported by TorchEEG. Here, we set an EEG sample to 1 second long and include 128 data points. The baseline signal is 3 seconds long, cut into three, and averaged as the baseline signal for the trial. In offline preprocessing, we divide the EEG signal of every electrode into 4 sub-bands, and calculate the differential entropy on each sub-band as a feature, followed by debaselining and mapping on the grid. Finally, the preprocessed EEG signals are stored in the local IO. In online processing, all EEG signals are converted into Tensors for input into neural networks.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "dataset = DEAPDataset(io_path=f'./tmp_out/examples_deap_ccnn/deap',\n                      root_path='./tmp_in/data_preprocessed_python',\n                      offline_transform=transforms.Compose([\n                          transforms.BandDifferentialEntropy(\n                              sampling_rate=128, apply_to_baseline=True),\n                          transforms.BaselineRemoval(),\n                          transforms.ToGrid(DEAP_CHANNEL_LOCATION_DICT)\n                      ]),\n                      online_transform=transforms.ToTensor(),\n                      label_transform=transforms.Compose([\n                          transforms.Select('valence'),\n                          transforms.Binary(5.0),\n                      ]),\n                      chunk_size=128,\n                      baseline_chunk_size=128,\n                      num_baseline=3,\n                      num_worker=4)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div class=\"alert alert-danger\"><h4>Warning</h4><p>If you use TorchEEG under the `Windows` system and want to use multiple processes (such as in dataset or dataloader), you should check whether :obj:`__name__` is :obj:`__main__` to avoid errors caused by multiple :obj:`import`.</p></div>\n\nThat is, under the :obj:`Windows` system, you need to:\n```\nif __name__ == \"__main__\":\n    dataset = DEAPDataset(\n         io_path=\n         f'./tmp_out/examples_deap_ccnn/deap',\n         root_path='./tmp_in/data_preprocessed_python',\n         offline_transform=transforms.Compose([\n             transforms.BandDifferentialEntropy(sampling_rate=128,\n                                                apply_to_baseline=True),\n             transforms.BaselineRemoval(),\n             transforms.ToGrid(DEAP_CHANNEL_LOCATION_DICT)\n         ]),\n         online_transform=transforms.ToTensor(),\n         label_transform=transforms.Compose([\n             transforms.Select('valence'),\n             transforms.Binary(5.0),\n         ]),\n         io_mode='pickle',\n         chunk_size=128,\n         baseline_chunk_size=128,\n         num_baseline=3,\n         num_worker=4)\n    # the following codes\n```\n<div class=\"alert alert-info\"><h4>Note</h4><p>LMDB may not be optimized for parts of Windows systems or storage devices. If you find that the data preprocessing speed is slow, you can consider setting :obj:`io_mode` to :obj:`pickle`, which is an alternative implemented by TorchEEG based on pickle.</p></div>\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Step 2: Divide the Training and Test samples in the Dataset\n\nHere, the dataset is divided using 5-fold cross-validation. In the process of division, we group according to the trial index, and every trial takes 4 folds as training samples and 1 fold as test samples. Samples across trials are aggregated to obtain training set and test set.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "k_fold = KFoldGroupbyTrial(n_splits=5,\n                           split_path='./tmp_out/examples_deap_ccnn/split')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Step 3: Define the Model and Start Training\n\nWe first use a loop to get the dataset in each cross-validation. In each cross-validation, we initialize the CCNN model and define the hyperparameters. For example, each EEG sample contains 4-channel features from 4 sub-bands, the grid size is 9 times 9, etc.\n\nWe then initialize the trainer and set the hyperparameters in the trained model, such as the learning rate, the equipment used, etc. The :obj:`fit` method receives the training dataset and starts training the model. The :obj:`test` method receives a test dataset and reports the test results. The :obj:`save_state_dict` method can save the trained model.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "for i, (train_dataset, val_dataset) in enumerate(k_fold.split(dataset)):\n    # Initialize the model\n    model = CCNN(in_channels=4, grid_size=(9, 9), num_classes=2, dropout=0.5)\n\n    # Initialize the trainer and use the 0-th GPU for training, or set device_ids=[] to use CPU\n    trainer = MyClassificationTrainer(model=model,\n                                      lr=1e-4,\n                                      weight_decay=1e-4,\n                                      device_ids=[0])\n\n    # Initialize several batches of training samples and test samples\n    train_loader = DataLoader(train_dataset,\n                              batch_size=256,\n                              shuffle=True,\n                              num_workers=4)\n    val_loader = DataLoader(val_dataset,\n                            batch_size=256,\n                            shuffle=False,\n                            num_workers=4)\n\n    # Do 50 rounds of training\n    trainer.fit(train_loader, val_loader, num_epochs=50)\n    trainer.test(val_loader)\n    trainer.save_state_dict(f'./tmp_out/examples_deap_ccnn/weight/{i}.pth')"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.8.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}