gpt4 book ai didi

apache-spark - 如何计算 Spark 中的距离矩阵?

转载 作者:行者123 更新时间:2023-12-04 03:58:58 25 4
gpt4 key购买 nike

我试过配对样本,但它需要大量的内存,因为 100 个样本导致 9900 个样本,这更昂贵。在spark分布式环境中计算距离矩阵的更有效方法是什么

这是我正在尝试的伪代码片段

val input = (sc.textFile("AirPassengers.csv",(numPartitions/2)))
val i = input.map(s => (Vectors.dense(s.split(',').map(_.toDouble))))
val indexed = i.zipWithIndex() //Including the index of each sample
val indexedData = indexed.map{case (k,v) => (v,k)}

val pairedSamples = indexedData.cartesian(indexedData)

val filteredSamples = pairedSamples.filter{ case (x,y) =>
(x._1.toInt > y._1.toInt) //to consider only the upper or lower trainagle
}
filteredSamples.cache
filteredSamples.count

上面的代码创建了对,但即使我的数据集包含 100 个样本,通过配对过滤样本(以上)会产生 4950 个样本,这对于大数据来说可能非常昂贵

最佳答案

我最近回答了一个类似的question .

基本上,它会到达计算n(n-1)/2对,即 4950你的例子中的计算。但是,这种方法的不同之处在于我使用连接而不是 cartesian .使用您的代码,解决方案如下所示:

val input = (sc.textFile("AirPassengers.csv",(numPartitions/2)))
val i = input.map(s => (Vectors.dense(s.split(',').map(_.toDouble))))
val indexed = i.zipWithIndex()

// including the index of each sample
val indexedData = indexed.map { case (k,v) => (v,k) }

// prepare indices
val count = i.count
val indices = sc.parallelize(for(i <- 0L until count; j <- 0L until count; if i > j) yield (i, j))

val joined1 = indices.join(indexedData).map { case (i, (j, v)) => (j, (i,v)) }
val joined2 = joined1.join(indexedData).map { case (j, ((i,v1),v2)) => ((i,j),(v1,v2)) }

// after that, you can then compute the distance using your distFunc
val distRDD = joined2.mapValues{ case (v1, v2) => distFunc(v1, v2) }

试试这个方法并将其与您已经发布的方法进行比较。希望这可以稍微加速您的代码。

关于apache-spark - 如何计算 Spark 中的距离矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37809834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com