首页 > 解决方案 > 如何修复 class_names 中超出范围的列表索引以绘制分类树

问题描述

我有一个问题说 List index out of range to make a classification tree

怎么修

export_graphviz(model_tree_smote, out_file=dot_data,
                filled=True, rounded=True,
                special_characters=True, feature_names = columns, class_names=['0.0', '1.0'])
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
graph.write_png('classification.png')
Image(graph.creat_png())

我得到这个错误

    IndexError                                Traceback (most recent call last)
<ipython-input-69-40154f7d5762> in <module>()
      7 export_graphviz(model_tree_smote, out_file=dot_data,
      8                 filled=True, rounded=True,
----> 9                 special_characters=True, feature_names = columns, class_names=['0.0', '1.0'])
     10 graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
     11 graph.write_png('classification.png')

10 frames
/usr/local/lib/python3.7/dist-packages/sklearn/tree/_export.py in node_to_str(self, tree, node_id, criterion)
    335                 node_string += 'class = '
    336             if self.class_names is not True:
--> 337                 class_name = self.class_names[np.argmax(value)]
    338             else:
    339                 class_name = "y%s%s%s" % (characters[1],

IndexError: list index out of range

所以我无法打印树因为这个错误,请帮我解决问题

标签: pythonjupyter-notebook

解决方案


类名应具有每个目标类的名称,按数字升序排列。仅与分类相关,不支持多输出。

您尚未共享目标变量的片段,但检查目标变量列的唯一值并确保class_names的数量等于目标变量唯一值的数量。例如,如果您的目标变量是月数 (12),请确保类名的数量为 12,即:

class_names = ['1','2','3','4','5','6','7','8','9','10','11','12']

或者

class_names=['Jan','Feb','Mar','April', 'May', 'June', 'July', 'Aug', 'Sep', 'Sep','Oct', 'Nov', 'Dec']

您的代码应该可以工作。


推荐阅读