gpt4 book ai didi

python - 逻辑回归 : How to find top three feature that have highest weights?

转载 作者:太空宇宙 更新时间:2023-11-03 14:05:49 25 4
gpt4 key购买 nike

我正在研究 UCI 乳腺癌数据集,并试图找到权重最高的前 3 个特征。我能够使用 logmodel.coef_ 找到所有特征的权重,但如何获取特征名称?下面是我的代码、输出和数据集(从 scikit 导入)。

from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression

cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
cancer.data, cancer.target, stratify=cancer.target, random_state=42)

logmodel = LogisticRegression(C=1.0).fit(X_train, y_train)
logmodel.coef_[0]

以上代码输出权重数组。我如何使用这些权重获得关联的特征名称?

Output:
array([ 1.90876683e+00, 9.98788148e-02, -7.65567571e-02,
1.30875965e-03, -1.36948317e-01, -3.86693503e-01,
-5.71948682e-01, -2.83323656e-01, -2.23813863e-01,
-3.50526844e-02, 3.04455316e-03, 1.25223693e+00,
9.49523571e-02, -9.63789785e-02, -1.32044174e-02,
-2.43125981e-02, -5.86034313e-02, -3.35199227e-02,
-4.10795998e-02, 1.53205924e-03, 1.24707244e+00,
-3.19709151e-01, -9.61881472e-02, -2.66335879e-02,
-2.44041661e-01, -1.24420873e+00, -1.58319440e+00,
-5.78354663e-01, -6.80060645e-01, -1.30760323e-01])

谢谢。如果能提供任何帮助,我将不胜感激。

最佳答案

这将完成工作:

import numpy as np
coefs=logmodel.coef_[0]
top_three = np.argpartition(coefs, -3)[-3:]
print(cancer.feature_names[top_three])

这打印

['worst radius' 'texture error' 'mean radius']

请注意,这些功能是前三个,但它们之间不一定排序。如果你想让它们排序,你可以这样做:

import numpy as np
coefs=logmodel.coef_[0]
top_three = np.argpartition(coefs, -3)[-3:]
top_three_sorted=top_three[np.argsort(coefs[top_three])]
print(cancer.feature_names[top_three_sorted])

关于python - 逻辑回归 : How to find top three feature that have highest weights?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43576614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com