如何在Spark Pipeline中使用RandomForest

bou*_*eli 4 pipeline random-forest apache-spark apache-spark-ml apache-spark-mllib

我想通过网格搜索和使用spark交叉验证来调整我的模型.在火花中,它必须将基础模型放在管道中,管道的办公室演示使用LogistictRegression作为基础模型,它可以是新的对象.但是,客户端代码RandomForest不能使用模型,因此似乎无法RandomForest在管道api中使用.我不想重新创建一个轮子,所以有人可以给出一些建议吗?谢谢

zer*_*323 5

但是,RandomForest模型不能是客户端代码的新模型,因此似乎无法在管道API中使用RandomForest.

嗯,这是真的,但你只是想尝试使用错误的类.而不是mllib.tree.RandomForest你应该使用ml.classification.RandomForestClassifier.这是一个基于MLlib文档的示例.

import org.apache.spark.ml.classification.RandomForestClassifier
import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.feature.StringIndexer
import org.apache.spark.mllib.linalg.Vector
import org.apache.spark.mllib.util.MLUtils
import sqlContext.implicits._ 

case class Record(category: String, features: Vector)

val data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt")
val splits = data.randomSplit(Array(0.7, 0.3))
val (trainData, testData) = (splits(0), splits(1))

val trainDF = trainData.map(lp => Record(lp.label.toString, lp.features)).toDF
val testDF = testData.map(lp => Record(lp.label.toString, lp.features)).toDF

val indexer = new StringIndexer()
  .setInputCol("category")
  .setOutputCol("label")

val rf  = new RandomForestClassifier()
    .setNumTrees(3)
    .setFeatureSubsetStrategy("auto")
    .setImpurity("gini")
    .setMaxDepth(4)
    .setMaxBins(32)

val pipeline = new Pipeline()
    .setStages(Array(indexer, rf))

val model = pipeline.fit(trainDF)

model.transform(testDF)
Run Code Online (Sandbox Code Playgroud)

有一件事我在这里无法弄清楚.据我所知,应该可以使用LabeledPoints直接提取的标签,但由于某种原因它不起作用并pipeline.fit引发IllegalArgumentExcetion:

给RandomForestClassifier输入了无效的标签列标签,没有指定的类数.

因此,这个丑陋的伎俩StringIndexer.在应用之后,我们得到了必需的属性({"vals":["1.0","0.0"],"type":"nominal","name":"label"}),但是有些类ml似乎没有它就可以正常工作.