如何在Logistic Regression中列出特征重要性对应的列名而非索引
问题:展示特征重要性时如何显示实际特征名称而非索引编号
我希望在展示特征重要性时列出实际的特征名称(列名),而非特征的索引编号,该如何实现?
原代码:
from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression X, y = make_classification(n_samples=2700, n_features=3, n_informative=5, n_redundant=5, random_state=1) model = LogisticRegression() model.fit(X, y) importance = model.coef_[0] for i,v in enumerate(importance): print('Feature: %0d, Score: %.5f' % (i,v))
当前输出:
Feature: 0, Score: -0.11124 Feature: 1, Score: -0.04292 Feature: 2, Score: 0.00561
期望输出:
featurename1, Score: -0.11124 featurename2, Score: -0.04292 featurename3, Score: 0.00561
解决方案
核心是给特征绑定名称列表,遍历重要性时通过索引匹配对应名称,分两种场景实现:
场景1:手动定义特征名称
如果是numpy数组格式的特征数据,直接创建和特征数量匹配的名称列表,用zip关联名称与重要性分数:
from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression X, y = make_classification(n_samples=2700, n_features=3, n_informative=5, n_redundant=5, random_state=1) # 定义与特征数量一致的名称列表 feature_names = ['featurename1', 'featurename2', 'featurename3'] model = LogisticRegression() model.fit(X, y) importance = model.coef_[0] # 遍历名称和对应分数并打印 for name, score in zip(feature_names, importance): print('%s, Score: %.5f' % (name, score))
场景2:使用Pandas DataFrame存储数据
如果特征数据存在DataFrame中,直接调用df.columns获取列名即可,无需手动定义:
import pandas as pd from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression # 生成数据并转为带列名的DataFrame X, y = make_classification(n_samples=2700, n_features=3, n_informative=5, n_redundant=5, random_state=1) df = pd.DataFrame(X, columns=['featurename1', 'featurename2', 'featurename3']) model = LogisticRegression() model.fit(df, y) importance = model.coef_[0] # 用DataFrame的columns属性获取特征名称 for name, score in zip(df.columns, importance): print('%s, Score: %.5f' % (name, score))
内容的提问来源于stack exchange,提问作者prof31
相关产品推荐
相关产品推荐

