【问题标题】:Spark MLib Decision Trees: Probability of labels by features?Spark MLlib 决策树:按特征划分标签的概率?
【发布时间】:2016-09-04 21:42:58
【问题描述】:

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

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 吗?
  • @DanieldePaula ,是的,没关系。
  • 我对 Scala 有一个想法。有时间我会和你分享

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


【解决方案1】:

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

假设您只想像示例中那样直观地表示树,也许一种选择是调整 Spark GitHub 上 Node.scala 代码中的 subtreeToString 方法,以包含每个节点拆分的概率,例如以下sn-p:

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 并使用它们来构建结构。

【讨论】:

猜你喜欢
  • 2016-11-06
  • 2017-10-18
  • 2012-08-04
  • 2020-12-03
  • 2016-10-07
  • 2017-07-11
  • 2018-05-15
  • 2020-04-02
  • 2017-03-24
相关资源
最近更新 更多