Skip to content

第8章:模型选择和调优

本章将详细介绍如何使用scikit-learn进行模型选择和调优。

8.1 网格搜索和随机搜索

网格搜索和随机搜索是常用的超参数调优方法。

8.1.1 网格搜索

使用GridSearchCV进行网格搜索。

python
from sklearn.model_selection import GridSearchCV
param_grid = {'n_estimators': [100, 200], 'max_depth': [2, 4]}
grid_search = GridSearchCV(RandomForestClassifier(), param_grid, cv=5)
grid_search.fit(X_train, y_train)

8.1.2 随机搜索

使用RandomizedSearchCV进行随机搜索。

python
from sklearn.model_selection import RandomizedSearchCV
param_distributions = {'n_estimators': [100, 200], 'max_depth': [2, 4]}
random_search = RandomizedSearchCV(RandomForestClassifier(), param_distributions, n_iter=10, cv=5)
random_search.fit(X_train, y_train)

8.2 贝叶斯优化

贝叶斯优化是一种高效的超参数调优方法。

8.2.1 贝叶斯优化

使用BayesianOptimization进行贝叶斯优化。

python
from bayes_opt import BayesianOptimization
def target_function(n_estimators, max_depth):
    clf = RandomForestClassifier(n_estimators=int(n_estimators), max_depth=int(max_depth))
    clf.fit(X_train, y_train)
    return -clf.score(X_test, y_test)
optimizer = BayesianOptimization(f=target_function, pbounds={'n_estimators': (100, 200), 'max_depth': (2, 4)}, random_state=42)
optimizer.maximize(init_points=10, n_iter=30)

8.3 模型管道

模型管道可以帮助我们自动化数据预处理和模型训练的流程。

8.3.1 创建管道

使用Pipeline创建模型管道。

python
from sklearn.pipeline import Pipeline
pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('clf', RandomForestClassifier())
])
pipeline.fit(X_train, y_train)

8.4 本章小结

本章介绍了模型选择和调优的方法,包括网格搜索、随机搜索、贝叶斯优化和模型管道。这些工具可以帮助我们找到最佳的模型配置,提高模型性能。