众所周知,Spark 中的 GBT 现在可以给出预测标签。
我想尝试计算一个类别的预测概率(比如说所有落在特定叶子节点下的实例)。
构建 GBT 的代码:
import org.apache.spark.SparkContext
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.tree.GradientBoostedTrees
import org.apache.spark.mllib.tree.configuration.BoostingStrategy
import org.apache.spark.mllib.tree.model.GradientBoostedTreesModel
import org.apache.spark.mllib.util.MLUtils
//Importing the data
val data = sc.textFile("data/mllib/credit_approval_2_attr.csv") //using the credit approval data set from UCI machine learning repository
//Parsing the data
val parsedData = data.map { line =>
val parts = line.split(',').map(_.toDouble)
LabeledPoint(parts(0), Vectors.dense(parts.tail))
}
//Splitting the data
val splits = parsedData.randomSplit(Array(0.7, 0.3), seed = 11L)
val training = splits(0).cache()
val test = splits(1)
// Train a GradientBoostedTrees model.
// The defaultParams for Classification use LogLoss by default.
val boostingStrategy = BoostingStrategy.defaultParams("Classification")
boostingStrategy.numIterations = 2 // We can use more iterations in practice.
boostingStrategy.treeStrategy.numClasses = 2
boostingStrategy.treeStrategy.maxDepth = 2
boostingStrategy.treeStrategy.maxBins = 32
boostingStrategy.treeStrategy.subsamplingRate = 0.5
boostingStrategy.treeStrategy.maxMemoryInMB =1024
boostingStrategy.learningRate = 0.1
// Empty categoricalFeaturesInfo indicates all features are continuous.
boostingStrategy.treeStrategy.categoricalFeaturesInfo = Map[Int, Int]()
val model = GradientBoostedTrees.train(training, boostingStrategy)
model.toDebugString
为了简单起见,这给我两棵深度为2的树,如下所示:
Tree 0:
If (feature 3 <= 2.0)
If (feature 2 <= 1.25)
Predict: -0.5752212389380531
Else (feature 2 > 1.25)
Predict: 0.07462686567164178
Else (feature 3 > 2.0)
If (feature 0 <= 30.17)
Predict: 0.7272727272727273
Else (feature 0 > 30.17)
Predict: 1.0
Tree 1:
If (feature 5 <= 67.0)
If (feature 4 <= 100.0)
Predict: 0.5739387416147804
Else (feature 4 > 100.0)
Predict: -0.550117566730937
Else (feature 5 > 67.0)
If (feature 2 <= 0.0)
Predict: 3.0383669122382835
Else (feature 2 > 0.0)
Predict: 0.4332824083446489
我的问题是:我能否使用以上树来计算预测概率,如下所示:
针对用于预测的特征集中的每个实例
exp(来自树0的叶子分数+来自树1的叶子分数)/(1+exp(来自树0的叶子分数+来自树1的叶子分数))
这给了我一种概率。但不确定是否是正确的方法。而且如果有任何文件解释如何计算叶子分数(预测),如果有人分享,我会非常感激。
任何建议都将是非常棒的。