Scala 在Apache Spark中使用RowMatrix.ColumnComparison后打印坐标矩阵

Scala 在Apache Spark中使用RowMatrix.ColumnComparison后打印坐标矩阵,scala,apache-spark,apache-spark-mllib,Scala,Apache Spark,Apache Spark Mllib,我正在为我的一个项目使用spark mllib,其中我需要计算文档的相似性 我首先使用mllib的tf idf转换将文档转换为向量,然后将其转换为RowMatrix并使用columnComplomics()方法 我参考了文档并使用了余弦相似性的实现 在spark shell中,这是执行的scala代码: import org.apache.spark.rdd.RDD import org.apache.spark.SparkContext import org.apache.spark.mlli

我正在为我的一个项目使用spark mllib,其中我需要计算文档的相似性

我首先使用mllib的tf idf转换将文档转换为向量,然后将其转换为RowMatrix并使用columnComplomics()方法

我参考了文档并使用了余弦相似性的实现

在spark shell中,这是执行的scala代码:

import org.apache.spark.rdd.RDD
import org.apache.spark.SparkContext
import org.apache.spark.mllib.feature.HashingTF
import org.apache.spark.mllib.linalg.Vector
import org.apache.spark.mllib.feature.IDF
import org.apache.spark.mllib.linalg.distributed.RowMatrix

val documents = sc.textFile("test1").map(_.split(" ").toSeq)
val hashingTF = new HashingTF()

val tf = hashingTF.transform(documents)
tf.cache()

val idf = new IDF().fit(tf)
val tfidf = idf.transform(tf)

// now use the RowMatrix to compute cosineSimilarities
// which implements DIMSUM algorithm

val mat = new RowMatrix(tfidf)
val sim = mat.columnSimilarities() // returns a CoordinateMatrix
现在让我们假设我的
输入文件
,这个代码块中的
test1
是一个简单的文件,有5个简短的文档(每个文档少于10个术语),每行一个

因为我刚刚测试了这段代码,所以我想看看object
sim
中的
mat.columnComplomics()
的输出。 我想查看第一个文档向量与第二个、第三个等的相似性。

我为
CoordinateMatrix
引用了spark,它是
RowMatrix
类的
ColumnComparison
方法返回的对象类型,由
sim
引用

通过阅读更多文档,我想我可以将CoordinateMatrix转换为RowMatrix,然后将RowMatrix的行转换为数组,然后像这样打印
println(sim.toRowMatrix().rows.toArray().mkString(“\n”)

但这会产生一些我无法理解的输出

有人能帮忙吗?任何类型的资源链接等将帮助很多


谢谢

您可以尝试以下操作,无需转换为行矩阵格式

val transformedRDD = sim.entries.map{case MatrixEntry(row: Long, col:Long, sim:Double) => Array(row,col,sim).mkString(",")}
要检索元素,可以调用以下操作

transformedRDD.collect()

非常感谢。我要试试这个!当我运行transformeddd.saveAsTextFile(“…”)并打开输出文件时,我看到多个三元组。我不知道这些三胞胎是什么@pranav3688三元组是columnComplomics()方法的输出,它的格式是row id、column id和themok之间的相似性,但是我的输入文件有5行,所以我有5个文档向量。行矩阵也有5行。但是当我运行columnComparison()时,生成的坐标矩阵有12行(12个不同的行ID)。仍然不确定发生了什么。
sim
引用的
CoordinateMatrix
有1048576行和1048576列。由
mat
引用的
RowMatrix
有5行和1048576列。我以为
sim
将有5行5列。请确保您已验证是否转置了tdif RowMatrix