pythonpython-3.xscikit-learnattributeerrorgridsearchcv

AttributeError: 'GridSearchCV' object has no attribute 'best_params_'


Grid search is a way to find the best parameters for any model out of the combinations we specify. I have formed a grid search on my model in the below manner and wish to find best parameters identified using this gridsearch.

from sklearn.model_selection import GridSearchCV
# Create the parameter grid based on the results of random search 
param_grid = {
    'bootstrap': [True],'max_depth': [20,30,40, 100, 110],
    'max_features': ['sqrt'],'min_samples_leaf': [5,10,15],
    'min_samples_split': [40,50,60], 'n_estimators': [150, 200, 250]
}
# Create a based model
rf = RandomForestClassifier()
# Instantiate the grid search model
grid_search = GridSearchCV(estimator = rf, param_grid = param_grid, 
                          cv = 3, n_jobs = -1, verbose = 2)

Now I want to find the best parameters of the gridsearch as the output

grid_search.best_params_

Error:

----> grid_search.best_params_
AttributeError: 'GridSearchCV' object has no attribute 'best_params_'

What am I missing?


Solution

  • You cannot get best parameters without fitting the data.

    Fit the data

    grid_search.fit(X_train, y_train)
    

    Now find the best parameters.

    grid_search.best_params_
    

    grid_search.best_params_ will work after fitting on X_train and y_train.