【问题标题】:Logistic Regression: How to find top three feature that have highest weights?逻辑回归:如何找到权重最高的前三个特征?
【发布时间】:2017-09-20 10:58:59
【问题描述】:

我正在研究 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])

谢谢。我非常感谢您对此提供任何帮助。

【问题讨论】:

    标签: python machine-learning scikit-learn logistic-regression feature-selection


    【解决方案1】:

    这样就可以了:

    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])
    

    【讨论】:

    • 非常感谢。你能告诉我np.argpartition(coefs, -3) 是做什么的吗?
    • 函数 np.argpartition(coefs, k) 将返回一个数组,该数组以 coefs 中最小 n-k 个元素的索引开始,以 coefs 中最大 k 个元素的索引结束。由于它不执行全排序,因此它比对数组进行全排序效率更高(注意在函数中使用 -3 与使用 len(coefs)-3 相同)。如果您不需要效率,也可以用 top_three = np.argsort(coefs)[-3:] 替换该行
    • 我想知道我是否需要进行排序? top_three = np.argpartition(coefs, -3)[-3:] 给了我三个最重要的特征,对吧?但是为什么我需要对top_three_sorted=top_three[np.argsort(coefs[top_three])] 进行排序。这不会改变结果吗?
    • 根据您的问题,您不需要额外的排序,top_three = np.argpartition(coefs, -3)[-3:] 将完成这项工作。我只是不确定我最初何时阅读它(我不确定您是否只需要前三个,或者您是否想让它们像 [第三大,第二大,最大]),所以我两个都回答了场景
    • 感谢您的帮助
    猜你喜欢
    • 2016-03-07
    • 2019-10-03
    • 2014-08-06
    • 2018-12-29
    • 2018-09-23
    • 2014-01-19
    • 2021-06-10
    • 2016-05-15
    • 2016-05-17
    相关资源
    最近更新 更多