【问题标题】:Getting feature importance by sample - Python Scikit Learn通过样本获取特征重要性 - Python Scikit Learn
【发布时间】:2021-02-02 18:57:36
【问题描述】:

我有一个使用 sklearn.ensemble.RandomForestClassifier 的拟合模型 (clf)。我已经知道我可以通过clf.feature_importances_ 获得特征重要性。无论如何,如果可能的话,我想知道如何通过每个样本获取特征重要性。

例子:

from sklearn.ensemble import RandomForestClassifier

X = {"f1":[0,1,1,0,1], "f2":[1,1,1,0,1]}
y = [0,1,0,1,0]

clf = RandomForestClassifier(max_depth=2, random_state=0)
clf.fit(X, y)

y_pred = clf.predict(X)

那么,我该如何得到这样的东西:

y_pred f1_importance f2_importance
   1         0.57          0.43          
   1         0.26          0.74
   1         0.31          0.69
   0         0.62          0.38
   1         0.16          0.84

* y_pred 值不是真实的。我实际上在 Python 3.8 中将pandas 用于实际项目。

【问题讨论】:

    标签: python python-3.x scikit-learn random-forest


    【解决方案1】:

    您可以使用treeinterpreter 来获取您的RandomForestClassifier 的单个预测的特征重要性

    您可以在Github 上找到treeinterpreter 并通过以下方式安装它

    pip install treeinterpreter
    

    我使用了你的参考代码,但不得不调整它,因为你不能使用字典作为输入来适应你的RandomForestClassifier

    from sklearn.ensemble import RandomForestClassifier
    from treeinterpreter import treeinterpreter as ti
    import numpy as np
    import pandas as pd
    
    X = np.array([[0,1],[1,1],[1,1],[0,0],[1,1]])
    y = [0,1,0,1,0]
    
    clf = RandomForestClassifier(max_depth=2, random_state=0)
    clf.fit(X, y)
    
    y_pred = clf.predict(X)
    y_pred_probas = clf.predict_proba(X)
    

    然后我使用带有分类器和数据的树解释器来计算偏差、贡献和预测值:

    prediction, bias, contributions = ti.predict(clf, X)
    
    df = pd.DataFrame(data=np.matrix([y_pred, prediction.transpose()[0], prediction.transpose()[1], np.sum(contributions, axis=1).transpose()[0], bias.transpose()[0], np.sum(contributions, axis=1).transpose()[1], bias.transpose()[1]]).transpose(), columns=["Prediction", "Prediction value 0", "Prediction value 1", "f1_contribution", "f1_bias", "f2_contribution","f2_bias"])
    
    df
    

    输出

    您可以查看作者的this blogpost,以更好地了解其工作原理。

    表中0和1的预测值指的是两个类的概率,也可以使用RandomForestClassifier现有的predict_proba()方法计算。

    您可以验证,偏差和贡献加起来是这样的预测值/概率:

    bias + np.sum(contributions, axis=1)
    

    输出

    array([[0.744 , 0.256 ],
           [0.6565, 0.3435],
           [0.6565, 0.3435],
           [0.214 , 0.786 ],
           [0.6565, 0.3435]])
    

    【讨论】:

      猜你喜欢
      • 2017-11-04
      • 2016-03-18
      • 2018-09-23
      • 2019-02-14
      • 2018-08-16
      • 2018-01-01
      • 2018-05-13
      • 1970-01-01
      • 2016-02-25
      相关资源
      最近更新 更多