使用Apache Spark在TFIDF上的余弦相似度

Ale*_*hov 1 scala tf-idf cosine-similarity apache-spark apache-spark-mllib

我正在尝试使用Apache Spark在TFIDF上计算余弦相似度矩阵。这是我的代码:

def cosSim(input: RDD[Seq[String]]) = {
  val hashingTF = new HashingTF()
  val tf = hashingTF.transform(input)
  tf.cache()
  val idf = new IDF().fit(tf)
  val tfidf = idf.transform(tf)
  val mat = new RowMatrix(tfidf)
  val sim = mat.columnSimilarities
  sim
}
Run Code Online (Sandbox Code Playgroud)

我在输入中大约有3000行,但是如果我执行sim.numRows()或sim.numCols(),我会看到1048576而不是3K,据我了解,这是因为val tfidf和val mat的大小均为3K * 1048576其中1048576是tf功能的数量。也许要解决这个问题,我必须移调垫子,但是我不知道该怎么做。

小智 5

你可以试试:

import org.apache.spark.mllib.linalg.distributed._

val irm = new IndexedRowMatrix(rowMatrix.rows.zipWithIndex.map {
   case (v, i) => IndexedRow(i, v)
})

irm.toCoordinateMatrix.transpose.toRowMatrix.columnSimilarities
Run Code Online (Sandbox Code Playgroud)