注意:以下解决方案仅适用于Scala。 我没有找到在Python中执行此操作的方法。
假设您只想像示例中那样直观地表示树,也许一个选择是调整Spark
GitHub上代码中
subtreeToString存在的方法,
Node.scala以包括每个节点拆分时的概率,如以下代码片段所示:
def subtreeToString(rootNode: Node, indentFactor: Int = 0): String = { def splitToString(split: Split, left: Boolean): String = { split.featureType match { case Continuous => if (left) { s"(feature ${split.feature} <= ${split.threshold})" } else { s"(feature ${split.feature} > ${split.threshold})" } case Categorical => if (left) { s"(feature ${split.feature} in ${split.categories.mkString("{", ",", "}")})" } else { s"(feature ${split.feature} not in ${split.categories.mkString("{", ",", "}")})" } } } val prefix: String = " " * indentFactor if (rootNode.isLeaf) { prefix + s"Predict: ${rootNode.predict.predict} n" } else { val prob = rootNode.predict.prob*100D prefix + s"If ${splitToString(rootNode.split.get, left = true)} " + f"(Prob: $prob%04.2f %%)" + "n" + subtreeToString(rootNode.leftNode.get, indentFactor + 1) + prefix + s"Else ${splitToString(rootNode.split.get, left = false)} " + f"(Prob: ${100-prob}%04.2f %%)" + "n" + subtreeToString(rootNode.rightNode.get, indentFactor + 1) }}我已经在Iris数据集上运行的模型上对其进行了测试,结果如下:
scala> println(subtreeToString(model.topNode))If (feature 2 <= -0.762712) (Prob: 35.35 %) Predict: 1.0Else (feature 2 > -0.762712) (Prob: 64.65 %) If (feature 3 <= 0.333333) (Prob: 52.24 %) If (feature 0 <= -0.666667) (Prob: 92.11 %) Predict: 3.0 Else (feature 0 > -0.666667) (Prob: 7.89 %) If (feature 2 <= 0.322034) (Prob: 94.59 %) Predict: 2.0 Else (feature 2 > 0.322034) (Prob: 5.41 %) If (feature 3 <= 0.166667) (Prob: 50.00 %) Predict: 3.0 Else (feature 3 > 0.166667) (Prob: 50.00 %) Predict: 2.0 Else (feature 3 > 0.333333) (Prob: 47.76 %) Predict: 3.0
可以使用类似的方法来使用此信息创建树结构。主要的差别是存储打印的信息(
split.feature,
split.threshold,
predict.prob,等等),为瓦尔斯并使用它们来构建结构。



