Skip to content

Inconsistent results with HalvingGridSearchCV #24901

Closed

Description

@fickas

Describe the bug

best_params_ does not match top rank_test_scores incv_results_.

Steps/Code to Reproduce

Please see https://stackoverflow.com/q/74408418/4996152

Expected Results

Expect best params to be top ranked result.

Actual Results

The output of best_params_ is not within the top 4 rank_test_scores incv_results_.

Versions

System:
    python: 3.7.15 (default, Oct 12 2022, 19:14:55)  [GCC 7.5.0]
executable: /usr/bin/python3
   machine: Linux-5.10.133+-x86_64-with-Ubuntu-18.04-bionic

Python dependencies:
          pip: 21.1.3
   setuptools: 57.4.0
      sklearn: 1.0.2
        numpy: 1.21.6
        scipy: 1.7.3
       Cython: 0.29.32
       pandas: 1.3.5
   matplotlib: 3.2.2
       joblib: 1.2.0
threadpoolctl: 3.1.0

Built with OpenMP: True

Activity

  1. added
    Needs Triage
    on Nov 11, 2022
  2. glemaitre commented on Nov 13, 2022

    @glemaitre
    Member

    Could you provide a minimum example with simple data such that we can reproduce the issue.

  3. added and removed
    Needs Triage
    on Nov 13, 2022
  4. fickas commented on Nov 14, 2022

    @fickas
    Author

    That is going to be hard. I am working on the Titanic dataset but I run a lengthy pipeline to get to training and test data. Can I attach a notebook that you can run?

  5. fickas commented on Nov 14, 2022

    @fickas
    Author

    I could put my training set out on github and just provide code from there if that helps.

  6. glemaitre commented on Nov 14, 2022

    @glemaitre
    Member

    yep until this is a file and a possibly short snippet of code that reproduce the issue, then it will be helpful for debugging.

  7. fickas commented on Nov 14, 2022

    @fickas
    Author
  8. betatim commented on Nov 15, 2022

    @betatim
    Member

    Thanks for making the notebook. It looks like the test scores for all parameter combinations is NaN. This means there is no good way to rank the combinations. All you can really say is that combinations with a test score of NaN are all equally bad, and should be ranked last. However, the last release of scikit-learn didn't implement this behaviour.

    Can you try the latest scikit-learn from main? In #24539 we tried to fix how NaN test scores are handled to implement the above ("all combos with NaN share the lowest rank")

  9. glemaitre commented on Nov 15, 2022

    @glemaitre
    Member

    Can you try the latest scikit-learn from main?

    In case you don't want to build from source, you can install the nightly build: https://scikit-learn.org/stable/developers/advanced_installation.html#installing-nightly-builds

  10. betatim commented on Nov 15, 2022

    @betatim
    Member

    I think there are a few things happening in this example. One is that roc_auc as a scorer produces a lot of warnings because KNeighborsClassifier doesn't have a decision_function. At least there are a lot of warnings about that. I don't understand why sometimes a score can be calculated and sometimes not though. This is one thing to investigate, but probably unrelated to this.

    The other thing that is happening is that the highest mean_test_score is achieved not in the last iteration but in an earlier one. As a result grid_result.best_params_, grid_result.cv_results_['params'][best_idx] and grid_result.cv_results_['mean_test_score'][best_idx] all agree (with best_idx = grid_result.best_index_). But when you look at the output of:

    sorted_csv = pd.DataFrame(grid_result.cv_results_,
                              columns=['params', 'rank_test_score', 'mean_test_score']
                             ).sort_values('mean_test_score', ascending=False)
    sorted_csv.head()

    you see a result ranked number 1 with a score of 0.789. Which is higher than 0.746 which is reported as the score of grid_result.best_params_. If instead you limit yourself to the last iteration when printing the results:

    sorted_csv = pd.DataFrame(grid_result.cv_results_,
                              columns=['params', 'iter', 'rank_test_score', 'mean_test_score']
                             ).sort_values('mean_test_score', ascending=False)
    sorted_csv[sorted_csv.iter == sorted_csv.iter.max()].head()

    you recover the result from grid_result.best_params_.

    It took me a while to figure this out, because it is just too intuitive to look at grid_result.cv_results_['rank_test_score'] and think "yeah, the one ranked 1 should be in best_params_". I wonder what we can do about this.

    On the one hand, the successive halving algorithm says "pick solution from final iteration" and most likely the uncertainty on the score from an earlier iteration means that the score fluctuated up (it isn't truly better).

    On the other hand, HalvingGridSearchCV provides a ranking for all parameter combinations of all iterations in its public API which suggests that you should look at it and use it.

    A third thought/question: does it happen that algorithms get a worse test score when the resource (in this case n_samples) is increased?

  11. fickas commented on Nov 16, 2022

    @fickas
    Author

    Thanks for those thoughtful comments. If I understand correctly, I easily could see higher MTS on prior iterations given they come from reduced sample size. Hence, I should ignore the table and just concentrate on the last iteration. But you already do that with best_params_.

    What I don't understand, and is probably a separate thread, is why I am getting nan values with KNN. KNN does have a predict_proba method so it seems I can calculate auc. So not sure what I am missing there. I also commented out the socring line (#scoring="roc_auc"), which I believe then defaults to the score method on KNN. Still getting warnings and nans. If someone asked about all these warnings and you answered in another post, please give me the link, thanks.

  12. betatim commented on Nov 17, 2022

    @betatim
    Member

    I have no good answer/knowledge of why the warnings occur :-/ I think the best way to figure it out would be to run the example in a debugger with a break point somewhere "far enough before but not too far before" the place the warning is raised. Then look around and try to understand why it happens. From making a change to the code a while back I remember that you have to have an agile mind to be able to follow what is happening where.

    I think an actionable thing to do for this issue is to think about how to improve the documentation for HalvingGridSearchCV and friends. Or maybe add some functions/methods to help with interpreting the results. If you count the issue from a while back that pointed out that the ranking wasn't quite right when NaNs were present and this issue, then you have two in a short span of time that are at least semi related to the fact that it is tricky to understand what is what in the results from HalvingGridSearchCV. Three instances if you count the fact that it took me a moment of poking around to realise what was happening, even though I worked on a the code a few weeks ago.

  13. dveni commented on Nov 10, 2023

    @dveni

    Hi!

    Just came across this issue investigating why the best score was not the rank 1 in the cv_results dictionary. I think it would make sense to specify this in the documentation (https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.HalvingGridSearchCV.html). In the best_estimator_ attribute, something in the lines of "Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data in the last iteration of the gridsearch."

    What do you think? I can propose the PR

  14. RudrenduPaul commented on Apr 11, 2026

    @RudrenduPaul
    Contributor

    I'd like to tackle this documentation clarification.

    Based on the discussion above, my plan is to:

    1. Update the best_estimator_, best_score_, and best_params_ attribute docstrings to make clear they reflect the last halving iteration, not the globally highest-ranked row in cv_results_
    2. Add a short note in the user guide clarifying the difference between best_score_ and the highest value in cv_results_['mean_test_score']

    Does this match what @betatim had in mind? Happy to refine the scope before starting.

  15. RudrenduPaul commented on Apr 11, 2026

    @RudrenduPaul
  16. added a commit that references this issue on Apr 11, 2026
    e583be3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions