Grid Searching Hyperparameters: Save and Reuse Params Dictionary Object
The sklearn.model_selection.GridSearchCV and RandomizedSearchCV optimizers expect specifying a dictionary with key-value pairs as ‘parameter’ : [list_of_value]. After the search completes, the optimal parameters are stored in the best_params_ attribute which is itself a dictionary.
Convenient?
Not really. Say you want to reuse the optimal parameters to perform further calculations later on in your code, without retyping each individual parameter : value pair. You cannot supply best_params_ as the parameters argument directly. Below we find the optimal hyperparameters and save them in a variable. When we attempt to reuse them, we get an error:
In[101]:
grid = {'criterion': ['gini', 'entropy', 'log_loss'],
'max_depth': [5, 10, 20, None],
...,
'n_estimators': [25, 100, 150, 250]}}
model = RandomForestClassifier()
# Run the hyperparameters search
grid_search = GridSearchCV (estimator = model, param_grid = grid, cv = 10, scoring = 'accuracy', verbose = 1)
grid_search.fit(x_train, y_train)
best_score = grid_search.best_score_
best_stdev = float(grid_search.cv_results_['std_test_score'][0])
print ('Accuracy: %.4f (%.4f)' % (best_score, best_stdev))
# save list of parameters for later use
optimal_params = grid_search.best_params_
Out[101]:
Fitting 10 folds for each of 1 candidates, totalling 10 fits
0.9511253909968721 0.015894356473124302
[...]
In[151]:
# Attempt to supply optimal_params to the param_grid argument.
grid_search = GridSearchCV (estimator = model, param_grid = optimal_params, cv = 10, scoring = 'accuracy', verbose = 1)
grid_search.fit(x_train, y_train)
best_score = grid_search.best_score_
best_stdev = float(grid_search.cv_results_['std_test_score'][0])
print(best_score, best_stdev)
Out[151]:
TypeError: Parameter grid for parameter 'criterion' needs to be a list or a numpy array, but got 'entropy' (of type str) instead. Single values need to be wrapped in a list with one element.So it wants a dictionary where each value is a list with one element. How do we do this?
The best_params_ object returned by the optimizer looks like this:
{'criterion': 'entropy',
'max_depth': None,
'max_features': None,
'min_samples_leaf': 2,
'min_samples_split': 20,
'min_weight_fraction_leaf': 0.0,
'n_estimators': 100}What we want is to encapsulate each value in []; i.e., convert it to a single-element list. Unfortunately, there is no general way to do this for every data type at the same time; there is no magic single method/function that will operate on the entire dictionary at once. Above we have numerics, a string, two Nones. After scouring StackOverflow an the internet, I didn’t see anything fully satisfying, but I eventually came up with this:
In[152]:
# params will become the desired dictionary with lists, supplied to model.fit()
params = optimal_params.copy()
for key, value in params.items():
if isinstance(params[key], str):
params[key] = str.split(str(value))
elif isinstance(params[key], int):
params[key] = [params[key]]
elif isinstance(params[key], float):
params[key] = [params[key]]
elif params[key] is None:
params[key] = [None]
params
Out[152]:
{'criterion': ['entropy'],
'max_depth': [None],
'max_features': [None],
'min_samples_leaf': [2],
'min_samples_split': [20],
'min_weight_fraction_leaf': [0.0],
'n_estimators': [100]}Now, the params dictionary looks like something that the optimizer will handle:
In[153]:
grid = params
grid_search = GridSearchCV (estimator = model, param_grid = params, scoring = 'accuracy', cv = 10, verbose = 1)
grid_search.fit(x_train, y_train)
best_score = grid_search.best_score_
best_stdev = float(grid_search.cv_results_['std_test_score'][0])
print(best_score, best_stdev)
Out[153]:
Fitting 10 folds for each of 1 candidates, totalling 10 fits
0.9487964096287229 0.01783032095207848
# Comment:
# you could use RandomizedSearchCV in place of GridSearchCV, except you would specify n_iter = 1 because there is only 1 combination of parameters.
rand_search = RandomizedSearchCV(estimator = model, param_distributions = grid, scoring = 'accuracy', n_iter = 1, cv = 10, verbose = 1)It took me a while to figure out how to get the brackets [] around each value in the params dictionary, so I’m sharing this post, thus solving a problem you didn’t know you had….. ;)
Now if you want to reuse your optimal parameters and/or you perform another time-consuming Grid or Randomized search, you don’t have to go through the rest of the notebook to update all the params lists manually. ;)