简体   繁体   English

使用 GridSearchCV 进行超参数调整

[英]hyperparameter tuning using GridSearchCV

I have a K nearest neighbour classifier which you can see below.我有一个 K 最近邻分类器,您可以在下面看到。 From what I understand, the GridSearchCV is testing the model with different values of k between 1-20.据我了解,GridSearchCV 正在测试 model,其 k 值在 1-20 之间。 When I do y_pred=knn_grid_cv.predict(x_test) I get a bunch of y predictions, but what value k (between 1-20) was used to obtain these y predictions?当我执行y_pred=knn_grid_cv.predict(x_test)时,我得到了一堆 y 预测,但是使用什么值 k(在 1-20 之间)来获得这些 y 预测? Would it be the highest scoring k value from the GridSearchCV?它会是 GridSearchCV 中得分最高的 k 值吗?

x=football_df["Pace"].values.reshape(-1, 1)
print(x)
y=football_df["Position"].values.reshape(-1, 1)  

x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.4,random_state=42)

param_grid={"n_neighbors":np.arange(1,20)}  
knn = KNeighborsClassifier()
knn_grid_cv = GridSearchCV(knn, param_grid, cv=5)
knn_grid_cv.fit(x_train,y_train)
y_pred=knn_grid_cv.predict(x_test)
print(y_pred)

You are correct.你是对的。 The way you defined param_grid will test the performance of 20 different models, each with a different value for n_neighbors .您定义param_grid的方式将测试 20 个不同模型的性能,每个模型具有不同的n_neighbors值。 The best model is chosen as the one with the highest average cross-validated score.最好的 model 被选为具有最高平均交叉验证分数的那个。 In the case of a KNeighborsClassifier , the default score metric used is the mean accuracy.KNeighborsClassifier的情况下,使用的默认分数指标是平均准确度。

In your case, that'd be the model with the highest mean accuracy across all five splits.在您的情况下,这将是 model 在所有五个拆分中的平均准确度最高。

To see what value of n_neighbors was chosen, simply do:要查看选择了n_neighbors的值,只需执行以下操作:

# Option 1: print the parameters of the best classifier
print(knn_grid_cv.best_estimator_.get_params())

# Option 2: print results of all model combinations
import pandas as pd
res = pd.DataFrame(knn_grid_cv.cv_results_)
print(res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM