Spark:如何使用训练数据集执行预测(MLLIB:SVMWithSGD)

时间:2014-10-18 05:14:22

标签: apache-spark prediction

我是Spark的新手。我能够训练DataSet。但是无法使用经过训练的数据集进行预测。

以下是训练数据的代码,即1800x4000矩阵。

import org.apache.spark.mllib.classification.SVMWithSGD
import org.apache.spark.mllib.regression.LinearRegressionWithSGD
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.linalg.Vectors

// Load and parse the data
val data = sc.textFile("data/mllib/ridge-data/myfile.txt")
val parsedData = data.map { line =>
  val parts = line.split(' ')
  LabeledPoint(parts(0).toDouble, Vectors.dense(parts(1).split(' ').map(_.toDouble)))
}

val firstDataPoint = parsedData.take(1)(0)

// Building the model
val numIterations = 100
val model = SVMWithSGD.train(parsedData, numIterations)
//val model = LinearRegressionWithSGD.train(parsedData,numIterations)


val labelAndPreds = parsedData.map { point =>
  val prediction = model.predict(point.features)
  (point.label, prediction)
}
val trainErr = labelAndPreds.filter(r => r._1 != r._2).count.toDouble / parsedData.count
println("Training Error = " + trainErr)

现在我加载要用于执行预测的数据:数据是1800值的向量

val test = sc.textFile("data/mllib/ridge-data/data.txt")

但不确定如何使用此数据执行预测。请帮忙。

1 个答案:

答案 0 :(得分:0)

首先从textFile加载labeledPoints(请记住,你必须使用saveAsTextFile保存RDD):

JavaRDD<LabeledPoint> test = MLUtils.loadLabeledPoints(init.context, "hdfs://../test/", 30).toJavaRDD();
JavaRDD<Tuple2<Object, Object>> scoreAndLabels = test.map(
  new Function<LabeledPoint, Tuple2<Object, Object>>() {
    public Tuple2<Object, Object> call(LabeledPoint p) {
      Double score = model.predict(p.features());
      return new Tuple2<Object, Object>(score, p.label());
    }
  }
);

现在收集分数并迭代它们:

List<Tuple2<Object, Object>> scores = scoreAndLabels.collect();
    for(Tuple2<Object, Object> score : scores){
    System.out.println(score._1 + " \t" + score._2);
}

它是Java,但也许你可以转换它:)

但预测值没有意义: -18.841544889249917 0.0 168.32916035523283 1.0 420.67763915879794 1.0 -974.1942589201286 0.0 71.73602841256813 1.0 233.13636224524993 1.0 -1000.5902168199027 0.0 有人知道他们的意思吗?