TextRank algorithm using Spark的实现(Calculating cosine similarity matrix using spark)

Implementation of TextRank algorithm using Spark(Calculating cosine similarity matrix using spark)

我正在尝试实现 textrank 算法,我正在计算所有 sentences.I 的余弦相似度矩阵,想并行化使用 Spark 创建相似度矩阵的任务,但不知道如何实现 it.Here 是代码:

    cluster_summary_dict = {}
    for cluster,sentences in tqdm(cluster_wise_sen.items()):
        sen_sim_matrix = np.zeros([len(sentences),len(sentences)])
        for row in range(len(sentences)):
            for col in range(len(sentences)):
                if row != col:
                    sen_sim_matrix[row][col] = cosine_similarity(cluster_dict[cluster]  
                                               [row].reshape(1,100), cluster_dict[cluster] 
                                               [col].reshape(1,100))[0,0]
        sentence_graph = nx.from_numpy_array(sen_sim_matrix)
        scores = nx.pagerank(sentence_graph) 
        pagerank_sentences = sorted(((scores[k],sent) for k,sent in enumerate(sentences)), 
                             reverse=True)
        cluster_summary_dict[cluster] = pagerank_sentences

这里,cluster_wise_sen 是一个包含不同集群的句子列表的字典({'cluster 1' : [句子列表] ,...., 'cluster n' : [列表的句子]})。 cluster_dict 包含句子的 100d 向量表示。我必须为每个集群计算句子相似度矩阵。由于它很耗时,因此希望使用 spark 对其进行并行化。

余弦相似度的大规模矩阵计算实验写的很好 here!

为了在不影响准确性的情况下提高速度,您还可以尝试使用 Min-Hash 等哈希方法并评估 Jaccard 距离相似度。它带有一个很好的 Spark ML-lib 实现,文档中有非常详细的示例供参考:http://spark.apache.org/docs/latest/ml-features.html#minhash-for-jaccard-distance