Repository navigation
Conversation
|
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. |
|
@ogrisel, Thank you for your reply. I will remove pandas and will use python core data structures to implement the same. |
|
Note you do not need to include #21895 in every commit message. It will clutter the UI in the original issue. |
|
@thomasjpfan , Noted, won't include the REF in further commits. |
|
Hello, I have updated the PR. Regards. |
|
The issue with using 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, Another considerationThere 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 Another API proposalIf 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 |
|
@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. Code snippet to generate rank_MEAN_test_score and rank_STD_test_score : In both cases, even if we rank according to std, we encounter the same issue as raised before. @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. 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). |
|
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. |
|
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 ( |
|
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 |
|
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 |
|
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. |


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:
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
Sort the values.
For above example, the dataframe will look like :
C kernel
1. 1 linear
2. 10 rbf
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.