簡體   English   中英

如何將隨機rdd加入另一個rdd?

[英]How to join a random rdd to another rdd?

我有一個RDD字符串(但實際上可以是任何東西),我想與rdd隨機法線進行內部連接。 我知道這可以在兩個RDD上都使用.zipWithIndex來解決,但這似乎無法很好地擴展,是否有一種方法可以用來自另一個RDD數據或另一個更快的方法來初始化隨機rdd 這是我對.zipWithIndex所做的工作:

import org.apache.spark.mllib.random.RandomRDDs
import org.apache.spark.rdd.RDD

val numExamples = 10 // number of rows in RDD 
val maNum   = 7
val commonStdDev   = 0.1 // common standard deviation 1/10, makes variance = 0.01
val normalVectorRDD = RandomRDDs.normalVectorRDD(sc, numRows = numExamples, numCols = maNum) 
val rescaledNormals = normalVectorRDD.map{myVec => myVec.toArray.map(x => x*commonStdDev)}
  .zipWithIndex
  .map{case (key,value) => (value,(key))} 

val otherRDD = sc.textFile(otherFilepath)
  .zipWithIndex
  .map{case (key,value) => (value,(key))} 

val joinedRDD = otherRDD.join(rescaledNormals).map{case(key,(other,dArray)) => (other,dArray)}

通常,我不會擔心zipWithIndex 盡管它需要其他操作,但它屬於相對便宜的操作。 但是join是另一回事。

由於向量內容不依賴於otherRDD的值,因此otherRDD生成向量更有意義。 您要做的就是模仿RandomRDDs邏輯:

import org.apache.spark.mllib.random.StandardNormalGenerator 
import org.apache.spark.ml.linalg.DenseVector  // or org.apache.spark.mllib

val vectorSize = 42
val stdDev = 0.1
val seed = scala.util.Random.nextLong  // Or set manually

// Define seeds for each partition
val random = new scala.util.Random(seed)
val seeds = (0 until otherRDD.getNumPartitions).map(
  i => i -> random.nextLong
).toMap

otherRDD.mapPartitionsWithIndex((i, iter) => {
  val generator = new StandardNormalGenerator()
  generator.setSeed(seeds(i))
  iter.map(x => 
    (x, new DenseVector(Array.fill(vectorSize)(generator.nextValue() * stdDev)))
  )
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM