为什么我在sklearn中使用pipline和不使用pipline会得到不同的值

时间:2019-04-14 02:39:35

标签: python machine-learning scikit-learn pipeline cross-validation

我将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

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

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

很高兴在需要时提供更多详细信息。

1 个答案:

答案 0 :(得分:1)

在管道情况下,

在将RFECV应用于最终估计量之前,对基本模型(RandomForestClassifier(random_state = 42, class_weight="balanced"))进行功能选择(grid_searchCV)。

在没有管道的情况下,

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