使用分区中的数据训练分类器



如何在分区内的分类算法取决于分区索引的情况下使用分区内的实例训练分类器?例如,假设以下代码片段:

val data = MLUtils.loadLibSVMFile(sc, "path to SVM file")
val r = data.mapPartitionsWithIndex((index,localdata)=>{
if (index % 2 == 0)
{
// train a NaiveBayes with localdata
NaiveBayes.train(localdata)    // Error => found:iterator[LabeledPoint] , required: RDD[labeledPoint]
}
else
{
// train a DecisionTree classifier with localdata
DecisionTree.train(localdata)    // Error => found:iterator[LabeledPoint] , required: RDD[labeledPoint]
}
})

在我看来,错误是正确的,因为这些任务是在其单独的 JVM 中执行的,并且无法从映射任务分发。这就是为什么我无法在任务中访问SparkContext的原因。但是,有没有人对我的目的有其他建议?

基于上述评论部分的讨论 - 你可以试试这个——

val rdd = MLUtils.loadLibSVMFile(sc, "path to SVM file")
// approach -1
val nb = rdd.sample(withReplacement = false, fraction = 0.5) // sample 50% of the record
val dt = rdd.sample(withReplacement = false, fraction = 0.5) // sample 50% of the record
//or approach-2 
val (nb, dt) = rdd.randomSplit(Array(0.5, 0.5))
// apply algo
NaiveBayes.train(nb)
DecisionTree.train(dt, strategy= ..)

最新更新