在将随机森林可视化的时候,调用tree.export_graphviz突然报错:string index out of range
先训练一个模型嘛
rf_classifier = RandomForestClassifier(n_estimators=n_estimators,max_depth=max_depth,criterion=criterion,max_features=max_features,bootstrap=bootstrap,max_samples=max_samples,class_weight=class_weight,random_state=random_state)
rf_classifier.fit(X, Y)
然后调用graphviz把每棵树存下来
for index, model in enumerate(Estimators):
dot_data = tree.export_graphviz(model, out_file=None,
feature_names=features,
class_names=label, #***
filled=True, rounded=True,
special_characters=True)
结果就报错string index out of range
问题就出在class_names=label
在我这里,label是指数据集中标签列那一整列的数据。然后发现tree.export_graphviz中对class_names的定义是
class_names : list of strings, bool or None, optional (default=None)
Names of each of the target classes in ascending numerical order.
我琢磨,这是只想要有多少个class,都叫啥,而不是整个数据的class。
所以改了一下
class_names=list(set(label))
就成了
还有一个玄学的问题。之前测试的时候都是可以跑通的,结果怎么又不行了呢。估计是测试的数据集特征比较少,实际数据集有两百来个特征就暴露问题了。