如何隐藏plot_tree()生成树图节点的criterion值并替换value为proba
操作方法
1. 隐藏节点内的criterion值
你使用的应该是scikit-learn提供的sklearn.tree.plot_tree函数,隐藏criterion值不需要额外修改配置,直接调用函数时设置impurity=False参数即可:该参数默认值为True,会展示基尼系数/交叉熵等criterion的计算结果,设为False后会自动隐藏这部分内容。
示例代码片段:
from sklearn.tree import plot_tree import matplotlib.pyplot as plt # 此处clf为已训练完成的决策树模型 plt.figure(figsize=(12,8)) plot_tree(clf, impurity=False, # 核心参数,隐藏criterion值 feature_names=feature_names, class_names=class_names, filled=True) plt.show()
2. 替换"value"为"proba"
不需要修改sklearn源码,直接对matplotlib生成的文本对象做内容替换即可实现需求:调用plot_tree时会返回所有节点的文本对象列表,遍历列表匹配关键词替换即可。
完整示例代码:
from sklearn.tree import plot_tree import matplotlib.pyplot as plt plt.figure(figsize=(12,8)) # 调用plot_tree获取返回的文本对象列表 tree_texts = plot_tree(clf, impurity=False, feature_names=feature_names, class_names=class_names, filled=True) # 遍历所有文本对象替换内容 for text in tree_texts: content = text.get_text() # 把value替换为proba new_content = content.replace("value", "proba") text.set_text(new_content) plt.show()
如果需要把value对应的原始样本数同步修改为概率值,可以在替换文本的同时计算每个类别的占比再更新文本内容即可,无需额外调整其他配置。
内容的提问来源于stack exchange,提问作者Любовь Пономарева
相关产品推荐
相关产品推荐

