Skip to content

Allow for refit=callable in *SearchCV to balance score and model complexity #11269

Closed

Description

@jnothman

GridSearchCV and RandomizedSearchCV currently allow for refit=my_scorer_name to select the model that maximises some chosen metric. But these scorers need to be calculated independent of other candidates' results.

To balance model complexity with cross-validated score, it is common to use an approach like choosing the model that is least complex (by some metric or ordering) but is within 1 standard deviation of the best score. (Variant approaches exist, and may relate to budget constraints etc.)

We could consider allowing a callable to be passed to refit:

"""
...
    refit : boolean, string, or callable, default=True
        Refit an estimator using the best found parameters on the whole
        dataset.

        For multiple metric evaluation, this can be a string denoting the
        scorer maximised to find the best parameters for refitting the estimator
        at the end.

        Where there are considerations other than maximum model performance in
        choosing a best estimator, ``refit`` can be set to a function which
        returns the selected ``best_index_`` given the ``cv_results_``.

...
"""

Does this interface sound reasonable, @janvanrijn, @betatim?

Activity

  1. janvanrijn commented on Jun 15, 2018

    @janvanrijn
    Contributor

    This would replace the following parts in the code?

            if self.refit or not self.multimetric_:
                self.best_index_ = results["rank_test_%s" % refit_metric].argmin()
                self.best_params_ = results["params"][self.best_index_]
                self.best_score_ = results["mean_test_%s" % refit_metric][
                    self.best_index_]
    

    What would be the parameters of this refit method? The results dictionary?

  2. jnothman commented on Jun 15, 2018

    @jnothman
    MemberAuthor

    Yes, it would be passed results and would be expected to return a value for best_index_. best_params_ and best_score_ would still be computed by BaseSearchCV

  3. janvanrijn commented on Jun 15, 2018

    @janvanrijn
    Contributor

    In my code projects I would probably still use inheritance (Java school) but this would facilitate this.

    Btw, how would you handle a string value? Some metrics need to be maximized, whereas others need to be minimized.

  4. jnothman commented on Jun 15, 2018

    @jnothman
    MemberAuthor

    Do you mean things like MSE need to be minimised? We have a convention that all our scorers return values to be maximised. See the docs for scoring.

  5. added
    Easy
    on Jun 16, 2018
  6. wenhaoz-fengcai commented on Jun 18, 2018

    @wenhaoz-fengcai

    @janvanrijn Hi, are you working on this enhancement or is it open to others?

  7. janvanrijn commented on Jun 18, 2018

    @janvanrijn
    Contributor

    I am not working on this, but I am happy to provide input / help / unit tests if that would be needed.

  8. wenhaoz-fengcai commented on Jun 18, 2018

    @wenhaoz-fengcai

    Thanks! I'm planning on working on this issue. Your inputs and help are greatly appreciated

  9. jnothman commented on Jun 18, 2018

    @jnothman
    MemberAuthor
  10. wenhaoz-fengcai commented on Jun 18, 2018

    @wenhaoz-fengcai

    @jnothman Thanks for the response! My idea is to add another condition after this line to prevent it raise valueError when self.refit is a callable func.

    Meanwhile, replace this line with something like

        if callable(self.refit):
            self.best_index = self.refit(results)
        else
           self.best_index_ = results["rank_test_%s" % refit_metric].argmin()
    

    Please correct me if I'm wrong.

  11. jnothman commented on Jun 19, 2018

    @jnothman
    MemberAuthor
  12. wenhaoz-fengcai commented on Jun 20, 2018

    @wenhaoz-fengcai

    @janvanrijn @jnothman
    Here is a test case for callable self.refit

     def test_refit_callable():
         """
          Test refit=callable, which adds flexibility in identifying the "best" estimator
     	 """
         def score(cv_results):
             """
             Dummy custmized score function for testing refit=callable.
             Returns the first element in 'foo_param' candidates
             """
             return cv_results["param_foo_param"].data[0]
     
         X = np.arange(4).reshape(2,2)
         y = np.array([0,1])
     
         clf = GridSearchCV(MockClassifier(), {'foo_param':[1,2,3]}, refit=score)
         clf.fit(X,y)
     
         assert.equal(clf.best_index_, 1)

    Is this something we want?

  13. jnothman commented on Jun 20, 2018

    @jnothman
    MemberAuthor
  14. wenhaoz-fengcai commented on Jun 23, 2018

    @wenhaoz-fengcai

    @jnothman Hi, I went through the examples directory and couldn't find an example of getting the sparsest model with 1 sd of the best. The only example I found could be relative is in "examples/model_selection/plot_roc_crossval.py".

  15. wenhaoz-fengcai commented on Jun 23, 2018

    @wenhaoz-fengcai

    One more thing, if we use multi-metric scoring, the parameter refit will be set to a scorer key to refit an estimator with the best parameter setting. If refit is passed a callable, how this callable going to tell which scorer to use? Check this related code here

  16. jnothman commented on Jun 23, 2018

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

    EasyEnhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions