def test_decoding_time(): """Test TimeDecoding """ epochs = make_epochs() tg = TimeDecoding() assert_equal("<TimeDecoding | no fit, no prediction, no score>", '%s' % tg) assert_true(hasattr(tg, 'times')) assert_true(not hasattr(tg, 'train_times')) assert_true(not hasattr(tg, 'test_times')) tg.fit(epochs) assert_equal("<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), no prediction, no score>", '%s' % tg) assert_true(not hasattr(tg, 'train_times_')) assert_true(not hasattr(tg, 'test_times_')) assert_raises(RuntimeError, tg.score, epochs=None) tg.predict(epochs) assert_equal("<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), predicted 14 epochs, no score>", '%s' % tg) assert_array_equal(np.shape(tg.y_pred_), [15, 14, 1]) tg.score(epochs) tg.score() assert_array_equal(np.shape(tg.scores_), [15]) assert_equal("<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), predicted 14 epochs,\n scored (accuracy_score)>", '%s' % tg)
def test_decoding_time(): epochs = make_epochs() tg = TimeDecoding() assert_equal("<TimeDecoding | no fit, no prediction, no score>", '%s' % tg) assert_true(hasattr(tg, 'times')) assert_true(not hasattr(tg, 'train_times')) assert_true(not hasattr(tg, 'test_times')) tg.fit(epochs) assert_equal( "<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), no prediction, no score>", '%s' % tg) assert_true(not hasattr(tg, 'train_times_')) assert_true(not hasattr(tg, 'test_times_')) assert_raises(RuntimeError, tg.score, epochs=None) tg.predict(epochs) assert_equal( "<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), predicted 14 epochs, no score>", '%s' % tg) assert_array_equal(np.shape(tg.y_pred_), [15, 14, 1]) tg.score(epochs) tg.score() assert_array_equal(np.shape(tg.scores_), [15]) assert_equal( "<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), predicted 14 epochs,\n scored (accuracy_score)>", '%s' % tg)
class SensorDecoding(): """Fit an estimator on each sensor separately across all time points""" def __init__(self, clf=None, predict_method='predict', scorer=None, n_jobs=1, ch_groups=None, cv=5): self.clf = clf self.predict_method = predict_method self.scorer = scorer self.n_jobs = n_jobs self.ch_groups = ch_groups self.cv = cv def fit(self, epochs, y=None): from mne.decoding import TimeDecoding epochs = self._prepare_data(epochs) self._td = TimeDecoding(clf=self.clf, cv=self.cv, predict_method=self.predict_method, scorer=self.scorer, n_jobs=self.n_jobs,) self._td.fit(epochs, y=y) def predict(self, epochs): epochs = self._prepare_data(epochs) self._td.predict(epochs) self.y_pred_ = self._td.y_pred_ return self.y_pred_ def score(self, epochs=None, y=None): if not hasattr(self, 'y_pred_'): self.predict(epochs) self._td.score(y=y) self.scores_ = self._td.scores_ return self.scores_ def _prepare_data(self, epochs): """Swap channel and time""" from mne import EpochsArray, create_info # regroup channels X = self._group_channels(epochs) # swap time and channels X = X.transpose([0, 2, 1]) # format for GAT epochs_ = EpochsArray( data=X, events=epochs.events, info=create_info(X.shape[1], sfreq=1, ch_types='mag')) return epochs_ def _group_channels(self, epochs): if self.ch_groups is None: self.ch_groups = np.arange(len(epochs.ch_names))[None, :] if self.ch_groups.ndim != 2: raise ValueError('Channel groups must be n_group * n_chans array') n_group = len(self.ch_groups) n_time = len(epochs.times) X = np.empty((len(epochs), n_group, self.ch_groups.shape[1] * n_time)) for ii, chans in enumerate(self.ch_groups): X[:, ii, :] = np.hstack([epochs._data[:, ch, :] for ch in chans]) return X
def calculate_diagonal_decoding(epochs, picked_channels, y, fold_nr, outputfile): if picked_channels: epochs.pick_channels(picked_channels) else: print 'no channels to pick' #epochs.equalize_event_counts(epochs.event_id, copy=False) cv = StratifiedKFold(y=y, n_folds=fold_nr) # do a stratified cross-validation #armar clf y pasarlo al time decoding para mas de dos condiciones td = TimeDecoding(cv=cv, scorer=roc_auc_score, n_jobs=1, score_mode='fold-wise') # Fit, score, and plot td.fit(epochs, y=y) scores = td.score(epochs) if outputfile: scipy.io.savemat(outputfile, {'scores': scores}) print('TD DONE') return scores
def test_decoding_time(): """Test TimeDecoding """ from sklearn.svm import SVR from sklearn.cross_validation import KFold epochs = make_epochs() tg = TimeDecoding() assert_equal("<TimeDecoding | no fit, no prediction, no score>", '%s' % tg) assert_true(hasattr(tg, 'times')) assert_true(not hasattr(tg, 'train_times')) assert_true(not hasattr(tg, 'test_times')) tg.fit(epochs) assert_equal( "<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), no prediction, no score>", '%s' % tg) assert_true(not hasattr(tg, 'train_times_')) assert_true(not hasattr(tg, 'test_times_')) assert_raises(RuntimeError, tg.score, epochs=None) with warnings.catch_warnings(record=True): # not vectorizing tg.predict(epochs) assert_equal( "<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), predicted 14 epochs, no score>", '%s' % tg) assert_array_equal(np.shape(tg.y_pred_), [15, 14, 1]) with warnings.catch_warnings(record=True): # not vectorizing tg.score(epochs) tg.score() assert_array_equal(np.shape(tg.scores_), [15]) assert_equal( "<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), predicted 14 epochs,\n scored (accuracy_score)>", '%s' % tg) # Test with regressor clf = SVR() cv = KFold(len(epochs)) y = np.random.rand(len(epochs)) tg = TimeDecoding(clf=clf, cv=cv) tg.fit(epochs, y=y)
def test_decoding_time(): """Test TimeDecoding.""" from sklearn.svm import SVR if check_version('sklearn', '0.18'): from sklearn.model_selection import KFold else: from sklearn.cross_validation import KFold epochs = make_epochs() with warnings.catch_warnings(record=True): # dep tg = TimeDecoding() assert_equal("<TimeDecoding | no fit, no prediction, no score>", '%s' % tg) assert_true(hasattr(tg, 'times')) assert_true(not hasattr(tg, 'train_times')) assert_true(not hasattr(tg, 'test_times')) tg.fit(epochs) assert_equal( "<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), no prediction, no score>", '%s' % tg) assert_true(not hasattr(tg, 'train_times_')) assert_true(not hasattr(tg, 'test_times_')) assert_raises(RuntimeError, tg.score, epochs=None) with warnings.catch_warnings(record=True): # not vectorizing tg.predict(epochs) assert_equal( "<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), predicted 14 epochs, no score>", '%s' % tg) assert_array_equal(np.shape(tg.y_pred_), [15, 14, 1]) with warnings.catch_warnings(record=True): # not vectorizing tg.score(epochs) tg.score() assert_array_equal(np.shape(tg.scores_), [15]) assert_equal( "<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), predicted 14 epochs,\n scored (accuracy_score)>", '%s' % tg) # Test with regressor clf = SVR() cv = KFold(len(epochs)) y = np.random.rand(len(epochs)) with warnings.catch_warnings(record=True): # dep tg = TimeDecoding(clf=clf, cv=cv) tg.fit(epochs, y=y) # Test scorer parameter to accept string epochs.crop(epochs.times[0], epochs.times[2]) with warnings.catch_warnings(record=True): # dep td_1 = TimeDecoding(scorer='accuracy') td_1.fit(epochs) score_1 = td_1.score(epochs) with warnings.catch_warnings(record=True): # dep td_2 = TimeDecoding() td_2.fit(epochs) score_2 = td_2.score(epochs) assert_array_equal(score_1, score_2) td_1.scorer = 'accuracies' assert_raises(KeyError, td_1.score, epochs)
def test_decoding_time(): """Test TimeDecoding.""" from sklearn.svm import SVR if check_version('sklearn', '0.18'): from sklearn.model_selection import KFold else: from sklearn.cross_validation import KFold epochs = make_epochs() with warnings.catch_warnings(record=True): # dep tg = TimeDecoding() assert_equal("<TimeDecoding | no fit, no prediction, no score>", '%s' % tg) assert_true(hasattr(tg, 'times')) assert_true(not hasattr(tg, 'train_times')) assert_true(not hasattr(tg, 'test_times')) tg.fit(epochs) assert_equal("<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), no prediction, no score>", '%s' % tg) assert_true(not hasattr(tg, 'train_times_')) assert_true(not hasattr(tg, 'test_times_')) assert_raises(RuntimeError, tg.score, epochs=None) with warnings.catch_warnings(record=True): # not vectorizing tg.predict(epochs) assert_equal("<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), predicted 14 epochs, no score>", '%s' % tg) assert_array_equal(np.shape(tg.y_pred_), [15, 14, 1]) with warnings.catch_warnings(record=True): # not vectorizing tg.score(epochs) tg.score() assert_array_equal(np.shape(tg.scores_), [15]) assert_equal("<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), predicted 14 epochs,\n scored (accuracy_score)>", '%s' % tg) # Test with regressor clf = SVR() cv = KFold(len(epochs)) y = np.random.rand(len(epochs)) with warnings.catch_warnings(record=True): # dep tg = TimeDecoding(clf=clf, cv=cv) tg.fit(epochs, y=y) # Test scorer parameter to accept string epochs.crop(epochs.times[0], epochs.times[2]) with warnings.catch_warnings(record=True): # dep td_1 = TimeDecoding(scorer='accuracy') td_1.fit(epochs) score_1 = td_1.score(epochs) with warnings.catch_warnings(record=True): # dep td_2 = TimeDecoding() td_2.fit(epochs) score_2 = td_2.score(epochs) assert_array_equal(score_1, score_2) td_1.scorer = 'accuracies' assert_raises(KeyError, td_1.score, epochs)
def test_decoding_time(): """Test TimeDecoding """ from sklearn.svm import SVR from sklearn.cross_validation import KFold epochs = make_epochs() tg = TimeDecoding() assert_equal("<TimeDecoding | no fit, no prediction, no score>", '%s' % tg) assert_true(hasattr(tg, 'times')) assert_true(not hasattr(tg, 'train_times')) assert_true(not hasattr(tg, 'test_times')) tg.fit(epochs) assert_equal("<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), no prediction, no score>", '%s' % tg) assert_true(not hasattr(tg, 'train_times_')) assert_true(not hasattr(tg, 'test_times_')) assert_raises(RuntimeError, tg.score, epochs=None) with warnings.catch_warnings(record=True): # not vectorizing tg.predict(epochs) assert_equal("<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), predicted 14 epochs, no score>", '%s' % tg) assert_array_equal(np.shape(tg.y_pred_), [15, 14, 1]) with warnings.catch_warnings(record=True): # not vectorizing tg.score(epochs) tg.score() assert_array_equal(np.shape(tg.scores_), [15]) assert_equal("<TimeDecoding | fitted, start : -0.200 (s), stop : 0.499 " "(s), predicted 14 epochs,\n scored (accuracy_score)>", '%s' % tg) # Test with regressor clf = SVR() cv = KFold(len(epochs)) y = np.random.rand(len(epochs)) tg = TimeDecoding(clf=clf, cv=cv) tg.fit(epochs, y=y)
def run_time_decoding(subject_id, condition1, condition2): subject = "sub%03d" % subject_id data_path = os.path.join(meg_dir, subject) epochs = mne.read_epochs(os.path.join(data_path, '%s-epo.fif' % subject)) # We define the epochs and the labels n_cond1 = len(epochs[condition1]) n_cond2 = len(epochs[condition2]) y = np.r_[np.ones((n_cond1, )), np.zeros((n_cond2, ))] epochs = mne.concatenate_epochs([epochs[condition1], epochs[condition2]]) epochs.apply_baseline() # Let us restrict ourselves to the occipital channels from mne.selection import read_selection ch_names = [ch_name.replace(' ', '') for ch_name in read_selection('occipital')] epochs.pick_types(meg='mag').pick_channels(ch_names) # Now we fit and plot the time decoder from mne.decoding import TimeDecoding times = dict(step=0.005) # fit a classifier only every 5 ms # Use AUC because chance level is same regardless of the class balance td = TimeDecoding(predict_mode='cross-validation', times=times, scorer='roc_auc') td.fit(epochs, y) # let's save the scores now a_vs_b = '%s_vs_%s' % (os.path.basename(condition1), os.path.basename(condition2)) fname_td = os.path.join(data_path, '%s-td-auc-%s.mat' % (subject, a_vs_b)) from scipy.io import savemat savemat(fname_td, {'scores': td.score(epochs), 'times': td.times_['times']})
class TimeFrequencyDecoding(): """Search light across sensor in each time-frequency bin.""" def __init__(self, freqs, tfr_kwargs=None, td=None, n_jobs=1): from mne.decoding import TimeDecoding # Search light parameters self.td = TimeDecoding() if td is None else td self.td.n_jobs = n_jobs if not isinstance(self.td, TimeDecoding): raise ValueError('`td` needs to be a `TimeDecoding` object, got ' '%s instead.' % type(td)) if (('step' in self.td.times.keys()) or ('length' in self.td.times.keys())): raise ValueError("Cannot use advance `time` param") # Time frequency decomposition parameters self.tfr_kwargs = tfr_kwargs if tfr_kwargs is None: self.tfr_kwargs = dict() self.tfr_kwargs['n_jobs'] = n_jobs self.tfr_kwargs['frequencies'] = freqs self.freqs = freqs def transform(self, epochs): from mne import EpochsArray from mne.time_frequency import single_trial_power sfreq = epochs.info['sfreq'] # Time Frequency decomposition tfr = single_trial_power(epochs._data, sfreq=sfreq, **self.tfr_kwargs) # Consider frequencies as if it was different time points n_trial, n_chan, n_freq, n_time = tfr.shape tfr = np.reshape(tfr, [n_trial, n_chan, n_freq * n_time]) # Make pseudo epochs sfreq = epochs.info['sfreq'] decim = self.tfr_kwargs.get('decim', None) if isinstance(decim, slice): decim = decim.step if decim is not None and decim > 1: sfreq /= decim info = epochs.info.copy() info['sfreq'] = sfreq self._tfr_epochs = EpochsArray(data=tfr, info=info, events=epochs.events) def fit(self, epochs=None, y=None): self._check_transform(epochs) self.td.fit(self._tfr_epochs, y=y) return self def predict(self, epochs=None): self._check_transform(epochs) self.td.predict(self._tfr_epochs) def y_pred_(self): nT, nt, ns, np = self.td.y_pred_.shape nfreq = len(self.tfr_kwargs['frequencies']) return np.reshape(self.td.y_pred_, [nfreq, nT, ns, np]) def score(self, epochs=None, y=None): if epochs is not None: self._check_transform(epochs) epochs = self._tfr_epochs scores = self.td.score(epochs, y=y) self.scores_ = np.reshape(scores, [len(self.freqs), -1]) return self.scores_ def _check_transform(self, epochs): if epochs is not None: self.transform(epochs) if not hasattr(self, '_tfr_epochs'): raise RuntimeError('You need to transform epochs first')
eeg=False, stim=True, eog=True, exclude='bads') # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=None, preload=True, reject=dict(grad=4000e-13, eog=150e-6)) epochs_list = [epochs[k] for k in event_id] mne.epochs.equalize_epoch_counts(epochs_list) data_picks = mne.pick_types(epochs.info, meg=True, exclude='bads') ############################################################################### # Setup decoding: default is linear SVC td = TimeDecoding(predict_mode='cross-validation', n_jobs=1) # Fit td.fit(epochs) # Compute accuracy td.score(epochs) # Plot scores across time td.plot(title='Sensor space decoding')
data_picks = mne.pick_types(epochs.info, meg=True, exclude="bads") ############################################################################### # Temporal decoding # ----------------- # # We'll use the default classifer for a binary classification problem # which is a linear Support Vector Machine (SVM). td = TimeDecoding(predict_mode="cross-validation", n_jobs=1) # Fit td.fit(epochs) # Compute accuracy td.score(epochs) # Plot scores across time td.plot(title="Sensor space decoding") ############################################################################### # Generalization Across Time # -------------------------- # # This runs the analysis used in [1]_ and further detailed in [2]_ # # Here we'll use a stratified cross-validation scheme. # make response vector y = np.zeros(len(epochs.events), dtype=int) y[epochs.events[:, 2] == 3] = 1
epochsR_list = [epochsR[k] for k in event_id] mne.epochs.equalize_epoch_counts(epochsR_list) data_picks = mne.pick_types(epochsR.info, meg=True, exclude='bads') epochsR.plot() epochsL.plot() # Temporal decoding ##### Left Hemisphere Temporal Decoding td = TimeDecoding(predict_mode='cross-validation', n_jobs=1) # Fit td.fit(epochsL) # Compute accuracy z = td.score(epochsL) # Plot scores across time td.plot(title='Left Sensor space decoding') ##### Right Hemisphere Temporal Decoding # Fit td.fit(epochsR) # Compute accuracy x = td.score(epochsR) # Plot scores across time td.plot(title='Right Sensor space decoding') ############ epochsL_train = epochsL.copy().crop(tmin=-0.1, tmax=1) labelsL = epochsL.events[:, -1]