Skip to content

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

Closed
Nivi09 wants to merge 20 commits into
scikit-learn:mainfrom
Nivi09:test
Closed

Nivi09 wants to merge 20 commits into
scikit-learn:mainfrom
Nivi09:test

Conversation

@Nivi09

@Nivi09 Nivi09 commented Dec 8, 2021 •

Copy link
Copy Markdown

Reference Issues/PRs

Fixes #21895

This implementation fixes the ranking issue and returns the best hyper-parameters combination in consistent manner using grid/randomized search cv when mean_test_scores and rank are same.

The issue is mentioned in detail in #21895.

What did I implement ?

Since best_params_ in all search algorithms is supposed to return only one combination of hyper-parameters, keeping that in mind, my approach was to sort the hyper-parameters combination having same mean test score and rank 1 in lexicographical order and return the top most.

Let's take an example :

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) # this one returned best params as {'C': 1, 'kernel': 'linear'}
params = {'kernel':('rbf', 'linear'), 'C':[10, 1]}
grid_search(params) #

The output of above code is :
param_C param_kernel mean_test_score rank_test_score mean_train_score
0 1 linear 0.980000 1 0.981667
1 1 rbf 0.966667 4 0.973333
2 10 linear 0.973333 3 0.978333
3 10 rbf 0.980000 1 0.985000
best_parameters = {'C': 1, 'kernel': 'linear'}

param_C param_kernel mean_test_score rank_test_score mean_train_score
0 10 rbf 0.980000 1 0.985000
1 10 linear 0.973333 3 0.978333
2 1 rbf 0.966667 4 0.973333
3 1 linear 0.980000 1 0.981667
best_parameters = {'C':10, kernel:'rbf'}

This happened because : The combination orders were different.

So in this case, my idea was to take all param combinations with rank 1 and then sort the values in params in lexicographical/alphabetical order.
Therefore, my code do the following steps:

  1. Take the param combinations with rank.
    So, based on the code snippet :
    params = {'kernel':('rbf', 'linear'), 'C':[10, 1]}
    grid_search(params)
    the combinations that I will get is {C:[10,1], kernel:['rbf', 'linear']}. In form of dataframe, it will look like :
    C kernel
    0. 10 rbf
    1. 1 linear

  2. Sort the values.
    For above example, the dataframe will look like :
    C kernel
    1. 1 linear
    2. 10 rbf

  3. The code will return the combination index of combination C=1, kernel=linear in the results['params'].

I have tested with for the following combinations of inputs mentioned in tests.

@ogrisel

ogrisel commented Dec 9, 2021

Copy link
Copy Markdown
Member

Thanks for the PR. However scikit-learn has no (strong) dependency on pandas, so if agree this is the best way to deal with tied search results, this would have to be implemented using only pure Python or numpy code.

Also please include a non-regression test for this. For instance by doing a grid search on a purpose-defined test estimator class that ignores it hyper-parameter values (and training set passed to fit) and always predicts a constant prediction.

@Nivi09

Nivi09 commented Dec 9, 2021

Copy link
Copy Markdown
Author

@ogrisel, Thank you for your reply. I will remove pandas and will use python core data structures to implement the same.
I will take your suggestions and try to implement it. Give me a day please.

@thomasjpfan

Copy link
Copy Markdown
Member

Note you do not need to include #21895 in every commit message. It will clutter the UI in the original issue.

@Nivi09

Nivi09 commented Dec 11, 2021

Copy link
Copy Markdown
Author

@thomasjpfan , Noted, won't include the REF in further commits.

@Nivi09

Nivi09 commented Dec 21, 2021

Copy link
Copy Markdown
Author

@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.

@thomasjpfan

Copy link
Copy Markdown
Member

The issue with using params for ordering is that it depends on the repr, which may not be consistent:

from sklearn.datasets import load_iris
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.utils._testing import MinimalClassifier
from sklearn.linear_model import LogisticRegression

X, y = load_iris(return_X_y=True)
pipe = Pipeline([
    ("prep", StandardScaler()), 
    ("clf", MinimalClassifier())])
clf = GridSearchCV(pipe, {"clf": [MinimalClassifier(), LogisticRegression()]})

clf.fit(X, y)
clf.cv_results_['params']

# [{'clf': <sklearn.utils._testing.MinimalClassifier at 0x105438130>},
#  {'clf': LogisticRegression()}]

In this case, MinimalClassifier has a memory address in its repr and will change between runs. I think using std_test_score to break ties would be a little better since it should be consistent with the same data (and random seed).

