Skip to content

Customizing BaseSearchCV is hard #9499

Closed

Description

@amueller

There are several projects working on smarter ways to search parameters.
Right now, BaseSearchCV makes it really hard to customize parts, mostly because the fit function is really long, and changing anything in the parameter loop means copying the whole fit method, see here.

Maybe factoring this out into a method, or just splitting up fit a bit more might be a good idea?

Activity

  1. jnothman commented on Aug 5, 2017

    @jnothman
    Member

    I think (without looking in detail) that the SMAC implementation could have reused BaseSearchCV/RandomizedSearchCV more, albeit with a little overhead in each run.

    I would be +1 for something like:

    def search_cv(estimator, candidates, X, y, ...):
        ...
        return cv_results_
    

    WDYT?

  2. amueller commented on Aug 9, 2017

    @amueller
    MemberAuthor

    yeah, that would be good, I think. I don't think SMAC could have reused more. How?

  3. jnothman commented on Aug 9, 2017

    @jnothman
    Member
  4. amueller commented on Aug 11, 2017

    @amueller
    MemberAuthor

    Maybe. You'd have to consolidate all the dictionaries you get at the end. I guess that would be simpler than copying all the code.

    Hm it depends a bit what candidates is in your example. I don't think that's actually needed, since we already have _get_param_iterator, and any optimization would create these on the fly?

  5. betatim commented on Aug 13, 2017

    @betatim
    Member

    From my point of view the tricky bit is passing feedback from _fit_and_score to the iterator from _get_param_iterator. So I would suggest splitting things somewhere around here and replace the first part in scikit-optimize.

  6. jnothman commented on Aug 13, 2017

    @jnothman
    Member

    There's also a subtle trickiness in ensuring the CV splits are the same across calls and the fact that we could reuse the parallel backend.

    So we basically want a coroutine. Either:

    def candidates_generator():
        new_cv_results = yield candidates
        # ... determine new candidates to try or give up

    and the search does something like:

    for candidates in gen:
        .... _fit_and_score(..., candidates, ...)
        gen.send(cv_results)

    or inverted:

    def search_cv_generator(estimator, candidates, X, y, ...):
        while candidates:
            ...
            candidates = yield cv_results

    which may make more sense.

  7. jnothman commented on Aug 13, 2017

    @jnothman
    Member

    Perhaps the latter case more refined is:

    def search_cv_coroutine(estimator, X, y, ...):
        candidates = yield
        while candidates:
            ...
            candidates = yield cv_results

    In the latter case, your skopt code might be:

    def fit(...):
        search = search_cv_coroutine(*args, **kwargs)
        results = search.send(candidates)
        all_results = results
        while results are not good enough:
            candidates = ...
            results = search.send(candidates)
            for k in all_results:
                all_results[k] = np.concatenate([all_results[k], results[k]])
        ... store results ...
  8. amueller commented on Aug 13, 2017

    @amueller
    MemberAuthor

    @betatim yeah that's about where I thought. Though I wouldn't split the fit method, I would just encapsulate the call that generates the candidates and gets the results.

    I agree that co-routine is probably the best pattern for this. Do you know how that would work with the Parallel interface, though?

    I would still not have skopt overwrite fit, because most of the fit is parameter validation and result parsing, and these are exactly the parts they don't want to copy.

  9. jnothman commented on Aug 13, 2017

    @jnothman
    Member
  10. jnothman commented on Aug 14, 2017

    @jnothman
    Member

    Btw, @betatim, the problem with passing results back from _fit_and_score is that I don't want to make any promises about its interface. I would rather return a list of dicts even if it takes some overhead to transform it. I'm still not sure what the right format for returning things here is.

    We can also achieve a similar effect to a coroutine with a class having an evaluate method (rather than the awkward send). It makes it slightly messier to use a parallel context manager, but perhaps produces a cleaner interface overall.

  11. betatim commented on Aug 21, 2017

    @betatim
    Member

    Thinking out loud here: there are a lot of things already in RandomSearch that I'd prefer not to have to write myself: argument validation (first part of fit), the contents of _fit_and_score and the aggregation of results (second part of fit).

    "All" I want to do is be given results so far and asked for a new set of parameters to try. How can we make it so that these lines become customisable while keeping everything else fixed? I like the idea of sending stuff into a generator. How would it work interface wise for that generator to return more than one new point per iteration (for parallelism)? My guess: you always send in all past results and the generator returns a list of next points per iteration. Does mean the generator has to know something about how "parallel" you want to be running.

    With a setup like this all skopt would have to do is provide BaseSearchCV with a custom generator as argument to __init__ right?

  12. jnothman commented on Aug 22, 2017

    @jnothman
    Member

    I was a bit uncertain about your statement, so I just mocked up one possible solution at #9599.

  13. jerryfuyu0104 commented on Mar 8, 2018

    @jerryfuyu0104

    could _fit_and_score return estimator with ret? then in BaseSearchCV().fit(), we can get all trained estimators, and can get top 5 or top 10 best estimators, other than using refit=True to retrain the best estimator and get the best_estimator_

  14. jnothman commented on Mar 8, 2018

    @jnothman
    Member
  15. jerryfuyu0104 commented on Mar 8, 2018

    @jerryfuyu0104

    @jnothman i think each estimator was assigned to hyper-parameter other than fold, every parameter can get an estimator which was trained in the func _fit_and_score, so we can get or pickle it(and how to pickle these estimator? i cannot find examples), and not need to fit the best estimator again by set refit=True

  16. 16 remaining items

  17. janvanrijn commented on Jun 15, 2018

    @janvanrijn
    Contributor

    Should _generate_candidates be a function of fit arguments (X, y, ...)?​

    you mean that it would get X and y as parameters? I don't see the immediate advantage.

    There is one more related thing that is not immediately supported, which is the manipulating (subsampling) of the X and y by the search coroutine. (Is this what you meant?) If this would somehow be possible that would be great, but I suppose there are also other ways of achieving this within the search routine (e.g., wrapping the estimator).

  18. jnothman commented on Jun 15, 2018

    @jnothman
    Member

    No, I didn't mean for that purpose... we assume constant CV indices through all experiments.

    I meant perhaps so that the search could select good initial candidates given the data.

  19. janvanrijn commented on Jun 15, 2018

    @janvanrijn
    Contributor

    Ah, of course. That would make perfect sense indeed.

  20. stsievert commented on Jun 15, 2018

    @stsievert
    Contributor

    #9599 implements the functionality I'd like to see: there is some function call after each evaluation, which means it works for adaptive selection schemes (e.g., Bayesian approaches and Hyperband). I've added a review, and will be watching. This would enable the adaptive implementations discussed in dask/dask-ml#161.

    I'll try to make #11266 work with #9599.

    changing anything in the parameter loop means copying the whole fit method

    That's been my experience too.

  21. jnothman commented on Jun 16, 2018

    @jnothman
    Member

    Please explain your use case for overriding _format_results, @janvanrijn? If it's adding a measure that can be estimated independently for each fit, could you do it with a custom scorer?

  22. janvanrijn commented on Jul 2, 2018

    @janvanrijn
    Contributor

    Please explain your use case for overriding _format_results, @janvanrijn? If it's adding a measure that can be estimated independently for each fit, could you do it with a custom scorer?

    Sorry for the slow reply!

    For a hyperband or successive halving implementation, it wouldn't be a bad idea to add meta-data to the cv_results_ field, that indicate stuff such as

    • the subsample size (indicating which stage of successive halving we are)
    • the bracket number (indicating which stage of hyperband we are)
    • the hyperband iteration number (since the algorithm can be repeated multiple times)

    This can be used by the callable refit function as implemented in #11354, to determine which hyperparameter setting should be chosen (the original algorithm claims that only hyperparameters as ran on the maximum subsample size can be recommended)

  23. jnothman commented on Jul 3, 2018

    @jnothman
    Member

    I'd rather implementers not play with _format_results, but we should have some contact about how the custom search function is allowed to modify the results. Hmmm.

  24. janvanrijn commented on Jul 3, 2018

    @janvanrijn
    Contributor

    I'd rather implementers not play with _format_results, but we should have some contact about how the custom search function is allowed to modify the results. Hmmm.

    I'll be at SciPy next week.

    Currently, I do not completely get the whole idea behind results_container (line 682). Some questions that I wasn't able to answer:

    1. why is it a list of dict (we seem only interested in element 0)
    2. line 732: why results = results_container[0] if we can also grab the result from the return of _run_search
    3. if point 2 were the case, the evaluate_candidates fn could be wrapped and the results could be enhanced by search implementations (I think .. )

    Please help improve the documentation in my branch.

    Still interested in this? How should I add stuff? Mention it here or PR to your fork?

  25. jnothman commented on Jul 3, 2018

    @jnothman
    Member
  26. added this to the 0.20 milestone on Jul 21, 2018
  27. NicolasHug commented on Oct 3, 2019

    @NicolasHug
    Member

    @jnothman , what was the motivation for passing evaluate_candidates() to _run_search versus e.g. just making it a private method?

  28. jnothman commented on Oct 4, 2019

    @jnothman
    Member

    @jnothman , what was the motivation for passing evaluate_candidates() to _run_search versus e.g. just making it a private method?

    If a method, how would evaluate_candidates be provided the other variables it needs to do its job? evaluate_candidates is a closure over several other variables available in _fit. If it were a method, then those variables would need to be stored on the object. This is a cleaner functional abstraction (but maybe it's more functional paradigmatically than a lot of code in scikit-learn)

  29. wangyexiang commented on Nov 12, 2019

    @wangyexiang

    Dear sir, how to use GridSearchCV or RandomizedSearchCV in a huge dataset? I want to load the data in batch from disk with a generator to avoid MemoryError, then I can feed the batch data to fit method.
    Maybe like this:

    model = RandomizedSearchCV()
    model.fit(batch_data) #where batch_data is a generator`
    

    replace:

    model = RandomizedSearchCV()
    model.fit(x, y)
    

    As you can see, we can feed a generator into tensorflow model's fit method and this is pretty useful to huge dataset, like a images dataset.
    Thank you very much.
    @jnothman

  30. jnothman commented on Nov 12, 2019

    @jnothman
    Member
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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions