【问题标题】:Calculating cosine similarity by featurizing the text into vector using tf-idf通过使用 tf-idf 将文本特征化为向量来计算余弦相似度
【发布时间】:2015-12-15 04:51:26
【问题描述】:

我是Apache Spark的新手,想从一堆文字中找到相似的文字,自己尝试如下-

我有 2 个 RDD-

第一个 RDD 包含不完整的文本如下 -

[0,541 Suite 204, Redwood City, CA 94063]
[1,6649 N Blue Gum St, New Orleans,LA, 70116]
[2,#69, Los Angeles, Los Angeles, CA, 90034]
[3,98 Connecticut Ave Nw, Chagrin Falls]
[4,56 E Morehead Webb, TX, 78045]

第二个 RDD 包含正确的地址如下 -

[0,541 Jefferson Avenue, Suite 204, Redwood City, CA 94063]
[1,6649 N Blue Gum St, New Orleans, Orleans, LA, 70116]
[2,25 E 75th St #69, Los Angeles, Los Angeles, CA, 90034]
[3,98 Connecticut Ave Nw, Chagrin Falls, Geauga, OH, 44023]
[4,56 E Morehead St, Laredo, Webb, TX, 78045]

已经编写了这段代码,这需要很多时间,谁能告诉我在 Apache Spark 中使用 scala 执行此操作的正确方法。

val incorrect_address_count = incorrect_address_rdd.count()
val all_address = incorrect_address_rdd.union(correct_address_rdd) map (_._2.split(" ").toSeq)

val hashingTF = new HashingTF()
val tf = hashingTF.transform(all_address)
.zipWithIndex()

val input_vector_rdd = tf.filter(_._2 < incorrect_address_count)

val address_db_vector_rdd = tf.filter(_._2 >= incorrect_address_countt)
.map(f => (f._2 - input_count, f._1))
.join(correct_address_rdd)
.map(f => (f._2._1, f._2._2))

val input_similarity_rdd = input_vector_rdd.cartesian(address_db_vector_rdd)
.map(f => {

val cosine_similarity = cosineSimilarity(f._1._1.toDense, f._2._1.toDense)

(f._1._2, cosine_similarity, f._2._2)
})


def cosineSimilarity(vectorA: Vector, vectorB: Vector) = {

var dotProduct = 0.0
var normA = 0.0
var normB = 0.0
var index = vectorA.size - 1

for (i <- 0 to index) {
dotProduct += vectorA(i) * vectorB(i)
normA += Math.pow(vectorA(i), 2)
normB += Math.pow(vectorB(i), 2)
}
(dotProduct / (Math.sqrt(normA) * Math.sqrt(normB)))
}

【问题讨论】:

    标签: scala apache-spark tf-idf cosine-similarity


    【解决方案1】:

    我遇到了几乎同样的问题。我有 370K 行,每行有 2 个 300K 和 400K 的向量。我将测试 rdd 行与这两个向量相乘。

    您可以进行 2 项重大改进。一是预先计算规范。它们不会改变。其次是使用稀疏向量。如果你这样做,你可以使用 vector.size 它是 300K。如果您使用 Sparse,它会针对每个关键字进行迭代。(每行 20-30 个)。

    恐怕这是最有效的方法,因为计算不需要洗牌。如果你最后有一个好的估计,你可以按分数过滤,事情会很快。(我的意思是哪个分数对你来说就足够了。 )

    def cosineSimilarity(vectorA: SparseVector, vectorB:SparseVector,normASqrt:Double,normBSqrt:Double) :(Double,Double) = {
      var dotProduct = 0.0
      for (i <-  vectorA.indices){ 
        dotProduct += vectorA(i) * vectorB(i)
      }
      val div = (normASqrt * normBSqrt)
      if( div == 0 )
        (dotProduct,0)
      else
        (dotProduct,dotProduct / div)
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-03
      • 1970-01-01
      • 2016-10-15
      • 2015-10-06
      • 2012-11-20
      • 2018-01-28
      • 2012-04-27
      • 1970-01-01
      • 2013-02-03
      相关资源
      最近更新 更多