Exemplo n.º 1
0
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)
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
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
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
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
Exemplo n.º 6
0
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)
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
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')
Exemplo n.º 10
0
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')