为什么我在 python 的 sklearn 中使用管道和不使用管道得到不同的值

Why do I get different values with pipline and without pipline in sklearn in python

我正在使用 recursive feature elimination with cross-validation (rfecv)GridSearchCV 以及 RandomForest 分类器,如下所示 使用管道 不使用管道 .

我的代码与管道如下。

X = df[my_features_all]
y = df['gold_standard']

#get development and testing sets
x_train, x_test, y_train, y_test = train_test_split(X, y, random_state=0)

from sklearn.pipeline import Pipeline

#cross validation setting
k_fold = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
#this is the classifier used for feature selection
clf_featr_sele = RandomForestClassifier(random_state = 42, class_weight="balanced")
rfecv = RFECV(estimator=clf_featr_sele, step=1, cv=k_fold, scoring='roc_auc')

param_grid = {'n_estimators': [200, 500],
    'max_features': ['auto', 'sqrt', 'log2'],
    'max_depth' : [3,4,5]
    }

#you can have different classifier for your final classifier
clf = RandomForestClassifier(random_state = 42, class_weight="balanced")
CV_rfc = GridSearchCV(estimator=clf, param_grid=param_grid, cv= k_fold, scoring = 'roc_auc', verbose=10, n_jobs = 5)

pipeline  = Pipeline([('feature_sele',rfecv),('clf_cv',CV_rfc)])

pipeline.fit(x_train, y_train)

结果是(带管道):

Optimal features: 29
Best hyperparameters: {'max_depth': 3, 'max_features': 'auto', 'n_estimators': 500}
Best score: 0.714763

我的代码没有管道如下

X = df[my_features_all]
y = df['gold_standard']

#get development and testing sets
x_train, x_test, y_train, y_test = train_test_split(X, y, random_state=0)

#cross validation setting
k_fold = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)

clf = RandomForestClassifier(random_state = 42, class_weight="balanced")

rfecv = RFECV(estimator=clf, step=1, cv=k_fold, scoring='roc_auc')

param_grid = {'estimator__n_estimators': [200, 500],
    'estimator__max_features': ['auto', 'sqrt', 'log2'],
    'estimator__max_depth' : [3,4,5]
    }

CV_rfc = GridSearchCV(estimator=rfecv, param_grid=param_grid, cv= k_fold, scoring = 'roc_auc', verbose=10, n_jobs = 5)
CV_rfc.fit(x_train, y_train)

结果是(没有管道):

Optimal features: 4
Best hyperparameters: {'max_depth': 3, 'max_features': 'auto', 'n_estimators': 500}
Best score: 0.756835

虽然这两种方法的概念相似,但我得到了不同的结果不同的选定特征(如上图结果部分所示).但是,我得到了相同的超参数值。

我只是想知道为什么会出现这种差异。哪种方法(不使用管道 使用管道?)最适合执行上述任务?

如果需要,我很乐意提供更多详细信息。

在有管道的情况下,

在对最终估计器应用 grid_searchCV 之前,使用基础模型 (RandomForestClassifier(random_state = 42, class_weight="balanced")) 执行特征选择 (RFECV)。

在没有管道的情况下,

对于超参数的每个组合,对应的估计器用于特征选择(RFECV)。因此,这将非常耗时。