我想在我的逻辑回归模型中选择前5个特征。我现在有两个数组,一个包含所有特征名称,另一个数组包含来自model.coef_的系数,其中model = LogisticRegression()。
feature_list = ['ball', 'cat', 'apple',....,] # 这个数组有108个元素
coefficents = lr.coef_
print(coefficents[0])
这会打印如下内容:
[ 2.07587361e-04 5.59531750e-04 0.00000000e+00 0.00000000e+00 -5.16353886e-02 ...... 1.66633057e-02] # 这个数组也有108个元素
当我尝试对系数值进行排序时,我得到了不同的值。
sorted_index = np.argsort(coefficents[0])
print(sorted_index)
[ 22 91 42 15 52 31 16 32 86 .... 17 106] # 这个数组有108个值
如何从这两个数组中正确地获取前5个重要特征?
回答:
argsort
是按升序排序的,你需要按降序排序(最高值优先)
我在这里给你一个简单的例子:
import numpy as np
feature_list = ['ball', 'cat', 'apple', 'house', 'tree', 'school', 'child']
coeff = np.array([0.7, 0.3, 0.8, 0.2, 0.4, 0.1, 0.9])
# 取负值以按降序排序系数
idx = (-coeff).argsort()
# 将索引映射到特征列表
desc_feature = [feature_list[i] for i in idx]
# 选择前5个特征
top_feature = desc_feature[:5]
print(top_feature)
结果是你的前5个特征:
['child', 'apple', 'ball', 'tree', 'cat']