如果你想运行它,这里是我的代码
我尝试了两种方式来排序列表,首先使用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.shape
是 (1, 6, 2)
。使用 contributions[0]
可以方便地与 zip
一起迭代:
zip(importances, contributions[0])
将生成名称 + [值]
对。这是如何通过使用lambda进行排序并通过链接索引来迭代的示例:
for name, values in sorted(zip(importances, contributions[0]), key=lambda pair: pair[1][0]): print(name, values)
Lambda将获取名称 + 值
对,使用[1]
获取值
,然后使用[0]
获取值的第一列。
过滤是另一项任务。最简单的方式是在for
循环中检查值,以便于后续阅读/调试代码:
for name, values in sorted(zip(importances, contributions[0]), key=lambda pair: pair[1][0]): if -0.01 < values[0] > 0.01: print(name, values)
如果a < b > c
难以理解,你可以将其转换为not a < b < c
,或者(在你的情况下)abs(b) > a