如何从 Scikit-learn 中的拟合模型获取属性列表?
How to get attribute list from fitted model in Scikit-learn?
有什么方法可以从 Scikit-learn 中使用的模型(或整个 table 使用的训练数据)中获取特征(属性)列表?
我正在使用一些像特征选择这样的预处理,我想知道被选择的特征和被移除的特征。例如我使用随机森林分类器和递归特征消除。
所选功能的掩码存储在 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_
将显示:
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 模型中使用随机森林 classifier,您将收到此错误:
AttributeError: 'RandomForestClassifier' object has no attribute 'coef_'
我在这个线程中找到了一个解决方法:Recursive feature elimination on Random Forest using scikit-learn
您必须像这样覆盖 RandomForestClassifier class:
class RandomForestClassifierWithCoef(RandomForestClassifier):
def fit(self, *args, **kwargs):
super(RandomForestClassifierWithCoef, self).fit(*args, **kwargs)
self.coef_ = self.feature_importances_
希望对您有所帮助:)
有什么方法可以从 Scikit-learn 中使用的模型(或整个 table 使用的训练数据)中获取特征(属性)列表? 我正在使用一些像特征选择这样的预处理,我想知道被选择的特征和被移除的特征。例如我使用随机森林分类器和递归特征消除。
所选功能的掩码存储在 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_
将显示:
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 模型中使用随机森林 classifier,您将收到此错误:
AttributeError: 'RandomForestClassifier' object has no attribute 'coef_'
我在这个线程中找到了一个解决方法:Recursive feature elimination on Random Forest using scikit-learn
您必须像这样覆盖 RandomForestClassifier class:
class RandomForestClassifierWithCoef(RandomForestClassifier):
def fit(self, *args, **kwargs):
super(RandomForestClassifierWithCoef, self).fit(*args, **kwargs)
self.coef_ = self.feature_importances_
希望对您有所帮助:)