使用 RFECV 和排列重要性的正确方法 - Sklearn

tow*_*ism 5 python feature-selection scikit-learn cross-validation eli5

Sklearn 在#15075中有一个实现此功能的提案,但与此同时,eli5建议将其作为解决方案。但是,我不确定我是否以正确的方式使用它。这是我的代码:

from sklearn.datasets import make_friedman1
from sklearn.feature_selection import RFECV
from sklearn.svm import SVR
import eli5
X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
estimator = SVR(kernel="linear")
perm = eli5.sklearn.PermutationImportance(estimator,  scoring='r2', n_iter=10, random_state=42, cv=3)
selector = RFECV(perm, step=1, min_features_to_select=1, scoring='r2', cv=3)
selector = selector.fit(X, y)
selector.ranking_
Run Code Online (Sandbox Code Playgroud)

有几个问题:

  1. 我不确定我是否以正确的方式使用交叉验证。PermutationImportance用于cv验证验证集的重要性,或者交叉验证应该仅使用RFECV? (在示例中,我cv=3在两种情况下都使用了,但不确定这是否是正确的做法)

  2. 如果我运行eli5.show_weights(perm),我会得到:AttributeError: 'PermutationImportance' object has no attribute 'feature_importances_'。这是因为我适合使用吗RFECV?我正在做的事情与这里的最后一个片段类似: https: //eli5.readthedocs.io/en/latest/blackbox/permutation_importance.html

  3. cv作为一个不太重要的问题,当我设置时,这给了我一个警告eli5.sklearn.PermutationImportance

.../lib/python3.8/site-packages/sklearn/utils/validation.py:68: FutureWarning: Pass classifier=False as keyword args. From version 0.25 passing these as positional arguments will result in an error warnings.warn("Pass {} as keyword args. From version 0.25 "

整个过程有点模糊。有没有办法直接在里面做Sklearn例如通过添加feature_importances属性?

afs*_*rov 3

由于目标是选择具有排列重要性和递归特征消除的最佳特征数量,我建议使用RFECVPermutationImportance与 CV 分割器结合使用KFold。代码可能如下所示:

import warnings
from eli5 import show_weights
from eli5.sklearn import PermutationImportance
from sklearn.datasets import make_friedman1
from sklearn.feature_selection import RFECV
from sklearn.model_selection import KFold
from sklearn.svm import SVR


warnings.filterwarnings("ignore", category=FutureWarning)

X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)

splitter = KFold(n_splits=3) # 3 folds as in the example

estimator = SVR(kernel="linear")
selector = RFECV(
    PermutationImportance(estimator,  scoring='r2', n_iter=10, random_state=42, cv=splitter),
    cv=splitter,
    scoring='r2',
    step=1
)
selector = selector.fit(X, y)
selector.ranking_

show_weights(selector.estimator_)
Run Code Online (Sandbox Code Playgroud)

关于您的问题:

  1. PermutationImportanceRFECV将根据 提供的分割以相同的策略计算特征重要性和r2 评分KFold

  2. 您调用show_weights了未安装的PermutationImportance对象。这就是你收到错误的原因。您应该使用该estimator_属性来访问已安装的对象。

  3. 可以忽略不计。