Skip to content Skip to sidebar Skip to footer

How To Pass Elegantly Sklearn's Gridseachcv's Best Parameters To Another Model?

I have found a set of best hyperparameters for my KNN estimator with Grid Search CV: >>> knn_gridsearch_model.best_params_ {'algorithm': 'auto', 'metric': 'manhattan', 'n_

Solution 1:

You can do that as follows:

new_knn_model = KNeighborsClassifier()
new_knn_model.set_params(**knn_gridsearch_model.best_params_)

Or just unpack directly as @taras suggested:

new_knn_model = KNeighborsClassifier(**knn_gridsearch_model.best_params_)

By the way, after finish running the grid search, the grid search object actually keeps (by default) the best parameters, so you can use the object itself. Alternatively, you could also access the classifier with the best parameters through

gs.best_estimator_

Solution 2:

I just want to point out that using the grid.best_parameters and pass them to a new model by unpacking like:

my_model = KNeighborsClassifier(**grid.best_params_)

is good and all and I personally used it a lot. However, as you can see in the documentation here, if your goal is to predict something using those best_parameters, you can directly use the grid.predict method which will use these best parameters for you by default.

example:

y_pred = grid.predict(X_test)

Hope this was helpful.

Post a Comment for "How To Pass Elegantly Sklearn's Gridseachcv's Best Parameters To Another Model?"