Boh*_*iak 6 python artificial-intelligence feature-selection scikit-learn
有没有办法从 Scikit-learn 中使用的模型(或使用过的训练数据的整个表)中获取特征(属性)列表?我正在使用一些预处理,如特征选择,我想知道被选择的特征和被删除的特征。例如,我使用随机森林分类器和递归特征消除。
小智 1
所选功能的掩码存储在 RFE 对象的“_support”属性中。
这是一个例子:
from sklearn.datasets import make_friedman1
from sklearn.feature_selection import RFE
from sklearn.svm import SVR
# load a dataset
X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
estimator = SVR(kernel="linear")
selector = RFE(estimator, 5, step=1)
X_new = selector.fit_transform(X, y)
print selector.support_
print selector.ranking_
Run Code Online (Sandbox Code Playgroud)
将显示:
array([ True, True, True, True, True,
False, False, False, False, False], dtype=bool)
array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5])
Run Code Online (Sandbox Code Playgroud)
请注意,如果您想在 RFE 模型中使用随机森林分类器,您将收到以下错误:
AttributeError: 'RandomForestClassifier' object has no attribute 'coef_'
Run Code Online (Sandbox Code Playgroud)
我在此线程中找到了一个解决方法:Recursive feature Elimination on Random Forest using scikit-learn
您必须像这样重写 RandomForestClassifier 类:
class RandomForestClassifierWithCoef(RandomForestClassifier):
def fit(self, *args, **kwargs):
super(RandomForestClassifierWithCoef, self).fit(*args, **kwargs)
self.coef_ = self.feature_importances_
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你 :)