简体   繁体   English

如何将地图转换为Spark的RDD

[英]How to convert a map to Spark's RDD

I have a data set which is in the form of some nested maps, and its Scala type is: 我有一个数据集,它是一些嵌套映射的形式,其Scala类型是:

Map[String, (LabelType,Map[Int, Double])]

The first String key is a unique identifier for each sample, and the value is a tuple that contains the label (which is -1 or 1), and a nested map which is the sparse representation of the non-zero elements which are associated with the sample. 第一个String键是每个样本的唯一标识符,值是包含标签(-1或1)的元组,以及嵌套映射,它是与之关联的非零元素的稀疏表示样品。

I would like to load this data into Spark (using MUtil) and train and test some machine learning algorithms. 我想将这些数据加载到Spark(使用MUtil)并训练和测试一些机器学习算法。

It's easy to write this data into a file with LibSVM's sparse encoding, and then load it in Spark: 使用LibSVM的稀疏编码将此数据写入文件很容易,然后将其加载到Spark中:

writeMapToLibSVMFile(data_map,"libsvm_data.txt") // Implemeneted some where else
val conf = new SparkConf().setAppName("DecisionTree").setMaster("local[4]")
val sc = new SparkContext(conf)

// Load and parse the data file.
val data = MLUtils.loadLibSVMFile(sc, "libsvm_data.txt")
// Split the data into training and test sets
val splits = data.randomSplit(Array(0.7, 0.3))
val (trainingData, testData) = (splits(0), splits(1))

// Train a DecisionTree model.

I know it should be as easy to directly load the data variable from data_map , but I don't know how. 我知道直接从data_map加载data变量应该很容易,但我不知道如何。

Any help is appreciated! 任何帮助表示赞赏!

I guess you want something like this 我想你想要这样的东西

import org.apache.spark.rdd.RDD
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint

// If you know this upfront, otherwise it can be computed
// using flatMap
// trainMap.values.flatMap(_._2.keys).max + 1
val nFeatures: Int = ??? 

val trainMap = Map(
  "x001" -> (-1, Map(0 -> 1.0, 3 -> 5.0)),
  "x002" -> (1, Map(2 -> 5.0, 3 -> 6.0)))

val trainRdd: RDD[(String, LabeledPoint)]  = sc
  // Convert Map to Seq so it can passed to parallelize
  .parallelize(trainMap.toSeq)
  .map{case (id, (labelInt, values)) => {

      // Convert nested map to Seq so it can be passed to Vector
      val features = Vectors.sparse(nFeatures, values.toSeq)

      // Convert label to Double so it can be used for LabeledPoint
      val label = labelInt.toDouble 

      (id, LabeledPoint(label, features))
 }}

It can be done in two ways 它可以通过两种方式完成

  1. sc.textFile("libsvm_data.txt").map(s => createObject())
  2. Convert map into collection of objects and use sc.parallelize() 将map转换为对象集合并使用sc.parallelize()

The first one is preferrable. 第一个是可取的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM