scala - 如何将 RDD 中的每个元素与 RDD 中的每个其他元素进行比较?

标签 scala apache-spark nearest-neighbor

我正在尝试使用 spark 执行 K 最近邻搜索。

我有一个 RDD[Seq[Double]] 并且我打算返回一个
RDD[(Seq[Double],Seq[Seq[Double]])]
带有实际行和邻居列表

val out = data.map(row => {
    val neighbours = data.top(num = 3)(new Ordering[Seq[Double]] {
      override def compare(a:Seq[Double],b:Seq[Double]) = {
        euclideanDistance(a,row).compare(euclideanDistance(b,row))*(-1)
      }
    })
  (row,neighbours.toSeq)
})

它在 spark 提交时出现以下错误
15/04/29 21:15:39 WARN TaskSetManager: Lost task 0.0 in stage 1.0 (TID 2, 192.168.1.7): org.apache.spark.SparkException: RDD transformations and actions can only be invoked by the driver, not inside of other transformations; for example, rdd1.map(x => rdd2.values.count() * x) is invalid because the values transformation and count action cannot be performed inside of the rdd1.map transformation. For more information, see SPARK-5063.

我知道嵌套 RDD 是不可能的,但是我如何执行这样的操作,我可以将 RDD 中的每个元素与 RDD 中的每个其他元素进行比较

最佳答案

像这样的事情应该这样做。

import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.spark.rdd.RDD

val conf = new SparkConf().setAppName("spark-scratch").setMaster("local")
val sco= new SparkContext(conf)

// k is the number of nearest neighbors required 
val k = 3

// generate 5 rows of two-dimensional coordinates
val rows = List.fill(5)(List.fill(2)(Math.random))
val dataRDD = sco.parallelize(rows, 1)

// No need for the sqrt as we're just comparing them
def euclidean(a:List[Double], b:List[Double]) = 
 (a zip b) map {case (x:Double, y:Double) => (x-y)*(x-y)} sum

// get all pairs
val pairs = dataRDD.cartesian(dataRDD)

// case class to keep things a bit neater
// the neighbor, and its distance from the current point
case class Entry(neighbor: List[Double], dist:Double)

// map the second element to the element and distance from the first
val pairsWithDist = pairs.map {case (x, y) => (x, Entry(y, euclidean(x,y)))}

// merge a row of pairsWithDist with the ResultRow for this point
def mergeOne(u: List[Entry], v:Entry) = (v::u).sortBy{_.dist}.take(k)

// merge two results from different partitions
def mergeList(u: List[Entry], v:List[Entry]) = (u:::v).sortBy{_.dist}.take(k)

val nearestNeighbors = pairsWithDist
                      .aggregateByKey(List[Entry]())(mergeOne, mergeList)

关于scala - 如何将 RDD 中的每个元素与 RDD 中的每个其他元素进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29948746/

相关文章:

algorithm - 查找与输入数组具有最大交集的数组的有效方法

java - Scala类继承和方法参数

scala - 是否可以等到 EMR 集群终止?

apache-spark - 嵌套 json 中的结构化流式传输不同模式

arrays - matlab获取矩阵上的邻居

SQL 高效最近邻查询

java - 未找到 Spark RDD 类

scala - 为什么这个案例类可以容纳比它声明的更多的参数?

apache-spark - Spark NLP 中的多语言 bert

apache-spark - 对组内的 pyspark 数据框进行排序