【发布时间】:2018-07-29 16:14:25
【问题描述】:
如果你想运行,这是我的代码
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from treeinterpreter import treeinterpreter as ti
import operator
X, y = make_classification(n_samples=1000,
n_features=6,
n_informative=3,
n_classes=2,
random_state=0,
shuffle=False)
# Creating a dataFrame
df = pd.DataFrame({'Feature 1':X[:,0],
'Feature 2':X[:,1],
'Feature 3':X[:,2],
'Feature 4':X[:,3],
'Feature 5':X[:,4],
'Feature 6':X[:,5],
'Class':y})
y_train = df['Class']
X_train = df.drop('Class',axis = 1)
rf = RandomForestClassifier(n_estimators=50,
random_state=0)
rf.fit(X_train, y_train)
importances = rf.feature_importances_
importances = X_train.columns
instances = X_train.iloc[[60]]
prediction, biases, contributions = ti.predict(rf, instances)
我尝试用 2 种方式对列表进行排序,首先使用 itemgetter
for i in range(len(instances)):
for c, feature in sorted(zip(contributions[i], importances), key=operator.itemgetter(1)):
print (feature, np.round(c, 5))
其次,使用key= lambda
for i in range(len(instances)):
for c, feature in sorted(zip(contributions[i], importances), key=lambda x: x[0].any()):
print (feature, np.round(c, 5))
但是运行这两种解决方案会产生相同的输出
Feature 1 [ 0.16033 -0.16033]
Feature 2 [-0.02422 0.02422]
Feature 3 [-0.15412 0.15412]
Feature 4 [ 0.17162 -0.17162]
Feature 5 [ 0.02897 -0.02897]
Feature 6 [ 0.01889 -0.01889]
我想使用上述输出的第一列对列表进行排序,知道我做错了什么吗?
更新 2:只是澄清问题
按特征顺序排列它们,而不是特征括号内的值
更新 3:如果您使用第一列进行排列,输出应该是什么样子
Feature 4 [ 0.17162 -0.17162]
Feature 1 [ 0.16033 -0.16033]
Feature 5 [ 0.02897 -0.02897]
Feature 6 [ 0.01889 -0.01889]
Feature 2 [-0.02422 0.02422]
Feature 3 [-0.15412 0.15412]
如果你用第二列排列,输出应该是什么样子
Feature 3 [-0.15412 0.15412]
Feature 2 [-0.02422 0.02422]
Feature 6 [ 0.01889 -0.01889]
Feature 5 [ 0.02897 -0.02897]
Feature 1 [ 0.16033 -0.16033]
Feature 4 [ 0.17162 -0.17162]
更新 4 在排序中包含一个 if 条件
打印大于 0.01 和 -0.01 的值
【问题讨论】:
-
请为
contributions和instances提供正确的值。数据结构不清楚,你的代码没有描述这个 -
@Slam 你是什么意思对不起?正如您在提供的代码中向下滚动时所看到的,它们是“ti”的值。您可以在您的环境中运行整个代码
-
@Victor 你不应该按
key=lambda x: x[1]排序吗? -
@Greesha0 当然不是!或者至少这就是我的想法。 x[1] 将尝试对特征进行排序而不是对值进行排序
标签: python pandas numpy machine-learning scikit-learn