Scikit-learn SelectFromModel——实际获取底层预测变量的特征重要性分数
Scikit-learn SelectFromModel - actually obtain the feature importance scores of underlying predictor
我正在尝试估计手头分类任务的特征重要性。对我来说重要的是获得代表每个特征重要性的具体数字,而不仅仅是 'pick X features which are most important'.
显而易见的选择是使用基于树的方法,它提供了很好的 feature_importances_ 方法来获取每个特征的重要性。但我对基于树的分类器的结果并不满意。我了解到 SelectFromModel 方法能够根据重要性得分消除不重要的特征,并且对 SVM 或线性模型也能成功做到这一点。
我想知道,有没有什么方法可以从 SelectFromModel 中获取每个特征的特定重要性分数,而不仅仅是获取最重要特征的列表?
翻阅GitHubsource code,我发现了这段代码:
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
因此,如果您使用的是线性模型,代码只是使用模型系数作为 "importance scores"。
您可以通过从传递给 SelectFromModel
的估算器中提取 coef_
属性来做到这一点。
示例:
sfm = SelectFromModel(LassoCV(), 0.25)
sfm.fit(X, y)
print(sfm.estimator_.coef_) # print "importance" scores
我正在尝试估计手头分类任务的特征重要性。对我来说重要的是获得代表每个特征重要性的具体数字,而不仅仅是 'pick X features which are most important'.
显而易见的选择是使用基于树的方法,它提供了很好的 feature_importances_ 方法来获取每个特征的重要性。但我对基于树的分类器的结果并不满意。我了解到 SelectFromModel 方法能够根据重要性得分消除不重要的特征,并且对 SVM 或线性模型也能成功做到这一点。
我想知道,有没有什么方法可以从 SelectFromModel 中获取每个特征的特定重要性分数,而不仅仅是获取最重要特征的列表?
翻阅GitHubsource code,我发现了这段代码:
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
因此,如果您使用的是线性模型,代码只是使用模型系数作为 "importance scores"。
您可以通过从传递给 SelectFromModel
的估算器中提取 coef_
属性来做到这一点。
示例:
sfm = SelectFromModel(LassoCV(), 0.25)
sfm.fit(X, y)
print(sfm.estimator_.coef_) # print "importance" scores