Spark MLib决策树:按功能划分标签的概率?

时间:2016-05-10 04:59:05

标签: python apache-spark decision-tree data-science

我可以设法显示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自动执行此操作,我正在尝试使用{{1}}找到一种方法

1 个答案:

答案 0 :(得分:2)

注意:以下解决方案仅适用于Scala。我没有找到用Python做的方法。

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

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等)存储为val并使用它们来构建结构。