gpt4 book ai didi

python - Spark MLlib 决策树 : Probability of labels by features?

转载 作者:太空宇宙 更新时间:2023-11-04 03:13:31 25 4
gpt4 key购买 nike

我可以设法显示我的标签的总概率,例如在显示我的决策树之后,我有一个表格:

Total Predictions :
65% impressions
30% clicks
5% conversions

但我的问题是通过features(通过节点)找到概率(或计数),例如:

if feature1 > 5
if feature2 < 10
Predict Impressions
samples : 30 Impressions
else feature2 >= 10
Predict Clicks
samples : 5 Clicks

Scikit 自动完成,我正在尝试找到一种方法来使用 Spark

最佳答案

注意:以下解决方案仅适用于 Scala。我没有找到在 Python 中执行此操作的方法。

假设您只是想要树的可视化表示,如您的示例所示,也许一个选择是调整 Node.scala 中存在的方法 subtreeToString Spark 的 GitHub 上的代码包含每个节点拆分的概率,如以下代码片段所示:

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 dataset 上运行的模型上对其进行了测试,我得到了以下结果:

scala> println(subtreeToString(model.topNode))

If (feature 2 <= -0.762712) (Prob: 35.35 %)
Predict: 1.0
Else (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.featuresplit.thresholdpredict.prob 等)存储为 vals并使用它们构建结构。

关于python - Spark MLlib 决策树 : Probability of labels by features?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37129602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com