我试图估计手头分类任务的特征重要性。对我来说重要的是获得代表每个特征重要性的具体数字,而不仅仅是“选择最重要的X个特征”。
显而易见的选择是使用基于树的方法,这些方法提供了很好的feature_importances_方法来获取每个特征的重要性。但我对基于树的分类器的结果并不满意。我了解到SelectFromModel方法能够根据重要性得分消除不重要的特征,并且对SVM或线性模型也同样有效地做到这一点。
我想知道,有没有办法从SelectFromModel中获取每个特征的具体重要性得分,而不仅仅是得到最重要特征的列表?
回答:
在浏览GitHub的源代码时,我发现了这段代码:
def _get_feature_importances(estimator): """Retrieve or aggregate feature importances from estimator""" importances = getattr(estimator, "feature_importances_", None) if importances is None and hasattr(estimator, "coef_"): if estimator.coef_.ndim == 1: importances = np.abs(estimator.coef_) else: importances = np.sum(np.abs(estimator.coef_), axis=0) elif importances is None: raise ValueError( "The underlying estimator %s has no `coef_` or " "`feature_importances_` attribute. Either pass a fitted estimator" " to SelectFromModel or call fit before calling transform." % estimator.__class__.__name__) return importances
因此,如果您使用的是线性模型,代码只是将模型系数用作“重要性得分”。
您可以通过从传递给SelectFromModel
的估计器中提取coef_
属性来做到这一点。
示例:
sfm = SelectFromModel(LassoCV(), 0.25)sfm.fit(X, y)print(sfm.estimator_.coef_) # 打印“重要性”得分