我在Spark MLlib中有一个分类模型,它是使用训练数据构建的。现在我想用它来预测未标记的数据。
我有LIBSVM格式的功能(没有标签)。这是我的未标记数据的样本
的示例1:1 18:1
4:1 32:1
2:1 8:1 33:1
1:1 6:1 11:1
1:1 2:1 8:1 28:1
我将这些功能保存在HDFS上的文本文件中。如何在RDD [Vector]中加载它们,以便将它们传递给model.predict()?
我使用Scala进行编码。
感谢。
答案 0 :(得分:2)
这是一个解决方案,考虑到索引是一个基于升序的。
让我们创建一些类似于文本文件中的虚拟数据。
val data = sc.parallelize(Seq("1:1 18:1", "4:1 32:1", "2:1 8:1 33:1", "1:1 6:1 11:1", "1:1 2:1 8:1 28:1"))
我们现在可以将数据转换为带有索引和值的RDD
对。
val parsed = data.map(_.trim).map { line =>
val items = line.split(' ')
val (indices, values) = items.filter(_.nonEmpty).map { item =>
val indexAndValue = item.split(':')
val index = indexAndValue(0).toInt - 1 // Convert 1-based indices to 0-based.
val value = indexAndValue(1).toDouble
(index, value)
}.unzip
(indices.toArray, values.toArray)
}
获取功能数量
val numFeatures = parsed.map { case (indices, values) => indices.lastOption.getOrElse(0) }.reduce(math.max) + 1
最后创建向量
val vectors = parsed.map { case (indices, values) => Vectors.sparse(numFeatures, indices, values) }
vectors.take(10) foreach println
// (33,[0,17],[1.0,1.0])
// (33,[3,31],[1.0,1.0])
// (33,[1,7,32],[1.0,1.0,1.0])
// (33,[0,5,10],[1.0,1.0,1.0])
// (33,[0,1,7,27],[1.0,1.0,1.0,1.0])