有人建议在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_
#eli5.show_weights(perm) # fails: AttributeError: 'PermutationImportance' object has no attribute 'feature_importances_'
有几个问题:
>
我不确定是否正确地使用了交叉验证。 PermutationImportance
正在使用CV
验证验证集中的重要性,还是只应使用RFECV
进行交叉验证? (在本例中,我在两种情况下都使用了cv=3
,但不确定这样做是否正确)
如果取消最后一行的注释,我将得到一个AttributeError:“PermutationImportance”...
这是因为我适合使用RFECV
吗? 我所做的与这里的最后一个代码片段类似:https://eli5.readthedocs.io/en/latest/blackbox/permutation_importance.html
作为一个不太重要的问题,当我在eli5.sklearn.PermutationImportance
中设置cv
时,这会给我一个警告:
.../lib/python3.8/site-packages/sklearn/utils/validation.py:68:futurewarning:Pass classifier=false as关键字args。 从版本0.25传递这些作为位置参数将导致错误警告。warn(“pass{}as keyword args.From version 0.25”
整个过程有点模糊。 有没有直接在sklearn
中进行的方法? 例如,通过添加feature_importances
属性?
我看不出使用两次交叉验证有什么意义。 因此,我建议只使用rfe
而不是rfecv
。 具有排列重要性的特征选择如下所示:
from eli5 import show_weights
from sklearn.datasets import make_friedman1
from sklearn.feature_selection import RFE
from sklearn.svm import SVR
from eli5.sklearn import PermutationImportance
X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
selector = RFE(
PermutationImportance(estimator=SVR(kernel="linear"), cv=3),
step=1
)
selector = selector.fit(X, y)
selector.ranking_
show_weights(selector.estimator_)