1

有没有什么方法可以从Scikit-learn(或使用过的训练数据的整个表格)中获得使用模型中的特征(属性)列表? 我正在使用某些预处理功能,例如功能选择,我想知道所选的功能和已删除的功能。例如,我使用随机森林分类器和递归功能消除。如何从Scikit-learn中的拟合模型中获取属性列表?

回答

0

选定要素的蒙版存储在RFE对象的'_support'属性中。

在这里看到的文档:http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html#sklearn.feature_selection.RFE

下面是一个例子:

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_ 

显示:

array([ True, True, True, True, True, 
     False, False, False, False, False], dtype=bool) 
array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5]) 

请注意,如果你想在一个RFE使用随机森林分类模型,你会得到这个错误:

AttributeError: 'RandomForestClassifier' object has no attribute 'coef_' 

我发现了一个workarround在这个线程: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_ 

希望它能帮助:)

+0

谢谢,这就是我一直在寻找! – Bohemiak

相关问题