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(): 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 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 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 _run(epochs, events, analysis): """Runs Time Frequency Decoding on a given subject and analysis""" # Set time frequency parameters start = np.where(epochs.times >= -.200)[0][0] stop = np.where(epochs.times >= 1.400)[0][0] frequencies = np.logspace(np.log10(4), np.log10(80), 25) decim = slice(start, stop, 8) # ~62 Hz after TFR # Select relevant trials (e.g. remove absent trials) query, condition = analysis['query'], analysis['condition'] sel = range(len(events)) if query is None \ else events.query(query).index sel = [ii for ii in sel if ~np.isnan(events[condition][sel][ii])] y = np.array(events[condition], dtype=np.float32) print analysis['name'], np.unique(y[sel]), len(sel) # Abort if no trial if len(sel) == 0: return # Apply analysis td = TimeDecoding(clf=analysis['clf'], cv=analysis['cv'], scorer=analysis['scorer'], n_jobs=-1) tfd = TimeFrequencyDecoding(frequencies, td=td, n_jobs=-1, tfr_kwargs=dict(n_cycles=5, decim=decim)) print(subject, analysis['name'], 'fit') tfd.fit(epochs[sel], y=y[sel]) tfd.n_jobs = 1 # FIXME joblib else error with too many jobs?! tfd.td.n_jobs = 1 print(subject, analysis['name'], 'score') score = tfd.score() # Save analysis print(subject, analysis['name'], 'save') if analysis['name'] not in ['target_present', 'target_circAngle']: save([tfd.td.y_pred_, sel, events, epochs.times[decim], frequencies], 'decod_tfr', subject=subject, analysis=analysis['name'], overwrite=True) save([score, epochs.times[decim], frequencies], 'score_tfr', subject=subject, analysis=analysis['name'], overwrite=True)
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 __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
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')