GridSearch 最佳 estimator 设置问题

GridSearchCV 最佳 estimator 设置问题

def train_model_Grid(estimator, param_grid, cv, X_train, X_test, y_train, ):
    grid_search = GridSearchCV(estimator, param_grid, cv)
    grid_search.fit(X_train, y_train)

    best_classifier = grid_search.best_estimator_

    best_classifier.fit(X_train, y_train)
    y_pred_test = best_classifier.predict(X_test)
    y_pred_prob_test = best_classifier.predict_proba(X_test)

这段代码中通过 grid_search获得了最佳的estimator,通过best_classifier = grid_search.best_estimator_可以显式的将最佳模型估计器赋值给best_classifier,但这段代码不是必须的,即使没有这段代码,后续y_pred_test仍然会用最佳模型来进行预测。

best_classifier.fit(X_train, y_train) 这段代码目的是在使用交叉验证找到最佳模型参数后,使用完整的训练集对最佳模型进行训练,以便在最终模型上利用全部的数据来获得更好的性能。

通常在 GridSearchCV 中默认 refit=True,GridSearchCV 将找到最佳参数自动拟合整个数据集,所以这行代码是多余的。

若设置了refit=True,或者需要手动处理最佳模型的拟合过程,则需要保留这段代码。

posted @ 2024-02-29 17:47  ben犇  阅读(115)  评论(0)    收藏  举报