在Scikit-learn中,可以使用GridSearchCV或RandomizedSearchCV来实现模型微调。这两个方法可以帮助我们自动地搜索最优的超参数组合,从而提高模型的性能。
使用GridSearchCV进行模型微调:from sklearn.model_selection import GridSearchCVfrom sklearn.ensemble import RandomForestClassifier# 定义要调优的参数网格param_grid = { 'n_estimators': [100, 200, 300], 'max_depth': [None, 10, 20], 'min_samples_split': [2, 5, 10]}# 初始化随机森林分类器rf = RandomForestClassifier()# 使用GridSearchCV进行模型微调grid_search = GridSearchCV(estimator=rf, param_grid=param_grid, cv=5)grid_search.fit(X_train, y_train)# 输出最佳参数组合和最佳得分print("Best parameters found: ", grid_search.best_params_)print("Best score found: ", grid_search.best_score_)使用RandomizedSearchCV进行模型微调:from sklearn.model_selection import RandomizedSearchCVfrom scipy.stats import randintfrom sklearn.ensemble import RandomForestClassifier# 定义要调优的参数分布param_dist = { 'n_estimators': randint(100, 1000), 'max_depth': [None, 10, 20, 30], 'min_samples_split': randint(2, 20)}# 初始化随机森林分类器rf = RandomForestClassifier()# 使用RandomizedSearchCV进行模型微调random_search = RandomizedSearchCV(estimator=rf, param_distributions=param_dist, n_iter=100, cv=5)random_search.fit(X_train, y_train)# 输出最佳参数组合和最佳得分print("Best parameters found: ", random_search.best_params_)print("Best score found: ", random_search.best_score_)通过以上步骤,我们可以使用GridSearchCV或RandomizedSearchCV来实现模型微调,并找到最优的超参数组合。


