You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让决策树分类器的叶节点显示Result列的名称与对应值?

解决决策树叶节点显示类别名称与对应值的问题

你的核心问题是tree.plot_tree的class_names参数使用错误,导致叶节点无法正确显示Result的名称与对应值。以下是具体解决方案:

关键修正步骤

  1. 定义匹配类别的名称列表
    根据你数据集的规则(0=获胜、1=失败、2=平局),创建包含名称和对应值的列表,注意顺序要和模型自动识别的类别顺序一致(sklearn会按类别值升序排序,所以顺序为0、1、2):

    class_labels = ["获胜 (0)", "失败 (1)", "平局 (2)"]
    
  2. 修正tree.plot_tree的参数

    • feature_names传入特征列名,直接用x.columns即可(无需单独定义cols,避免出错)
    • class_names传入上面定义的class_labels
    • 可添加filled=True让树可视化更清晰,属于可选优化参数

修改后的完整代码

from sklearn.model_selection import train_test_split
from sklearn import tree 
from sklearn import metrics
import matplotlib.pyplot as plt

# 数据拆分部分(保持原逻辑)
x = chess.drop(columns = ['Result'])
y = chess['Result']
print(x.shape, y.shape)

x_train, x_test, y_train, y_test = train_test_split(x, y)
print(x_train.shape, x_test.shape)

# 训练决策树
clf = tree.DecisionTreeClassifier(max_depth=3, min_samples_leaf=5, random_state=0)
clf.fit(x_train, y_train)

# 模型评估部分(保持原逻辑)
y_train_pred = clf.predict(x_train)
y_pred = clf.predict(x_test)

print(y_pred)
print(metrics.confusion_matrix(y_test, y_pred))
print(metrics.accuracy_score(y_test, y_pred))
print(metrics.precision_score(y_test, y_pred, average = None))
print(metrics.recall_score(y_test, y_pred, average = None))

# 可视化决策树(核心修正)
class_labels = ["获胜 (0)", "失败 (1)", "平局 (2)"]
tree.plot_tree(
    clf,
    feature_names=x.columns,  # 使用特征列名
    class_names=class_labels, # 自定义类别名称与值
    filled=True,              # 可选:填充颜色区分节点
    rounded=True              # 可选:圆角边框更美观
)
plt.savefig('out.pdf')
plt.show() # 可选:直接显示图像

额外说明

  • 若不确定模型的类别顺序,可以运行print(clf.classes_)查看,输出结果应为[0 1 2],确保class_labels的顺序与之对应
  • 之前使用class_names=cols无效,是因为cols是特征列的名称集合,和分类任务的类别完全无关

内容的提问来源于stack exchange,提问作者TibbyMan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 17:40:47