Skip to content

ENH: encoding models #2796

Closed
Closed

Description

@choldgraf

Most of what I've been working on for my thesis has been so-called "encoding" models of electrode activity. This is quite similar to the decoding models already implemented in MNE, but where the output is the electrode activity, and inputs are time-lagged stimulus features. Is this something that would be useful to have in MNE?

I don't think it'll need to be as complicated as the decoding module because there isn't generalization across time etc, but I'm thinking of having a similar structure where you supply an epochs-like object and a tmin/tmax to pull specific times.

The output would be a list of regression models and the user could pull coefficients from these are necessary. It would rely heavily on scikit-learn throughout.

Let me know if this might be of interest and I can think up how it'd look in more detail if so.

Activity

  1. dengemann commented on Jan 19, 2016

    @dengemann
    Member

    This would then be a more contextual API for some of our regression models. Estimation of multivariate timecourses based on external events. Sounds good to me. Would be good to think of the APIs for that.

    On 19 Jan 2016, at 19:15, Chris Holdgraf [email protected] wrote:

    Most of what I've been working on for my thesis has been so-called "encoding" models of electrode activity. This is quite similar to the decoding models already implemented in MNE, but where the output is the electrode activity, and inputs are time-lagged stimulus features. Is this something that would be useful to have in MNE?

    I don't think it'll need to be as complicated as the decoding module because there isn't generalization across time etc, but I'm thinking of having a similar structure where you supply an epochs-like object and a tmin/tmax to pull specific times.

    The output would be a list of regression models and the user could pull coefficients from these are necessary. It would rely heavily on scikit-learn throughout.

    Let me know if this might be of interest and I can think up how it'd look in more detail if so.

    —
    Reply to this email directly or view it on GitHub.

  2. jona-sassenhagen commented on Jan 19, 2016

    @jona-sassenhagen
    Contributor

    What would you say is missing from stats.regression.linear_regression and stats.regression.linear_regression_raw?

  3. jasmainak commented on Jan 19, 2016

    @jasmainak
    Member

    Do we have data on which we could demo these models?

  4. jona-sassenhagen commented on Jan 19, 2016

    @jona-sassenhagen
    Contributor

    I rrrrrreally need to make available a dataset to demonstrate continuous covariates with rERPs ...

  5. choldgraf commented on Jan 19, 2016

    @choldgraf
    ContributorAuthor

    @jona-sassenhagen other than my knowledge of their existence, I am not sure ;) I'll take a look now

  6. larsoner commented on Jan 19, 2016

    @larsoner
    Member

    You mean like a STRF? That would indeed be great. It would be nice if we had that as a way to look at data.

    @rkmaddox I assume this would be relevant to you...?

  7. choldgraf commented on Jan 19, 2016

    @choldgraf
    ContributorAuthor

    It looks like the linear_regression code is a more general OLS function, is that correct?

    In this case, it'd be using Ridge Regression most likely (maybe offer support for L1 norm or Elastic Net, though that takes a lot longer to fit), and would incorporate cross-validation internally as well. This can be kind of tricky to do correctly, as most people would be inputting a timeseries which you can't just chunk up randomly. The way I imagine it, people would input epochs-shaped objects, and the cross validation iterator would default to doing a LabelShuffleSplit or LeavePLabelOut iteration, so that datapoints from a single epoch would always stay together in either the train or test splits.

    Other stuff that would build on the linear_regression functions would be a function for creating time-lagged matrices. I was also thinking of incorporating specific viz for doing spatio / spectro-temporal receptive fields since it's a bit thing in systems neuro, but that may be too specific.

  8. choldgraf commented on Jan 19, 2016

    @choldgraf
    ContributorAuthor

    yep @Eric89GXL, my life in grad school has been STRFs :)

  9. jona-sassenhagen commented on Jan 19, 2016

    @jona-sassenhagen
    Contributor

    #2641 is very similar to STRFs. I think it's a more general model.

    Also it's bad (because I coded it).

    Other stuff that would build on the linear_regression functions would be a function for creating time-lagged matrices.

    stats.linear_regression_raw

    n this case, it'd be using Ridge Regression most likely

    stats.linear_regression_raw can take a custom solver.

  10. larsoner commented on Jan 19, 2016

    @larsoner
    Member

    yep @Eric89GXL, my life in grad school has been STRFs :)

    Mine was too :)

    #2641 is very similar to STRFs. I think it's a more general model.

    Cool. @choldgraf want to close this and comment over there? (Can reopen here if somehow that isn't sufficient for what you're looking to do.)

  11. choldgraf commented on Jan 19, 2016

    @choldgraf
    ContributorAuthor

    yep, I'll take a look at #2641

  12. jona-sassenhagen commented on Jan 19, 2016

    @jona-sassenhagen
    Contributor

    First check if I'm correct. My grad school life was looking at object-before-subject sentences, I know very little about STRFs.

  13. rkmaddox commented on Jan 19, 2016

    @rkmaddox
    Contributor

    I've implemented a similar thing, although it is specifically coded for a continuous input and continuous output: https://github.com/rkmaddox/trf. It does ridge regression, or you can have a smoothness prior. It is pretty inflexible, but is also extremely fast due to optimization and the potential to run with cuda.

    I'd be happy for it to become a part of mne-python, but there are a number of interface issues that would need to be worked out first, particularly because there is a tradeoff between interface complexity and speed for some scenarios.

  14. choldgraf commented on Jan 19, 2016

    @choldgraf
    ContributorAuthor

    Just put some comments in PR #2641. The tl;dr is that it seems to me that the code is specifically for fitting a single linear model, and in the same way the "generalization across time" module is useful because it gives the machinery to automate the model fitting / predicting process, an explicit set of STRF or encoding code could be similarly useful. AKA, the stuff in stats.linear_regression as well as @rkmaddox is great for the fitting itself, but doesn't really address the general PITA that is doing your cross validation, feature making, model scaling, etc correctly. WDYT everybody?

  15. 61 remaining items

  16. kingjr commented on Jun 2, 2016

    @kingjr
    Member

    I'm +1 on making linear_regression_raw compatible with sklearn pipeline and modular, but I think it all comes down to creating a FeatureExtraction class/function that we can pipe to a sklearn pipeline. This is the main challenge since it doesnt fit sklearn design.

    I think something like:

    for X, Y in chunker.fit_transform(X_continuous, Y_continuous):
        clf.partial_fit(X, Y)
    

    should do the job.

    Then we can exploit clf.coef_ to make patterns, evoked or whatever.

  17. choldgraf commented on Jun 2, 2016

    @choldgraf
    ContributorAuthor

    @Eric89GXL I think that makes sense - I threw my encoding model stuff into a separate module to make it easier to figure out the scope of what it's trying to do:

    https://github.com/choldgraf/pySTRF

    I'd be fine with reorganizing the code that's in there and merging some of it into MNE if that makes sense.

  18. jona-sassenhagen commented on Jun 2, 2016

    @jona-sassenhagen
    Contributor

    Here's an outline of how you can currently fit and score an encoder model with the functions in mne.stats.regression:

    (having defined raw, events, event_id, covariates ...)

    from mne.stats.regression import _clean_rerp_input, _get_fast_dot, _prepare_rerp_preds, _prepare_rerp_data, _make_evokeds
    from sklearn.cross_validation import KFold as cv
    from sklearn.linear_model import Ridge
    
    clf = Ridge(solver='cholesky', fit_intercept=False)
    
    data, info, events = _prepare_rerp_data(raw.copy(), events)
    
    X = _prepare_rerp_preds(
        n_samples=data.shape[1], sfreq=info["sfreq"], events=events,
        event_id=event_id, covariates=covariates)[0]  # the other outputs are for retrieving the coefs as an evoked object
    
    folds = cv(n=data.shape[1], n_folds=5, shuffle=True)
    
    # fit
    clfs = list()
    for fold, (train, test) in enumerate(self.folds):
        clfs.append(deepcopy(clf).fit(X[train].copy(), data[:, train].copy().T))
        clfs[fold].coef_ = np.asarray(clfs[fold].coef_)
    
    # and predict
    predictions = list()
    for clf, (train, test) in zip(clfs, folds):
        predictions.append(clf.predict(X[test, :]).T)
    

    Roughly like this.

    This is from my own sklearn-like encoder model that's a lot less clean than Chris' implementation

  19. choldgraf commented on Jun 9, 2016

    @choldgraf
    ContributorAuthor

    hey all - back from being out of contact for a few days. What if as a start I opened a PR that tried to basically do these things:

    1. reorganize the data prep code so that it allowed for continuous data as well as events.
    2. Included an RegressionModel class that would be some hybrid of @jona-sassenhagen's gist and my EncodingModel class. This wouldn't do any CV. It'd basically just do fitting + predicting + keep track of which coefficients were categorical vs. continuous.

    And in the future, we could think about implementing a more extensive EncodingModel class that would use RegressionModel under the hood along with some kind of cross-validation + scoring. Hopefully that could be extended a bit more with better feature extraction functionality, partial fitting, etc.

  20. jona-sassenhagen commented on Jun 9, 2016

    @jona-sassenhagen
    Contributor

    Seems sensible to me.

  21. jona-sassenhagen commented on Jun 9, 2016

    @jona-sassenhagen
    Contributor

    Btw Chris since the internals are all private, if you think the API is limited, it can probably easily be changed.

  22. choldgraf commented on Jun 9, 2016

    @choldgraf
    ContributorAuthor

    ok, well I will try opening a PR in the near future and we can discuss API
    changes and such there. Sounds ok?

    On Thu, Jun 9, 2016 at 3:20 AM, jona-sassenhagen [email protected]
    wrote:

    Btw Chris since the internals are all private, if you think the API is
    limited, it can probably easily be changed.

    —
    You are receiving this because you were mentioned.
    Reply to this email directly, view it on GitHub
    #2796 (comment),
    or mute the thread
    https://github.com/notifications/unsubscribe/ABwSHQBikEL7wJdwZU4yDXa44bweCJDjks5qJ-j2gaJpZM4HH9DX
    .

  23. choldgraf commented on Jun 15, 2016

    @choldgraf
    ContributorAuthor

    I'm starting to think about how to do this properly. One snag that I've found is coming up with a good test-case for encoding models w/ a continuous variable.

    Think it's enough to just write a "simulate continuous data" function, that lets you input two continuously-varying signals, A and B (e.g. white noise + a sine wave) along with a set of delays, and a set of weights that you wish to correspond to each delay, and then outputs another continuous signal where signal A is now modulated by the amplitude of signal B?

    Then we could use that to make sure that the proper weights are reconstructed doing fitting etc. And also for examples...

  24. larsoner commented on Oct 13, 2016

    @larsoner
    Member

    I got some very efficient code from @rkmaddox for doing continuous regression that I am converting. It effectively provides a nice little test case (ideal in light color, fitted in dashed lines):

    figure_1

    This code has the advantage of being very efficient for its particular use case, but it will not handle event-based regression, has no cross-validation, etc. I need to extend it to deal with e.g. time-frequency data, too, but that shouldn't be too bad. Not sure how this would fit best with the other suggested approaches. This seems a bit complex :(

    Maybe we need a separate hangout session to work it out so that we don't overload GitHub. Maybe a Gitter room would work to hash it out?

  25. agramfort commented on Oct 13, 2016

    @agramfort
    SponsorMember
  26. kingjr commented on Oct 13, 2016

    @kingjr
    Member

    Let s do a session on that while you're in nyc

    Le 13 oct. 2016 13:57, "Alexandre Gramfort" [email protected] a
    écrit :

    isn't continuous regression a more general case. Discrete would be using
    this code with delta functions? am I missing something?

    —
    You are receiving this because you were mentioned.
    Reply to this email directly, view it on GitHub
    #2796 (comment),
    or mute the thread
    https://github.com/notifications/unsubscribe-auth/AEp7DGM4JHhoMNWr79kjiAAWjJmkmexAks5qznEHgaJpZM4HH9DX
    .

  27. rkmaddox commented on Oct 13, 2016

    @rkmaddox
    Contributor

    @agramfort Yeah, I believe they're equivalent mathematically. Though if the sampling rate >> event rate it could get pretty inefficient.

  28. rkmaddox commented on Oct 13, 2016

    @rkmaddox
    Contributor

    Although, actually, I have used it for doing auditory brainstem responses. EEG at 10 kHz, Poisson pulses at 40 Hz, and it is still faster because of the length of the window I'm deriving. So I think if (# events) * (time / event) < (recording time), there should be savings (and that is not taking into account FFT and CUDA gains).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions