mne.decoding.TimeDecoding

class mne.decoding.TimeDecoding(picks=None, cv=5, clf=None, times=None, predict_method='predict', predict_mode='cross-validation', scorer=None, score_mode='mean-fold-wise', n_jobs=1)

Train and test a series of classifiers at each time point to obtain a score across time.

Parameters:

picks : array-like of int | None

The channels indices to include. If None the data channels in info, except bad channels, are used.

cv : int | object

If an integer is passed, it is the number of folds. Specific cross-validation objects can be passed, see scikit-learn.cross_validation module for the list of possible objects. If clf is a classifier, defaults to StratifiedKFold(n_folds=5), else defaults to KFold(n_folds=5).

clf : object | None

An estimator compliant with the scikit-learn API (fit & predict). If None the classifier will be a standard pipeline including StandardScaler and a Logistic Regression with default parameters.

times : dict | None

A dictionary to configure the training times:

slices
: ndarray, shape (n_clfs,)

Array of time slices (in indices) used for each classifier. If not given, computed from ‘start’, ‘stop’, ‘length’, ‘step’.

start
: float

Time at which to start decoding (in seconds). By default, min(epochs.times).

stop
: float

Maximal time at which to stop decoding (in seconds). By default, max(times).

step
: float

Duration separating the start of subsequent classifiers (in seconds). By default, equals one time sample.

length
: float

Duration of each classifier (in seconds). By default, equals one time sample.

If None, empty dict.

predict_method : str

Name of the method used to make predictions from the estimator. For example, both predict_proba and predict are supported for sklearn.linear_model.LogisticRegression. Note that the scorer must be adapted to the prediction outputs of the method. Defaults to ‘predict’.

predict_mode : {‘cross-validation’, ‘mean-prediction’}

Indicates how predictions are achieved with regards to the cross- validation procedure:

  • cross-validation
    : estimates a single prediction per sample

    based on the unique independent classifier fitted in the cross-validation.

  • mean-prediction
    : estimates k predictions per sample, based

    on each of the k-fold cross-validation classifiers, and average these predictions into a single estimate per sample.

Defaults to ‘cross-validation’.

scorer : object | None | str

scikit-learn Scorer instance or str type indicating the name of the scorer such as accuracy, roc_auc. If None, set to accuracy.

score_mode : {‘fold-wise’, ‘mean-fold-wise’, ‘mean-sample-wise’}

Determines how the scorer is estimated:

  • fold-wise : returns the score obtained in each fold.

  • mean-fold-wise : returns the average of the fold-wise scores.

  • mean-sample-wise
    : returns score estimated across across all

    y_pred independently of the cross-validation. This method is faster than mean-fold-wise but less conventional, use at your own risk.

Defaults to ‘mean-fold-wise’.

n_jobs : int

Number of jobs to run in parallel. Defaults to 1.

Notes

The function is equivalent to the diagonal of GeneralizationAcrossTime()

New in version 0.10.

Attributes

picks_ (array-like of int | None) The channels indices to include.
ch_names (list, array-like, shape (n_channels,)) Names of the channels used for training.
y_train_ (ndarray, shape (n_samples,)) The categories used for training.
times_ (dict) A dictionary that configures the training times: * slices : ndarray, shape (n_clfs,) Array of time slices (in indices) used for each classifier. If not given, computed from ‘start’, ‘stop’, ‘length’, ‘step’. * times : ndarray, shape (n_clfs,) The training times (in seconds).
cv_ (CrossValidation object) The actual CrossValidation input depending on y.
estimators_ (list of list of scikit-learn.base.BaseEstimator subclasses.) The estimators for each time point and each fold.
y_pred_ (ndarray, shape (n_times, n_epochs, n_prediction_dims)) Class labels for samples in X.
y_true_ (list | ndarray, shape (n_samples,)) The categories used for scoring y_pred_.
scorer_ (object) scikit-learn Scorer instance.
scores_ (list of float, shape (n_times,)) The scores (mean accuracy of self.predict(X) wrt. y.).

Methods

__hash__() <==> hash(x)
fit(epochs[, y]) Train a classifier on each specified time slice.
plot([title, xmin, xmax, ymin, ymax, ax, ...]) Plotting function
predict(epochs) Test each classifier on each specified testing time slice.
score([epochs, y]) Score Epochs
__hash__() <==> hash(x)
fit(epochs, y=None)

Train a classifier on each specified time slice.

Note

This function sets the picks_, ch_names, cv_, y_train, train_times_ and estimators_ attributes.

Parameters:

epochs : instance of Epochs

The epochs.

y : list or ndarray of int, shape (n_samples,) or None, optional

To-be-fitted model values. If None, y = epochs.events[:, 2].

Returns:

self : TimeDecoding

Returns fitted TimeDecoding object.

Notes

If X and y are not C-ordered and contiguous arrays of np.float64 and X is not a scipy.sparse.csr_matrix, X and/or y may be copied.

If X is a dense array, then the other methods will not support sparse matrices as input.

plot(title=None, xmin=None, xmax=None, ymin=None, ymax=None, ax=None, show=True, color=None, xlabel=True, ylabel=True, legend=True, chance=True, label='Classif. score')

Plotting function

Predict each classifier. If multiple classifiers are passed, average prediction across all classifiers to result in a single prediction per classifier.

Parameters:

title : str | None

Figure title.

xmin : float | None, optional,

Min time value.

xmax : float | None, optional,

Max time value.

ymin : float

Min score value. Defaults to 0.

ymax : float

Max score value. Defaults to 1.

ax : object | None

Instance of mataplotlib.axes.Axis. If None, generate new figure.

show : bool

If True, the figure will be shown. Defaults to True.

color : str

Score line color. Defaults to ‘steelblue’.

xlabel : bool

If True, the xlabel is displayed. Defaults to True.

ylabel : bool

If True, the ylabel is displayed. Defaults to True.

legend : bool

If True, a legend is displayed. Defaults to True.

chance : bool | float. Defaults to None

Plot chance level. If True, chance level is estimated from the type of scorer.

label : str

Score label used in the legend. Defaults to ‘Classif. score’.

Returns:

fig : instance of matplotlib.figure.Figure

The figure.

predict(epochs)

Test each classifier on each specified testing time slice.

Note

This function sets the y_pred_ and test_times_ attributes.

Parameters:

epochs : instance of Epochs

The epochs. Can be similar to fitted epochs or not. See predict_mode parameter.

Returns:

y_pred : list of lists of arrays of floats, shape (n_times, n_epochs, n_prediction_dims)

The single-trial predictions at each time sample.

score(epochs=None, y=None)

Score Epochs

Estimate scores across trials by comparing the prediction estimated for each trial to its true value.

Calls predict() if it has not been already.

Note

The function updates the scorer_, scores_, and y_true_ attributes.

Note

If predict_mode is ‘mean-prediction’, score_mode is automatically set to ‘mean-sample-wise’.

Parameters:

epochs : instance of Epochs | None, optional

The epochs. Can be similar to fitted epochs or not. If None, it needs to rely on the predictions y_pred_ generated with predict().

y : list | ndarray, shape (n_epochs,) | None, optional

True values to be compared with the predictions y_pred_ generated with predict() via scorer_. If None and predict_mode``=='cross-validation' y = ``y_train_.

Returns:

scores : list of float, shape (n_times,)

The scores estimated by scorer_ at each time sample (e.g. mean accuracy of predict(X)).