{
  "nbformat_minor": 0, 
  "nbformat": 4, 
  "cells": [
    {
      "execution_count": null, 
      "cell_type": "code", 
      "source": [
        "%matplotlib inline"
      ], 
      "outputs": [], 
      "metadata": {
        "collapsed": false
      }
    }, 
    {
      "source": [
        "\n# Decoding sensor space data\n\n\nDecoding, a.k.a MVPA or supervised machine learning applied to MEG\ndata in sensor space. Here the classifier is applied to every time\npoint.\n\n"
      ], 
      "cell_type": "markdown", 
      "metadata": {}
    }, 
    {
      "execution_count": null, 
      "cell_type": "code", 
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.cross_validation import StratifiedKFold\n\nimport mne\nfrom mne.datasets import sample\nfrom mne.decoding import TimeDecoding, GeneralizationAcrossTime\n\ndata_path = sample.data_path()\n\nplt.close('all')"
      ], 
      "outputs": [], 
      "metadata": {
        "collapsed": false
      }
    }, 
    {
      "source": [
        "Set parameters\n\n"
      ], 
      "cell_type": "markdown", 
      "metadata": {}
    }, 
    {
      "execution_count": null, 
      "cell_type": "code", 
      "source": [
        "raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'\nevent_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'\ntmin, tmax = -0.2, 0.5\nevent_id = dict(aud_l=1, vis_l=3)\n\n# Setup for reading the raw data\nraw = mne.io.read_raw_fif(raw_fname, preload=True)\nraw.filter(2, None)  # replace baselining with high-pass\nevents = mne.read_events(event_fname)\n\n# Set up pick list: EEG + MEG - bad channels (modify to your needs)\nraw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more\npicks = mne.pick_types(raw.info, meg='grad', eeg=False, stim=True, eog=True,\n                       exclude='bads')\n\n# Read epochs\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,\n                    picks=picks, baseline=None, preload=True,\n                    reject=dict(grad=4000e-13, eog=150e-6))\n\nepochs_list = [epochs[k] for k in event_id]\nmne.epochs.equalize_epoch_counts(epochs_list)\ndata_picks = mne.pick_types(epochs.info, meg=True, exclude='bads')"
      ], 
      "outputs": [], 
      "metadata": {
        "collapsed": false
      }
    }, 
    {
      "source": [
        "Temporal decoding\n-----------------\n\nWe'll use the default classifer for a binary classification problem\nwhich is a linear Support Vector Machine (SVM).\n\n"
      ], 
      "cell_type": "markdown", 
      "metadata": {}
    }, 
    {
      "execution_count": null, 
      "cell_type": "code", 
      "source": [
        "td = TimeDecoding(predict_mode='cross-validation', n_jobs=1)\n\n# Fit\ntd.fit(epochs)\n\n# Compute accuracy\ntd.score(epochs)\n\n# Plot scores across time\ntd.plot(title='Sensor space decoding')"
      ], 
      "outputs": [], 
      "metadata": {
        "collapsed": false
      }
    }, 
    {
      "source": [
        "Generalization Across Time\n--------------------------\n\nThis runs the analysis used in [1]_ and further detailed in [2]_\n\nHere we'll use a stratified cross-validation scheme.\n\n"
      ], 
      "cell_type": "markdown", 
      "metadata": {}
    }, 
    {
      "execution_count": null, 
      "cell_type": "code", 
      "source": [
        "# make response vector\ny = np.zeros(len(epochs.events), dtype=int)\ny[epochs.events[:, 2] == 3] = 1\ncv = StratifiedKFold(y=y)  # do a stratified cross-validation\n\n# define the GeneralizationAcrossTime object\ngat = GeneralizationAcrossTime(predict_mode='cross-validation', n_jobs=1,\n                               cv=cv, scorer=roc_auc_score)\n\n# fit and score\ngat.fit(epochs, y=y)\ngat.score(epochs)\n\n# let's visualize now\ngat.plot()\ngat.plot_diagonal()"
      ], 
      "outputs": [], 
      "metadata": {
        "collapsed": false
      }
    }, 
    {
      "source": [
        "Exercise\n--------\n - Can you improve the performance using full epochs and a common spatial\n   pattern (CSP) used by most BCI systems?\n - Explore other datasets from MNE (e.g. Face dataset from SPM to predict\n   Face vs. Scrambled)\n\nHave a look at the example\n`sphx_glr_auto_examples_decoding_plot_decoding_csp_space.py`\n\nReferences\n==========\n\n.. [1] Jean-Remi King, Alexandre Gramfort, Aaron Schurger, Lionel Naccache\n       and Stanislas Dehaene, \"Two distinct dynamic modes subtend the\n       detection of unexpected sounds\", PLOS ONE, 2013,\n       http://www.ncbi.nlm.nih.gov/pubmed/24475052\n\n.. [2] King & Dehaene (2014) 'Characterizing the dynamics of mental\n       representations: the temporal generalization method', Trends In\n       Cognitive Sciences, 18(4), 203-210.\n       http://www.ncbi.nlm.nih.gov/pubmed/24593982\n\n"
      ], 
      "cell_type": "markdown", 
      "metadata": {}
    }
  ], 
  "metadata": {
    "kernelspec": {
      "display_name": "Python 2", 
      "name": "python2", 
      "language": "python"
    }, 
    "language_info": {
      "mimetype": "text/x-python", 
      "nbconvert_exporter": "python", 
      "name": "python", 
      "file_extension": ".py", 
      "version": "2.7.13", 
      "pygments_lexer": "ipython2", 
      "codemirror_mode": {
        "version": 2, 
        "name": "ipython"
      }
    }
  }
}