首页 > 解决方案 > 为什么叶子中的样本数与 DecisionTreeClassifier 的父节点中的值数不匹配?

问题描述

我有一个 python 脚本,它为数据集创建一个DecisionTreeClassifier,然后绘制这棵树的图。问题是叶子中的样本数量总是与父节点中的拆分不同。例如对于根节点,它的值=[4267, 6669],但它的右侧节点只有 828 个样本。

在此处输入图像描述

这是我的代码:

# Create Decision Tree classifier object
clf = DecisionTreeClassifier(max_depth=8, min_samples_split=0.03, min_samples_leaf=0.01)

# Train Decision Tree Classifier
clf = clf.fit(X_train_ohe, y_train)

# Predict the response for test dataset
X_test_ohe = ohe.transform(X_test)
y_pred = clf.predict(X_test_ohe)

print("Accuracy:", metrics.accuracy_score(y_test, y_pred))
plt.figure(figsize=(48, 24))
plot_tree(clf,
          feature_names=ohe_df.columns,
          class_names=np.unique(y).astype('str'),
          filled=True,
          fontsize=10)

为什么会这样?

标签: pythonpython-3.xpandasscikit-learndecision-tree

解决方案


就样本数量而言(参见samples图表),具有 10,936 个样本的根节点被拆分为具有 10,108 和 828 个样本的节点,因此它加起来为 (10,108 + 828 = 10,936)。

如果您查看value(显示每个节点中每个类的样本数),您可以看到:

  • 对于第一类 ( Bad):根节点中的 4,267 是左孩子中的 3,439 和右孩子中的 828 的总和
  • 对于第二类 ( Good):6,669 是 6,669(左)和 0(右)之和

推荐阅读