如何在SelectFromModel()中选择阈值来选择要素?

时间:2018-03-18 07:40:15

标签: python pandas numpy machine-learning scikit-learn

我正在使用随机森林分类器进行特征选择。我总共有70个功能,我想从70中选择最重要的功能。下面的代码显示分类器显示从最重要到最不重要的功能。

代码:

feat_labels = data.columns[1:]
clf = RandomForestClassifier(n_estimators=100, random_state=0)

# Train the classifier
clf.fit(X_train, y_train)

importances = clf.feature_importances_
indices = np.argsort(importances)[::-1]

for f in range(X_train.shape[1]):
    print("%2d) %-*s %f" % (f + 1, 30, feat_labels[indices[f]], importances[indices[f]]))  

enter image description here

现在我正在尝试使用SelectFromModel中的sklearn.feature_selection,但我如何确定给定数据集的阈值。

# Create a selector object that will use the random forest classifier to identify
# features that have an importance of more than 0.15
sfm = SelectFromModel(clf, threshold=0.15)

# Train the selector
sfm.fit(X_train, y_train)

当我尝试threshold=0.15然后尝试训练我的模型时,我得到一个错误,说数据太嘈杂或选择太严格。

但是如果我使用threshold=0.015我能够在选定的新功能上训练我的模型那么我该如何确定这个阈值呢?

1 个答案:

答案 0 :(得分:3)

我会尝试以下方法:

  1. 以较低的阈值开头,例如:1e-4
  2. 使用SelectFromModel fit& amp;降低您的功能变换
  3. 计算所选功能的估算工具(在您的案例中为RandomForestClassifier)的指标(准确度等)
  4. 增加阈值并重复从第1点开始的所有步骤。
  5. 使用此方法,您可以估算出特定数据和估算工具的最佳threshold