Skip to main content
 首页 » 编程设计

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

2024年11月24日8Leo_wl

我正在使用递归特征消除和交叉验证 (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 

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

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

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

请您参考如下方法:

在管道情况下,

特征选择 (RFECV) 在应用 grid_searchCV 在最终估算器上。

在没有管道的情况下,

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