何时使用交叉验证和网格搜索在imblearn管道中进行特征选择

Joo*_*sen 4 python sampling feature-selection imblearn

目前,我正在建立数据严重不平衡的分类器。我正在使用imblearn管道首先到达StandardScaling,SMOTE,然后使用gridSearchCV进行分类。这确保了在交叉验证期间完成了升采样。现在,我想将feature_selection包含到我的管道中。我应该如何将这一步骤纳入管道中?

model = Pipeline([
        ('sampling', SMOTE()),
        ('classification', RandomForestClassifier())
    ])

param_grid = { 
    'classification__n_estimators': [10, 20, 50],
    'classification__max_depth' : [2,3,5]
}

gridsearch_model = GridSearchCV(model, param_grid, cv = 4, scoring = make_scorer(recall_score))
gridsearch_model.fit(X_train, y_train)
predictions = gridsearch_model.predict(X_test)
print(classification_report(y_test, predictions))
print(confusion_matrix(y_test, predictions))
Run Code Online (Sandbox Code Playgroud)

Cri*_*riu 7

在模型是随机森林(RF)的管道中包括特征选择不一定是有意义的。这是因为RF模型的max_depthmax_features参数实际上控制着构建单个树时所包含的功能数量(最大深度n表示森林中的每棵树都是为n节点构建的,每个树的拆分由以下各项的组合组成)max_features功能数量)。检查https://scikit-learn.org/stable/modules/generation/sklearn.ensemble.RandomForestClassifier.html

您可以简单地调查您训练有素的模型以获得排名靠前的功能。训练一棵树时,可以计算出每个特征将一棵树中的加权杂质减少多少。对于森林,可以平均每个特征的杂质减少量,并根据此度量对特征进行排名。因此,实际上您不需要为不同的功能集重新培训森林,因为功能重要性(已在sklearn模型中计算出)可以告诉您所需的所有信息。


PS我也不会浪费时间网格搜索n_estimators,因为更多的树将导致更好的准确性。更多的树意味着更多的计算成本,并且经过一定数量的树后,改进量太小,因此也许您需要担心,但是否则您将通过大量的n_estimator获得性能,而实际上并没有过度拟合的麻烦。