【问题标题】:How to convert eli5.show_weights to an array/list in python如何在 python 中将 eli5.show_weights 转换为数组/列表
【发布时间】:2021-01-06 22:46:14
【问题描述】:

我是训练有素的模型,一切正常。我正在计算每个特征权重的排列重要性。我正在使用eli5.show_weights(),但它会将输出显示为html,但我需要将其转换为某种列表或数组,以便我可以访问这些值。

这是我的代码示例,为了简单起见,不包括 estimator's 代码部分:

import eli5
from eli5.sklearn import PermutationImportance

perm = PermutationImportance(estimator, random_state=1).fit(X_testdf, y_testdf)
eli5.show_weights(perm, feature_names = X_testdf.columns.tolist())

这很好用,但我需要将eli5.show_weights(..) 输出的值保存到数组或任何变量中,以便我可以访问这些值。

我也试过了,但没有成功

np.array(eli5.show_weights(perm, feature_names=X.columns.tolist()))

有人可以帮帮我吗?

【问题讨论】:

    标签: python numpy scikit-learn permutation logistic-regression


    【解决方案1】:

    权重或特征重要性存储在排列对象中,因此您可以直接提取它们:

    perm.feature_importances_ 
    

    例如,这可以返回一个类似的数组

    array([0.   , 0.008, 0.584, 0.172]) # Only the mean, not the Std.Dev.
    

    如果您需要它们以及功能名称,您可以压缩名称和功能重要性:

     list(zip(X_test.columns.tolist(), perm.feature_importances_))
    

    或者,您也可以将 HTML 显示转换回原始 HTML,然后使用 Pandas 读取。示例:

    w = eli5.show_weights(perm, feature_names=feature_names)
    result = pd.read_html(w.data)[0]
    result
    

    iris 数据集的输出示例)

    Weight          Feature
    0.5840 ± 0.1170 petal_length
    0.1720 ± 0.0697 petal_width
    0.0080 ± 0.0196 sepal_width
    0 ± 0.0000      sepal_length
    

    虽然注意这里的Weight 列是一个字符串,所以你必须做一些进一步的操作。

    【讨论】:

      【解决方案2】:

      我参考 tania 的帖子并使用以下代码获取列表。

      result = [(x[0], x[1], x[2]) for x in zip(perm_import.feature_importances_, perm_import.feature_importances_std_, X_train.columns)]
      result.sort(key=lambda x: x[0], reverse=True)
      
      print(result)
      

      【讨论】:

        猜你喜欢
        • 2019-01-10
        • 2012-04-03
        • 2017-06-07
        • 2019-03-12
        • 2019-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-04
        相关资源
        最近更新 更多