{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n\n# Decoding sensor space data with generalization across time and conditions\n\nThis example runs the analysis described in :footcite:`KingDehaene2014`. It\nillustrates how one can\nfit a linear classifier to identify a discriminatory topography at a given time\ninstant and subsequently assess whether this linear model can accurately\npredict all of the time samples of a second set of conditions.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Authors: Jean-R\u00e9mi King \n# Alexandre Gramfort \n# Denis Engemann \n#\n# License: BSD-3-Clause\n# Copyright the MNE-Python contributors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\n\nimport mne\nfrom mne.datasets import sample\nfrom mne.decoding import GeneralizingEstimator\n\nprint(__doc__)\n\n# Preprocess data\ndata_path = sample.data_path()\n# Load and filter data, set up epochs\nmeg_path = data_path / \"MEG\" / \"sample\"\nraw_fname = meg_path / \"sample_audvis_filt-0-40_raw.fif\"\nevents_fname = meg_path / \"sample_audvis_filt-0-40_raw-eve.fif\"\nraw = mne.io.read_raw_fif(raw_fname, preload=True)\npicks = mne.pick_types(raw.info, meg=True, exclude=\"bads\") # Pick MEG channels\nraw.filter(1.0, 30.0, fir_design=\"firwin\") # Band pass filtering signals\nevents = mne.read_events(events_fname)\nevent_id = {\n \"Auditory/Left\": 1,\n \"Auditory/Right\": 2,\n \"Visual/Left\": 3,\n \"Visual/Right\": 4,\n}\ntmin = -0.050\ntmax = 0.400\n# decimate to make the example faster to run, but then use verbose='error' in\n# the Epochs constructor to suppress warning about decimation causing aliasing\ndecim = 2\nepochs = mne.Epochs(\n raw,\n events,\n event_id=event_id,\n tmin=tmin,\n tmax=tmax,\n proj=True,\n picks=picks,\n baseline=None,\n preload=True,\n reject=dict(mag=5e-12),\n decim=decim,\n verbose=\"error\",\n)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will train the classifier on all left visual vs auditory trials\nand test on all right visual vs auditory trials.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "clf = make_pipeline(\n StandardScaler(),\n LogisticRegression(solver=\"liblinear\"), # liblinear is faster than lbfgs\n)\ntime_gen = GeneralizingEstimator(clf, scoring=\"roc_auc\", n_jobs=None, verbose=True)\n\n# Fit classifiers on the epochs where the stimulus was presented to the left.\n# Note that the experimental condition y indicates auditory or visual\ntime_gen.fit(X=epochs[\"Left\"].get_data(copy=False), y=epochs[\"Left\"].events[:, 2] > 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Score on the epochs where the stimulus was presented to the right.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "scores = time_gen.score(\n X=epochs[\"Right\"].get_data(copy=False), y=epochs[\"Right\"].events[:, 2] > 2\n)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig, ax = plt.subplots(layout=\"constrained\")\nim = ax.matshow(\n scores,\n vmin=0,\n vmax=1.0,\n cmap=\"RdBu_r\",\n origin=\"lower\",\n extent=epochs.times[[0, -1, 0, -1]],\n)\nax.axhline(0.0, color=\"k\")\nax.axvline(0.0, color=\"k\")\nax.xaxis.set_ticks_position(\"bottom\")\nax.set_xlabel(\n 'Condition: \"Right\"\\nTesting Time (s)',\n)\nax.set_ylabel('Condition: \"Left\"\\nTraining Time (s)')\nax.set_title(\"Generalization across time and condition\", fontweight=\"bold\")\nfig.colorbar(im, ax=ax, label=\"Performance (ROC AUC)\")\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## References\n.. footbibliography::\n\n" ] } ], "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.12.2" } }, "nbformat": 4, "nbformat_minor": 0 }