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

分类数据决策树编码结果与课程示例不符的技术咨询

决策树复现结果与课程不一致问题

我在复现课程中的分类数据决策树示例时,运行代码得到的结果和课程提供的结果不一致。数据为分类类型,我使用One-Hot Encoder对特征进行编码,将输出(是否打网球)的"no"转换为0、"yes"转换为1。以下是我编写的代码、我的输出结果以及课程提供的结果:

import numpy as np 
from sklearn import preprocessing
from sklearn import tree
from sklearn.tree import export_graphviz
import graphviz

# 变量定义
X = np.array([["sunny", "sunny", "overcast", "rain", "rain", "rain", "overcast", "sunny", "sunny", "rain", "sunny", "overcast", "overcast", "rain"],["hot", "hot", "hot", "mild", "cool", "cool", "cool", "mild", "cool", "mild", "mild", "mild", "hot", "mild"],["high", "high", "high", "high", "normal", "normal", "normal", "high", "normal", "normal", "normal", "high", "normal", "high"],["weak", "strong", "weak", "weak", "weak", "strong", "strong", "weak", "weak", "weak", "strong", "strong", "weak", "strong"]])
Y = np.array(["no", "no", "yes", "yes", "yes", "no", "yes", "no", "yes", "yes", "yes", "yes", "yes", "no"])

X = X.transpose()
Y = Y.transpose()

# 字符串转数值编码(独热编码)
enc = preprocessing.OneHotEncoder()
enc.fit(X)

# 查看特征中的类别
#print(enc.categories_)
Xenc = enc.transform(X).toarray()

# 输出变量编码
Yenc = Y
Yenc[Yenc == 'no'] = 0
Yenc[Yenc == 'yes'] = 1

# 训练决策树
clf = tree.DecisionTreeClassifier(max_depth=3)
clf = clf.fit(Xenc,Yenc)

# 绘制树(默认方式)
#tree.plot_tree(clf)

feat_name = ['outlook', 'temp', 'humidity', 'wind']

# 获取特征名称并生成dot数据
dot_data = export_graphviz(
    clf,
    out_file=None,
    feature_names=enc.get_feature_names(input_features=feat_name)
)

# 绘制初始决策树图
graph = graphviz.Source(dot_data)
graph.render("tree_plot")
graph

# 关联特征名称与对应类别
list(zip(feat_name, enc.categories_))


# 替换<=符号为=,调整类别显示方式
import re
new_dot = dot_data
for i, col in enumerate(feat_name):
  for cat in enc.categories_[i]:
    new_dot = re.sub(f"{col}_{cat} <= 0.5", f"{col}={cat}", new_dot)


# 切换True/False分支标签
new_dot = re.sub('labelangle=45, headlabel="True"', 'labelangle=45, headlabel="False"', new_dot)
new_dot = re.sub('labelangle=-45, headlabel="False"', 'labelangle=-45, headlabel="True"', new_dot)

# 绘制调整后的决策树图
graph = graphviz.Source(new_dot)
graph.render("tree_plot")
graph

我的输出结果

我的决策树结果

课程提供的结果

课程示例决策树结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:15:43