Another consideration

There are times where there are actual ties and produce the same models. For example:

from sklearn.datasets import load_iris
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier

X, y = load_iris(return_X_y=True)
clf = GridSearchCV(DecisionTreeClassifier(random_state=0), {"max_depth": [100, 50]})
clf.fit(X, y)

In this case, there is no clear choice between which parameter configuration to use.

In all cases, I prefer rank_test_score to reflect tie breaking behavior. In other words, instead of multiple rank 1s, it will actually give out different ranks reflecting how the ties are broken.

Another API proposal

If we can not decide on a way to break the tie ourselves, then we can open it up to the user by passing a callable to GridSearchCV, which we will pass in cv_results_ and a user will return the ranks they want.

@Nivi09

Nivi09 commented Dec 21, 2021 •

Copy link
Copy Markdown
Author

@thomasjpfan, Thank you for guidance. I got your point.

As you have mentioned, considering the std_test_score instead of mean_test_score to rank the parameters.
Tried it on the original code for the example mentioned in PR #21895 , following are the results :
sk

Code snippet to generate rank_MEAN_test_score and rank_STD_test_score :
sk1

In both cases, even if we rank according to std, we encounter the same issue as raised before.
Unless I'm making a mistake in using rankdata!

@thomasjpfan , @glemaitre Please let me know your thoughts on this.

I know that my previous approach has failed as there is one more issue that I have realized from the test case you have given.
For a particular example, as given in issue description above, the problem of having different values of hyper parameters for same estimator occurred because of the way the combinations were ordered, which could have been solved by sorting.

But for different estimators having different hyper parameters, if we have more than one candidate with rank 1, then, the sorting method won't work.

How about this: we will rank based on test mean scores , if there are more than one candidate, then test std among those having same test mean, if there is a tie on test std scores having same test means too, then try to break on train mean scores and if all fails (means has more than one candidate so far) , then return the one on index 0 (the original implementation).
We will also provide a callable to user and if user passes his/her callable, then their callable will be used to return best param instead of code's default method.

@cmarmo cmarmo added the Needs Decision Requires decision label Sep 13, 2022
@betatim

betatim commented Sep 13, 2022

Copy link
Copy Markdown
Member

My guess as to why the standard deviations also turn out to be the same is that the scores for all splits are the same for estimators that have the same mean. Because all the scores are the same we get exactly the same mean and also the same standard deviation.

I think if different hyper-parameter combinations result in the same score, then there is no good way to sort/rank them. As far as we can tell, they are the same. IMHO this means we can pick one at random and declare it "the best".

How about shuffling the combinations that have the same score and using the shuffled order as the ranking? If we can't tell the difference, then "sorting" things at random seems like a sensible thing to do. If the shuffle is based off of the random state of the the search instance it will be reproducible.

@betatim

betatim commented Sep 13, 2022

Copy link
Copy Markdown
Member

Re-reading the original issue and the example given in it, I am not sure this is something that needs fixing. The issue was raised based on the assumption that the order in which you specify the parameters to search over shouldn't matter ({'kernel':('linear', 'rbf'), 'C':[1, 10]} vs {'kernel':('rbf', 'linear'), 'C':[10, 1]}). But if we go with the "same score means we can't tell the difference and can pick at random", then maybe it isn't a problem that if you change the order, you get a different one of the "optimal" points.

@thomasjpfan

Copy link
Copy Markdown
Member

I think that the original issue: #21895 (comment) can be resolved with better documentation that states how ties are handled.

As for this PR, I am -1 because I prefer not add any more complexity to how we rank results. As noted in #21925 (comment), I prefer having a user provided callable that accepts cv_results_ and returns a ranking. This allows flexibility to resolve this issue as well: #7559 (comment). That feature request is about using the "1 standard deviation rule" to pick the simplest model.

@betatim

betatim commented Sep 14, 2022

Copy link
Copy Markdown
Member

Agreed that docs is probably the way to go for solving the original issue. I'd have to think about allowing people to pass a callable.

Should we close this PR and update #21895 to suggest that a PR updating the documentation is the better option? From a quick look at the code I think what happens is that np.argmin() is used to rank results and the docs for that state "In case of multiple occurrences of the minimum values, the indices corresponding to the first occurrence are returned." - so the order of evaluation of parameter combinations "matters".

@thomasjpfan

Copy link
Copy Markdown
Member

I agree. I am closing this PR and updated the original issue #21895 (comment) to say it's a documentation issue.

@Nivi09 Thank you for working on this PR.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

5 participants