繁体   English   中英

检查 scikit-learn 管道中的特征重要性

[英]Inspection of the feature importance in scikit-learn pipelines

我使用 scikit-learn 定义了以下管道:

model_lg = Pipeline([("preprocessing", StandardScaler()), ("classifier", LogisticRegression())])
model_dt = Pipeline([("preprocessing", StandardScaler()), ("classifier", DecisionTreeClassifier())])
model_gb = Pipeline([("preprocessing", StandardScaler()), ("classifier", HistGradientBoostingClassifier())])

然后我使用交叉验证来评估每个 model 的性能:

cv_results_lg = cross_validate(model_lg, data, target, cv=5, return_train_score=True, return_estimator=True)
cv_results_dt = cross_validate(model_dt, data, target, cv=5, return_train_score=True, return_estimator=True)
cv_results_gb = cross_validate(model_gb, data, target, cv=5, return_train_score=True, return_estimator=True)

当我尝试使用coef_方法检查每个 model 的特征重要性时,它给我一个归因错误:

model_lg.steps[1][1].coef_
AttributeError: 'LogisticRegression' object has no attribute 'coef_'

model_dt.steps[1][1].coef_
AttributeError: 'DecisionTreeClassifier' object has no attribute 'coef_'

model_gb.steps[1][1].coef_
AttributeError: 'HistGradientBoostingClassifier' object has no attribute 'coef_'

我想知道,我该如何解决这个错误? 或者是否有任何其他方法来检查每个 model 中的特征重要性?

Imo,这里的要点如下。 一方面,管道实例model_lgmodel_dt等未明确安装(您没有直接在它们上调用方法.fit() ),这会阻止您尝试访问实例本身的coef_属性。

另一方面,通过使用参数return_estimator=True调用.cross_validate() (仅在交叉验证方法中使用.cross_validate()是可能的),您可以为每个 cv 拆分返回拟合估计量,但您应该访问他们通过你的字典cv_results_lgcv_results_dt等(在'estimator'键上)。 这是代码中的参考,这是一个示例:

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_validate

X, y = load_iris(return_X_y=True)

model_lg = Pipeline([("preprocessing", StandardScaler()), ("classifier", LogisticRegression())])

cv_results_lg = cross_validate(model_lg, X, y, cv=5, return_train_score=True, return_estimator=True)

这些将是 - 例如 - 在第一次折叠时计算的结果。

cv_results_lg['estimator'][0].named_steps['classifier'].coef_

有关相关主题的有用见解可以在以下位置找到:

在某些算法和打印精度中进行循环

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM