Pyspark:将 RDD 转换为 RowMatrix

Pyspark: Converting RDD to RowMatrix

我有一个形式为 (id1,id2,score) 的 RDD。前 (5) 行看起来像

[(41955624, 42044497, 3.913625989045223e-06),
(41955624, 42039940, 0.0001018890937469129),
(41955624, 42037797, 7.901647831291928e-05),
(41955624, 42011137, -0.00016191403038589588),
(41955624, 42006663, -0.0005302800991148567)]

我想根据分数计算id2成员之间的相似度。我想使用 RowMatrix.columnSimilarity,但我需要先将其转换为 RowMatrix。我希望矩阵的结构为 id1 x id2——即,从 id1 中创建行 ID,从 id2 中创建列 ID。

如果我的数据较小,我可以将其转换为 Pyspark 数据框,然后使用类似

的数据透视表
rdd_df.groupBy("id1").pivot("id2").sum("score")

但这有超过 10,000 个不同的 id2,而我拥有的远不止这些。

天真 rdd_Mat = la.RowMatrix(红色) 将数据作为 3 列矩阵引入,这不是我想要的。

非常感谢。

您的数据结构更类似于 CoordinateMatrix 的结构,它基本上是 (long, long, float) 元组 RDD 的包装器。因此,您可以非常轻松地从现有 RDD 创建 CoordinetMatrix

from pyspark.mllib.linalg.distributed import CoordinateMatrix

cmat=CoordinateMatrix(yourRDD)

此外,由于您最初要求 RowMatrix,pyspark 提供了一种在矩阵类型之间轻松转换的方法:

rmat=cmat.toRowMatrix()

给你想要的 RowMatrix.