本文整理汇总了Python中mne.decoding.GeneralizationAcrossTime.score方法的典型用法代码示例。如果您正苦于以下问题:Python GeneralizationAcrossTime.score方法的具体用法?Python GeneralizationAcrossTime.score怎么用?Python GeneralizationAcrossTime.score使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mne.decoding.GeneralizationAcrossTime
的用法示例。
在下文中一共展示了GeneralizationAcrossTime.score方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_circular_classifiers
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
def test_circular_classifiers():
from mne.decoding import GeneralizationAcrossTime
from ..scorers import scorer_angle
from sklearn.linear_model import Ridge, RidgeCV
epochs, angles = make_circular_data()
clf_list = [PolarRegression, AngularRegression,
SVR_polar, SVR_angle] # XXX will be deprecated
for clf_init in clf_list:
for independent in [False, True]:
if clf_init in [SVR_polar, SVR_angle]:
if (not independent):
continue
clf = clf_init(clf=Ridge(random_state=0))
else:
clf = clf_init(clf=Ridge(random_state=0),
independent=independent)
print clf_init, independent
gat = GeneralizationAcrossTime(clf=clf, scorer=scorer_angle)
gat.fit(epochs, y=angles)
gat.predict(epochs)
gat.score(y=angles)
assert_true(np.abs(gat.scores_[0][0]) < .5) # chance level
assert_true(gat.scores_[1][1] > 1.) # decode
assert_true(gat.scores_[2][2] > 1.) # decode
assert_true(gat.scores_[1][2] < -1.) # anti-generalize
# Test args
gat = GeneralizationAcrossTime(clf=RidgeCV(alphas=[1., 2.]),
scorer=scorer_angle)
gat.fit(epochs, y=angles)
gat = GeneralizationAcrossTime(clf=RidgeCV(), scorer=scorer_angle)
gat.fit(epochs, y=angles)
示例2: _get_data
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
def _get_data(tmin=-0.2, tmax=0.5, event_id=dict(aud_l=1, vis_l=3),
event_id_gen=dict(aud_l=2, vis_l=4), test_times=None):
"""Aux function for testing GAT viz."""
with warnings.catch_warnings(record=True): # deprecated
gat = GeneralizationAcrossTime()
raw = read_raw_fif(raw_fname)
raw.add_proj([], remove_existing=True)
events = read_events(event_name)
picks = pick_types(raw.info, meg='mag', stim=False, ecg=False,
eog=False, exclude='bads')
picks = picks[1:13:3]
decim = 30
# Test on time generalization within one condition
with warnings.catch_warnings(record=True):
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
preload=True, decim=decim)
epochs_list = [epochs[k] for k in event_id]
equalize_epoch_counts(epochs_list)
epochs = concatenate_epochs(epochs_list)
# Test default running
with warnings.catch_warnings(record=True): # deprecated
gat = GeneralizationAcrossTime(test_times=test_times)
gat.fit(epochs)
gat.score(epochs)
return gat
示例3: quick_score
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
def quick_score(X, y, clf=None, scorer=None):
from sklearn.cross_validation import KFold
regression = (len(np.unique(y)) > 2) & isinstance(y[0], float)
if scorer is None:
scorer = scorer_spearman if regression else scorer_auc
if clf is None:
clf = RidgeCV(alphas=[(2 * C) ** -1 for C in [1e-4, 1e-2, 1]])\
if regression else force_predict(LogisticRegression(), axis=1)
sel = np.where(~np.isnan(y))[0]
X = X[sel, :, :]
y = y[sel]
epochs = mat2mne(X, sfreq=100)
clf = make_pipeline(StandardScaler(), clf)
cv = KFold(len(y), 5) if regression else None
gat = GeneralizationAcrossTime(clf=clf, n_jobs=-1, scorer=scorer, cv=cv)
gat.fit(epochs, y)
gat.score(epochs, y)
return gat
示例4: _get_data
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
def _get_data():
"""Aux function for testing GAT viz"""
gat = GeneralizationAcrossTime()
raw = io.Raw(raw_fname, preload=False)
events = read_events(event_name)
picks = pick_types(raw.info, meg='mag', stim=False, ecg=False,
eog=False, exclude='bads')
picks = picks[1:13:3]
decim = 30
# Test on time generalization within one condition
with warnings.catch_warnings(record=True):
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True, decim=decim)
# Test default running
gat = GeneralizationAcrossTime()
gat.fit(epochs)
gat.score(epochs)
return gat
示例5: _run
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
def _run(epochs, events, analysis):
"""Runs temporal generalization for a given subject and analysis"""
print(subject, analysis['name'])
# subselect the trials (e.g. exclude absent trials) with a
# dataframe query defined in conditions.py
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])]
# The to-be-predicted value, for each trial:
y = np.array(events[condition], dtype=np.float32)
print analysis['name'], np.unique(y[sel]), len(sel)
# Abort if there is no trial
if len(sel) == 0:
return
# Apply analysis
gat = GeneralizationAcrossTime(clf=analysis['clf'],
cv=analysis['cv'],
scorer=analysis['scorer'],
n_jobs=-1)
print(subject, analysis['name'], 'fit')
gat.fit(epochs[sel], y=y[sel])
print(subject, analysis['name'], 'score')
score = gat.score(epochs[sel], y=y[sel])
print(subject, analysis['name'], 'save')
# save space
if analysis['name'] not in ['probe_phase', 'target_circAngle']:
# we'll need the estimator trained on the probe_phase and to generalize
# to the target phase and prove that there is a significant signal.
gat.estimators_ = None
if analysis['name'] not in ['target_present', 'target_circAngle',
'probe_circAngle']:
# We need these individual prediction to control for the correlation
# between target and probe angle.
gat.y_pred_ = None
# Save analysis
save([gat, analysis, sel, events], 'decod',
subject=subject, analysis=analysis['name'], overwrite=True,
upload=True)
save([score, epochs.times], 'score',
subject=subject, analysis=analysis['name'], overwrite=True,
upload=True)
return
示例6: _decod
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
def _decod(subject, analysis):
from mne.decoding import GeneralizationAcrossTime
# if already computed let's just load it from disk
fname_kwargs = dict(subject=subject, analysis=analysis['name'] + '_vhp')
score_fname = paths('score', **fname_kwargs)
if op.exists(score_fname):
return load('score', **fname_kwargs)
epochs = _get_epochs(subject)
events = load('behavior', subject=subject)
# Let's not recompute everything, this is just a control analysis
print(subject, analysis['name'])
epochs._data = epochs.get_data()
epochs.preload = True
epochs.crop(0., .900)
epochs.decimate(2)
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)
if len(sel) == 0:
return
# Apply analysis
gat = GeneralizationAcrossTime(clf=analysis['clf'],
cv=analysis['cv'],
scorer=analysis['scorer'],
n_jobs=-1)
print(subject, analysis['name'], 'fit')
gat.fit(epochs[sel], y=y[sel])
print(subject, analysis['name'], 'score')
score = gat.score(epochs[sel], y=y[sel])
print(subject, analysis['name'], 'save')
# save space
gat.estimators_ = None
gat.y_pred_ = None
# Save analysis
save([score, epochs.times], 'score', overwrite=True, upload=True,
**fname_kwargs)
return score, epochs.times
示例7: test_generalization_across_time
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
def test_generalization_across_time():
"""Test time generalization decoding
"""
from sklearn.svm import SVC
from sklearn.linear_model import RANSACRegressor, LinearRegression
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from sklearn.cross_validation import LeaveOneLabelOut
epochs = make_epochs()
# Test default running
gat = GeneralizationAcrossTime(picks='foo')
assert_equal("<GAT | no fit, no prediction, no score>", "%s" % gat)
assert_raises(ValueError, gat.fit, epochs)
with warnings.catch_warnings(record=True):
# check classic fit + check manual picks
gat.picks = [0]
gat.fit(epochs)
# check optional y as array
gat.picks = None
gat.fit(epochs, y=epochs.events[:, 2])
# check optional y as list
gat.fit(epochs, y=epochs.events[:, 2].tolist())
assert_equal(len(gat.picks_), len(gat.ch_names), 1)
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), no "
"prediction, no score>", '%s' % gat)
assert_equal(gat.ch_names, epochs.ch_names)
gat.predict(epochs)
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), "
"predicted 14 epochs, no score>",
"%s" % gat)
gat.score(epochs)
gat.score(epochs, y=epochs.events[:, 2])
gat.score(epochs, y=epochs.events[:, 2].tolist())
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), "
"predicted 14 epochs,\n scored "
"(accuracy_score)>", "%s" % gat)
with warnings.catch_warnings(record=True):
gat.fit(epochs, y=epochs.events[:, 2])
old_mode = gat.predict_mode
gat.predict_mode = 'super-foo-mode'
assert_raises(ValueError, gat.predict, epochs)
gat.predict_mode = old_mode
gat.score(epochs, y=epochs.events[:, 2])
assert_true("accuracy_score" in '%s' % gat.scorer_)
epochs2 = epochs.copy()
# check _DecodingTime class
assert_equal("<DecodingTime | start: -0.200 (s), stop: 0.499 (s), step: "
"0.050 (s), length: 0.050 (s), n_time_windows: 15>",
"%s" % gat.train_times_)
assert_equal("<DecodingTime | start: -0.200 (s), stop: 0.499 (s), step: "
"0.050 (s), length: 0.050 (s), n_time_windows: 15 x 15>",
"%s" % gat.test_times_)
# the y-check
gat.predict_mode = 'mean-prediction'
epochs2.events[:, 2] += 10
gat_ = copy.deepcopy(gat)
assert_raises(ValueError, gat_.score, epochs2)
gat.predict_mode = 'cross-validation'
# Test basics
# --- number of trials
assert_true(gat.y_train_.shape[0] ==
gat.y_true_.shape[0] ==
len(gat.y_pred_[0][0]) == 14)
# --- number of folds
assert_true(np.shape(gat.estimators_)[1] == gat.cv)
# --- length training size
assert_true(len(gat.train_times_['slices']) == 15 ==
np.shape(gat.estimators_)[0])
# --- length testing sizes
assert_true(len(gat.test_times_['slices']) == 15 ==
np.shape(gat.scores_)[0])
assert_true(len(gat.test_times_['slices'][0]) == 15 ==
np.shape(gat.scores_)[1])
# Test longer time window
gat = GeneralizationAcrossTime(train_times={'length': .100})
with warnings.catch_warnings(record=True):
gat2 = gat.fit(epochs)
assert_true(gat is gat2) # return self
assert_true(hasattr(gat2, 'cv_'))
assert_true(gat2.cv_ != gat.cv)
scores = gat.score(epochs)
assert_true(isinstance(scores, list)) # type check
assert_equal(len(scores[0]), len(scores)) # shape check
assert_equal(len(gat.test_times_['slices'][0][0]), 2)
# Decim training steps
gat = GeneralizationAcrossTime(train_times={'step': .100})
with warnings.catch_warnings(record=True):
gat.fit(epochs)
gat.score(epochs)
assert_true(len(gat.scores_) == len(gat.estimators_) == 8) # training time
#.........这里部分代码省略.........
示例8: GeneralizationAcrossTime
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
epochs = mne.Epochs(raw, events, event_id, -0.050, 0.400, proj=True,
picks=picks, baseline=None, preload=True,
reject=dict(mag=5e-12), decim=decim, verbose=False)
# We will train the classifier on all left visual vs auditory trials
# and test on all right visual vs auditory trials.
# In this case, because the test data is independent from the train data,
# we test the classifier of each fold and average the respective predictions.
# Define events of interest
triggers = epochs.events[:, 2]
viz_vs_auditory = np.in1d(triggers, (1, 2)).astype(int)
gat = GeneralizationAcrossTime(predict_mode='mean-prediction', n_jobs=1)
# For our left events, which ones are visual?
viz_vs_auditory_l = (triggers[np.in1d(triggers, (1, 3))] == 3).astype(int)
# To make scikit-learn happy, we converted the bool array to integers
# in the same line. This results in an array of zeros and ones:
print("The unique classes' labels are: %s" % np.unique(viz_vs_auditory_l))
gat.fit(epochs[('AudL', 'VisL')], y=viz_vs_auditory_l)
# For our right events, which ones are visual?
viz_vs_auditory_r = (triggers[np.in1d(triggers, (2, 4))] == 4).astype(int)
gat.score(epochs[('AudR', 'VisR')], y=viz_vs_auditory_r)
gat.plot(
title="Generalization Across Time (visual vs auditory): left to right")
示例9: len
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
# reduce number or trials if too many XXX just for speed, remove
if len(sel) > 400:
import random
random.shuffle(sel)
sel = sel[0:400]
y = np.array(events[cond_name].tolist())
# Apply contrast
if clf_type['name']=='SVC':
decoding_parameters = decoding_params[0]['values']
elif clf_type['name']=='SVR':
decoding_parameters = decoding_params[1]['values']
gat = GeneralizationAcrossTime(**decoding_parameters)
gat.fit(epochs[sel], y=y[sel])
gat.score(epochs[sel], y=y[sel])
# Plot
fig = gat.plot_diagonal(show=False)
report.add_figs_to_section(fig,
('%s %s: (decoding)' % (subject, cond_name)), subject)
fig = gat.plot(show=False)
report.add_figs_to_section(fig,
('%s %s: GAT' % (subject, cond_name)), subject)
# Save contrast
pkl_fname = op.join(data_path, subject, 'mvpas',
'{}-decod_{}_{}{}.pickle'.format(subject, cond_name,clf_type['name'],fname_appendix))
# Save classifier results
示例10: make_pipeline
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
clf = make_pipeline(StandardScaler(), clf)
# initialize the GAT object
gat = GeneralizationAcrossTime(clf=clf, scorer=scorer_auc, n_jobs=-1,
cv=10)
# select the trials where a target is presented
for contrast in ['HL', 'EU', 'PR']:
epochs_ = concatenate_epochs((epochs[contrast[0]],
epochs[contrast[1]]))
y = np.hstack((np.zeros(len(epochs[contrast[0]])),
np.ones(len(epochs[contrast[1]]))))
gat.fit(epochs_, y=y)
fname = op.join(data_path, 's%i_%s_fit.pkl' % (subject, contrast))
with open(fname, 'wb') as f:
pickle.dump(gat, f)
# TODO: should save y_pred separately
# predict + score
scores = gat.score(epochs_, y=y)
fname = op.join(data_path,
's%i_%s_scores.npy' % (subject, contrast))
np.save(fname, np.array(scores))
all_scores[contrast].append(np.array(scores))
# plot
fig, axes = plt.subplots(2, 1, facecolor='w')
gat.plot_diagonal(show=False, ax=axes[0], chance=.5)
gat.plot(show=False, ax=axes[1], vmin=.25, vmax=.75)
report.add_figs_to_section(fig, str(subject), contrast)
report.save()
示例11: range
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
events = np.vstack((range(n_trial), np.zeros(n_trial, int), y.astype(int))).T
chan_names = ['MEG %i' % chan for chan in range(n_chan)]
chan_types = ['mag'] * n_chan
sfreq = 250
info = create_info(chan_names, sfreq, chan_types)
epochs = EpochsArray(data=X, info=info, events=events, verbose=False)
epochs.times = selected_times[:n_time]
# make classifier
clf = LogisticRegression(C=0.0001)
# fit model and score
gat = GeneralizationAcrossTime(
clf=clf, scorer="roc_auc", cv=cv, predict_method="predict")
gat.fit(epochs, y=y)
gat.score(epochs, y=y)
# Save model
joblib.dump(gat, data_path + "decode_time_gen/gat_ge.jl")
# make matrix plot and save it
fig = gat.plot(
cmap="viridis", title="Temporal Gen (Classic vs planning) for Global Eff.")
fig.savefig(data_path + "decode_time_gen/gat_matrix_ge.png")
fig = gat.plot_diagonal(
chance=0.5, title="Temporal Gen (Classic vs planning) for Global eff.")
fig.savefig(data_path + "decode_time_gen/gat_diagonal_ge.png")
# Manuel model
示例12: test_generalization_across_time
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
def test_generalization_across_time():
"""Test time generalization decoding
"""
from sklearn.svm import SVC
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
raw = io.Raw(raw_fname, preload=False)
events = read_events(event_name)
picks = pick_types(raw.info, meg='mag', stim=False, ecg=False,
eog=False, exclude='bads')
picks = picks[0:2]
decim = 30
# Test on time generalization within one condition
with warnings.catch_warnings(record=True):
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True, decim=decim)
# Test default running
gat = GeneralizationAcrossTime()
assert_equal("<GAT | no fit, no prediction, no score>", "%s" % gat)
assert_raises(ValueError, gat.fit, epochs, picks='foo')
with warnings.catch_warnings(record=True):
# check classic fit + check manual picks
gat.fit(epochs, picks=[0])
# check optional y as array
gat.fit(epochs, y=epochs.events[:, 2])
# check optional y as list
gat.fit(epochs, y=epochs.events[:, 2].tolist())
assert_equal(len(gat.picks_), len(gat.ch_names), 1)
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), no "
"prediction, no score>", '%s' % gat)
assert_equal(gat.ch_names, epochs.ch_names)
gat.predict(epochs)
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), "
"predicted 14 epochs, no score>",
"%s" % gat)
gat.score(epochs)
gat.score(epochs, y=epochs.events[:, 2])
gat.score(epochs, y=epochs.events[:, 2].tolist())
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), "
"predicted 14 epochs,\n scored "
"(accuracy_score)>", "%s" % gat)
with warnings.catch_warnings(record=True):
gat.fit(epochs, y=epochs.events[:, 2])
old_mode = gat.predict_mode
gat.predict_mode = 'super-foo-mode'
assert_raises(ValueError, gat.predict, epochs)
gat.predict_mode = old_mode
gat.score(epochs, y=epochs.events[:, 2])
assert_true("accuracy_score" in '%s' % gat.scorer_)
epochs2 = epochs.copy()
# check _DecodingTime class
assert_equal("<DecodingTime | start: -0.200 (s), stop: 0.499 (s), step: "
"0.047 (s), length: 0.047 (s), n_time_windows: 15>",
"%s" % gat.train_times)
assert_equal("<DecodingTime | start: -0.200 (s), stop: 0.499 (s), step: "
"0.047 (s), length: 0.047 (s), n_time_windows: 15 x 15>",
"%s" % gat.test_times_)
# the y-check
gat.predict_mode = 'mean-prediction'
epochs2.events[:, 2] += 10
gat_ = copy.deepcopy(gat)
assert_raises(ValueError, gat_.score, epochs2)
gat.predict_mode = 'cross-validation'
# Test basics
# --- number of trials
assert_true(gat.y_train_.shape[0] ==
gat.y_true_.shape[0] ==
len(gat.y_pred_[0][0]) == 14)
# --- number of folds
assert_true(np.shape(gat.estimators_)[1] == gat.cv)
# --- length training size
assert_true(len(gat.train_times['slices']) == 15 ==
np.shape(gat.estimators_)[0])
# --- length testing sizes
assert_true(len(gat.test_times_['slices']) == 15 ==
np.shape(gat.scores_)[0])
assert_true(len(gat.test_times_['slices'][0]) == 15 ==
np.shape(gat.scores_)[1])
# Test longer time window
gat = GeneralizationAcrossTime(train_times={'length': .100})
with warnings.catch_warnings(record=True):
gat2 = gat.fit(epochs)
assert_true(gat is gat2) # return self
assert_true(hasattr(gat2, 'cv_'))
assert_true(gat2.cv_ != gat.cv)
scores = gat.score(epochs)
assert_true(isinstance(scores, list)) # type check
assert_equal(len(scores[0]), len(scores)) # shape check
assert_equal(len(gat.test_times_['slices'][0][0]), 2)
# Decim training steps
gat = GeneralizationAcrossTime(train_times={'step': .100})
#.........这里部分代码省略.........
示例13: test_generalization_across_time
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
def test_generalization_across_time():
"""Test time generalization decoding
"""
from sklearn.svm import SVC
raw = io.Raw(raw_fname, preload=False)
events = read_events(event_name)
picks = pick_types(raw.info, meg='mag', stim=False, ecg=False,
eog=False, exclude='bads')
picks = picks[0:2]
decim = 30
# Test on time generalization within one condition
with warnings.catch_warnings(record=True):
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True, decim=decim)
# Test default running
gat = GeneralizationAcrossTime()
assert_equal("<GAT | no fit, no prediction, no score>", "%s" % gat)
with warnings.catch_warnings(record=True):
gat.fit(epochs)
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), no "
"prediction, no score>", '%s' % gat)
gat.predict(epochs)
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), "
"predict_type : 'predict' on 15 epochs, no score>",
"%s" % gat)
gat.score(epochs)
assert_equal("<GAT | fitted, start : -0.200 (s), stop : 0.499 (s), "
"predict_type : 'predict' on 15 epochs,\n scored "
"(accuracy_score)>", "%s" % gat)
with warnings.catch_warnings(record=True):
gat.fit(epochs, y=epochs.events[:, 2])
old_type = gat.predict_type
gat.predict_type = 'foo'
assert_raises(ValueError, gat.predict, epochs)
gat.predict_type = old_type
old_mode = gat.predict_mode
gat.predict_mode = 'super-foo-mode'
assert_raises(ValueError, gat.predict, epochs)
gat.predict_mode = old_mode
gat.score(epochs, y=epochs.events[:, 2])
assert_true("accuracy_score" in '%s' % gat.scorer_)
epochs2 = epochs.copy()
# check _DecodingTime class
assert_equal("<DecodingTime | start: -0.200 (s), stop: 0.499 (s), step: "
"0.047 (s), length: 0.047 (s), n_time_windows: 15>",
"%s" % gat.train_times)
assert_equal("<DecodingTime | start: -0.200 (s), stop: 0.499 (s), step: "
"0.047 (s), length: 0.047 (s), n_time_windows: 15 x 15>",
"%s" % gat.test_times_)
# the y-check
gat.predict_mode = 'mean-prediction'
epochs2.events[:, 2] += 10
assert_raises(ValueError, gat.score, epochs2)
gat.predict_mode = 'cross-validation'
# Test basics
# --- number of trials
assert_true(gat.y_train_.shape[0] ==
gat.y_true_.shape[0] ==
gat.y_pred_.shape[2] == 14)
# --- number of folds
assert_true(np.shape(gat.estimators_)[1] == gat.cv)
# --- length training size
assert_true(len(gat.train_times['slices']) == 15 ==
np.shape(gat.estimators_)[0])
# --- length testing sizes
assert_true(len(gat.test_times_['slices']) == 15 ==
np.shape(gat.scores_)[0])
assert_true(len(gat.test_times_['slices'][0]) == 15 ==
np.shape(gat.scores_)[1])
# Test longer time window
gat = GeneralizationAcrossTime(train_times={'length': .100})
with warnings.catch_warnings(record=True):
gat2 = gat.fit(epochs)
assert_true(gat is gat2) # return self
assert_true(hasattr(gat2, 'cv_'))
assert_true(gat2.cv_ != gat.cv)
scores = gat.score(epochs)
assert_true(isinstance(scores, list)) # type check
assert_equal(len(scores[0]), len(scores)) # shape check
assert_equal(len(gat.test_times_['slices'][0][0]), 2)
# Decim training steps
gat = GeneralizationAcrossTime(train_times={'step': .100})
with warnings.catch_warnings(record=True):
gat.fit(epochs)
gat.score(epochs)
assert_equal(len(gat.scores_), 8)
# Test start stop training
gat = GeneralizationAcrossTime(train_times={'start': 0.090,
#.........这里部分代码省略.........
示例14: make_pipeline
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
# Classifier
clf = make_pipeline(
StandardScaler(),
LogisticRegression(C=1, solver="lbfgs", multi_class="multinomial"))
# Setup the y vector and GAT
gat = GeneralizationAcrossTime(
predict_mode='mean-prediction', scorer="accuracy", n_jobs=1)
# Fit model
print("fitting GAT")
gat.fit(epochs_data, y=y)
# Scoring
print("Scoring GAT")
gat.score(epochs_data, y=y)
# Save model
joblib.dump(gat,
data_path + "decode_time_gen/%s_gat_all_grad_random.jl" % subject)
# make matrix plot and save it
fig = gat.plot(cmap="viridis", title="Temporal Gen for subject: %s" % subject)
fig.savefig(data_path + "decode_time_gen/%s_gat_matrix_all_grad_random.png" %
subject)
fig = gat.plot_diagonal(
chance=0.5, title="Temporal Gen for subject: %s" % subject)
fig.savefig(data_path + "decode_time_gen/%s_gat_diagonal_all_grad_random.png" %
subject)
示例15: len
# 需要导入模块: from mne.decoding import GeneralizationAcrossTime [as 别名]
# 或者: from mne.decoding.GeneralizationAcrossTime import score [as 别名]
# offset = [-1, 0, 1]
# decoding
epochs = epochs.decimate(decim)
n_te = len(epochs.times)
gat.predict_mode = 'mean-prediction' # generalization across conditions so no cross validation here.
# compute scores for each stimulus
rsvp_score_all = np.zeros((n_tr, n_te, n_stim))
rsvp_score_lag = np.zeros((n_tr, n_te, n_stim, n_lag))
rsvp_score_offset0_lag = np.zeros((n_tr, n_te, n_stim, n_lag))
rsvp_score_offset_1_lag = np.zeros((n_tr, n_te, n_stim, n_lag))
rsvp_score_offset1_lag = np.zeros((n_tr, n_te, n_stim, n_lag))
for istim in range(n_stim):
# compute scores across all trials
s = gat.score(epochs, stim_list_rsvp[:,istim]) # compute predictions as well.
s = np.array(s)
rsvp_score_all[:,:,istim] = s
# compute scores for lags
for ilag in range(len(ulag)):
sel = lag==ulag[ilag] # select one lag
s = gat.score(epochs[sel], stim_list_rsvp[sel,istim])
s = np.array(s)
rsvp_score_lag[:,:,istim,ilag] = s
if istim+1==ulag[ilag]: # if the stim is one of the lag, then scores according to report
# compute scores depending on accuracy
# one lag, correct T1, correct T2
# sel = [all(tup) for tup in zip(lag==ulag[ilag], R2[:,0]==ulag[ilag])]
sel = lag==ulag[ilag]