【问题标题】:sklearn important features error when using logistic regression使用逻辑回归时sklearn重要特征错误
【发布时间】:2021-06-19 08:56:48
【问题描述】:

以下代码使用随机森林模型为我提供了一个显示特征重要性的图表:

from sklearn.feature_selection import SelectFromModel
import matplotlib

clf = RandomForestClassifier()
clf = clf.fit(X_train,y_train)
clf.feature_importances_  
model = SelectFromModel(clf, prefit=True)
test_X_new = model.transform(X_test)

matplotlib.rc('figure', figsize=[5,5])
plt.style.use('ggplot')

feat_importances = pd.Series(clf.feature_importances_, index=X_test.columns)
feat_importances.nlargest(20).plot(kind='barh',title = 'Feature Importance')

但是,我需要对逻辑回归模型执行相同的操作。以下代码产生错误:

from sklearn.feature_selection import SelectFromModel
import matplotlib

clf = LogisticRegression()
clf = clf.fit(X_train,y_train)
clf.feature_importances_  
model = SelectFromModel(clf, prefit=True)
test_X_new = model.transform(X_test)

matplotlib.rc('figure', figsize=[5,5])
plt.style.use('ggplot')

feat_importances = pd.Series(clf.feature_importances_, index=X_test.columns)
feat_importances.nlargest(20).plot(kind='barh',title = 'Feature Importance')

我明白了

AttributeError: 'LogisticRegression' object has no attribute 'feature_importances_'

有人可以帮忙解决我哪里出错了吗?

【问题讨论】:

  • 正如错误所说:'LogisticRegression' object has no attribute 'feature_importances_'我建议你看看shap library,这可能是你在这种情况下要找的:)

标签: python scikit-learn classification


【解决方案1】:

逻辑回归没有排名特征的属性。如果您想可视化可用于显示特征重要性的系数。基本上,我们假设更大的系数对模型有更大的贡献,但必须确保特征具有相同的尺度,否则这个假设是不正确的。请注意,有些系数可能是负数,因此如果您想像在绘图上那样对它们进行排序,您的绘图看起来会有所不同,您可以将它们转换为正数。

拟合逻辑回归模型后,您可以可视化您的系数:

logistic_model.fit(X,Y)
importance = logistic_model.coef_[0]
#importance is a list so you can plot it. 
feat_importances = pd.Series(importance)
feat_importances.nlargest(20).plot(kind='barh',title = 'Feature Importance')

输出将是这样的:

注意:您可以对您的特征进行一些统计测试或相关性分析,以了解对模型的贡献。这取决于您应该使用哪种测试的数据类型(分类、数字等)。

【讨论】:

  • 太棒了,这就是我要找的。如何将系数显示为变量名而不是数字?
  • 您可以在创建熊猫系列时指定特征名称,例如 pd.Series(importance, index = feature_list),就像您在问题中所做的那样:index=X_test.columns 在绘制之前
猜你喜欢
  • 2014-08-06
  • 2014-01-19
  • 2018-02-27
  • 2018-09-23
  • 1970-01-01
  • 2020-04-14
  • 2018-12-03
  • 2023-03-25
  • 2018-12-29
相关资源
最近更新 更多