Skip to content

GridSearchCV & RandomizedSearchCV has a ranking issue when test scores are same. #21895

Open
trinhcon/scikit-learn
#9

Description

@AChand20

Describe the bug

During best parameter candidate search when two parameter candidates have the same mean_test_<scorer_name> then the rank_test_<scorer_name> ranks them the same, and if both have rank 1 then the algorithm picks the one that come first.

Steps/Code to Reproduce

from sklearn import svm, datasets
import pandas as pd
import numpy as np
from sklearn.model_selection import GridSearchCV
iris = datasets.load_iris()
def grid_search(parameters):
    svc = svm.SVC()
    clf = GridSearchCV(svc, parameters,return_train_score=True)
    clf.fit(iris.data, iris.target)
    print(pd.DataFrame(clf.cv_results_)[['param_C','param_kernel','mean_test_score','rank_test_score','mean_train_score']])
    print('best_parameters = ',clf.best_params_,'\n')

params = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
grid_search(params)
params = {'kernel':('rbf', 'linear'), 'C':[10, 1]}
grid_search(params)

Expected Results

Both function calls should return the same output for clf.best_params_
i.e best_parameters = {'C': 1, 'kernel': 'linear'} because the difference between the mean_train_score and the mean_test_score is the least for this parameter candidate.

Actual Results

scikit-learn_bug

Versions


System:
    python: 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)]
executable: C:\Anaconda3\anaconda3\envs\sklearndev\python.exe
   machine: Windows-10-10.0.19043-SP0

Python dependencies:
          pip: 21.2.4
   setuptools: 58.0.4
      sklearn: 1.1.dev0
        numpy: 1.21.2
        scipy: 1.7.1
       Cython: 0.29.24
       pandas: 1.3.4
   matplotlib: 3.5.0
       joblib: 1.1.0
threadpoolctl: 3.0.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: mkl
         prefix: mkl_rt
       filepath: C:\Anaconda3\anaconda3\envs\sklearndev\Library\bin\mkl_rt.1.dll
        version: 2021.4-Product
threading_layer: intel
    num_threads: 2

user_api: openmp
   internal_api: openmp
         prefix: vcomp
       filepath: C:\Windows\System32\vcomp140.dll
        version: None
    num_threads: 4

Activity

  1. AChand20 commented on Dec 6, 2021

    @AChand20
    Author

    I would like to work on this issue if the bug gets confirmed.

  2. Nivi09 commented on Dec 7, 2021

    @Nivi09

    Hello, I would like to work on this issue.

  3. thomasjpfan commented on Dec 7, 2021

    @thomasjpfan
    Member

    The issue with using train_score is that it does not describe the generalized performance of the configuration. Also it is only available if return_train_score=True. If we do want to rank parameters with the same mean test performance, then I think using the fit time would be better. In this case, when configurations have the same mean_test_score, then the configuration that fitted quicker will be ranked higher.

    Any change to the ranking will break backward compatibility. It would be best to get opinions from other maintainers before getting started.

  4. AChand20 commented on Dec 8, 2021

    @AChand20
    Author

    The issue with using train_score is that it does not describe the generalized performance of the configuration. Also it is only available if return_train_score=True. If we do want to rank parameters with the same mean test performance, then I think using the fit time would be better. In this case, when configurations have the same mean_test_score, then the configuration that fitted quicker will be ranked higher.

    Any change to the ranking will break backward compatibility. It would be best to get opinions from other maintainers before getting started.

    But fit time is not a consistent variable. It will change the rank every time we run the code (Tested this on the example code above).
    How about we don't change the ranking, instead we return all configurations that have the same mean_test_score and are ranked 1.

    So now in my particular example above clf.best_params_ will return both parameter candidates and the end user will try both and choose the one that performs best for his test data.

  5. Nivi09 commented on Dec 8, 2021

    @Nivi09

    Hello @AChand20 and @thomasjpfan, as AChand20 mentioned, I also thought of the same thing.

    Two approaches, :

    1. return all in best_aparams having same mean test score
    2. Sort the parameters combination having same mean test score in lexicographical order and return the top most.

    I would like to work on this. Please let me know if my approach is correct and if I can start to work on this.

  6. thomasjpfan commented on Dec 9, 2021

    @thomasjpfan
    Member

    But fit time is not a consistent variable. It will change the rank every time we run the code (Tested this on the example code above).

    Good point. In that case fit time is not the most stable way to rank parameter candidates.

    So now in my particular example above clf.best_params_ will return both parameter candidates

    In the end *SearchCV will be refitted on the complete dataset with one parameter configuration. Even if clf.best_params_ returns a multiple candidates, *SearchCV will still need to decide which candidates to use to refit on the complete dataset.

    Sort the parameters combination having same mean test score in lexicographical order and return the top most.

    Having a stable way to pick between candidates with the same rank is a good stop gap solution.

  7. Nivi09 commented on Dec 10, 2021

    @Nivi09

    @thomasjpfan Hi Thomas, Would you please elaborate a bit more on - 'Having a stable way to pick between candidates with the same rank is a good stop gap solution.' ? If you can provide any guidance to me, I will be thankful to you.

  8. thomasjpfan commented on Dec 10, 2021

    @thomasjpfan
    Member

    I think you already proposed a solution in #21925. Please update the opening message in the PR to describe what you mean by "lexicographical sort".

  9. AChand20 commented on Dec 11, 2021

    @AChand20
    Author

    Then I think we should go for a stable way to pick between candidates as suggested by @thomasjpfan , and if "lexicographical sort" provides this stability then we should go for it.
    Yes, updating the opening message in PR #21925 would be helpful.

    Moreover if this issue is confirmed as a 'Bug', can someone change the label of this issue from 'Bug: triage' to 'Bug'.

  10. Nivi09 commented on Dec 11, 2021

    @Nivi09

    @AChand20 , @thomasjpfan Have test and implemented the sorting and all local tests have passed. But azurebuild-piplines test has failed as it is asserting on the values that you will get using the previous implementation which we are trying to resolve. So looks like need to change some test output value. Working on that. I will update the detailed approach in PR.

  11. added
    Moderate
    and removed on Dec 11, 2021
  12. Nivi09 commented on Dec 21, 2021

    @Nivi09

    @AChand20 , @thomasjpfan

    Hello, I have updated the PR.
    Can anyone of you please have a look and provide feedback on the approach and if there is anything that can be improved or modified?
    Thank you in advance.

    Regards.

  13. thomasjpfan commented on Dec 21, 2021

    @thomasjpfan
    Member

    For future reference, it is best to ping in the PR when you want attention on a PR. This makes the notification link directly to the PR.

  14. thomasjpfan commented on Sep 13, 2022

    @thomasjpfan
    Member

    As noted in #21925 (comment) and #21925 (comment), I think this is more of a documentation issue on how we rank ties. A long term solution would be to have a callable to allow users to specific how they want to rank the results.

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

    DocumentationModeratemodule:model_selection

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions