管道与网格搜索的变体
使用非网格空间中搜索,即,将参数字典替换为参数字典序列,可以实现在管道上寻找最优模型的最优状态。当然,最优的模型和可能的最优状态都是开发者自己指定的。
实现
①👇加载cancer数据集
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
cancer = load_breast_cancer()
②制作参数字典序列,原因是当前是在非网格空间上进行搜索。
#👇制作参数字典
param_grid = [
{'classifier': [SVC()], 'preprocessing': [StandardScaler(), None],
'classifier__gamma': [0.001, 0.01, 0.1, 1, 10, 100],
'classifier__C': [0.001, 0.01, 0.1, 1, 10, 100]},
{'classifier': [RandomForestClassifier(n_estimators=100)],
'preprocessing': [None], 'classifier__max_features': [1, 2, 3]}]
👆由于随机森林不需要进行数据预处理(前面的文章也提到过,对基于树的机器学习模型进行数据预处理可能会使模型的精度下降,这些模型本身就不需要进行数据预处理),因此在preprocessing处的参数填为None。
③👇寻找最优模型的最优状态
X_train, X_test, y_train, y_test = train_test_split(
cancer.data, cancer.target, random_state=0)
grid = GridSearchCV(pipe, param_grid, cv=5)
grid.fit(X_train, y_train)
#👇用网格搜索SVC和RandomForest哪个模型更优,及在合时(参数状态)更优
print("Best params:\n{}\n".format(grid.best_params_))
print("Best cross-validation score: {:.2f}".format(grid.best_score_))
print("Test-set score: {:.2f}".format(grid.score(X_test, y_test)))