【问题标题】:How to get attribute list from fitted model in Scikit-learn?如何从 Scikit-learn 中的拟合模型中获取属性列表?
【发布时间】:2015-11-21 22:03:16
【问题描述】:

有没有办法从 Scikit-learn 中使用的模型(或使用的训练数据的整个表)中获取特征(属性)列表? 我正在使用一些预处理,如特征选择,我想知道选择的特征和删除的特征。例如我使用随机森林分类器和递归特征消除。

【问题讨论】:

    标签: python scikit-learn artificial-intelligence feature-selection


    【解决方案1】:

    所选特征的掩码存储在 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_'
    

    我在这个帖子中找到了一个解决方法: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_
    

    希望对你有帮助:)

    【讨论】:

    • 谢谢,这就是我要找的!
    猜你喜欢
    • 2019-08-18
    • 2021-05-09
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 2015-03-25
    • 2017-07-13
    • 2018-07-16
    • 2019-10-29
    相关资源
    最近更新 更多