【问题标题】:Construct dataframe from pairwise Word Mover Distance score list从成对的 Word Mover 距离得分列表构建数据框
【发布时间】:2020-08-21 02:32:15
【问题描述】:

我想对我拥有的成对句子距离(单词移动距离)列表进行 PCA 分析。到目前为止,我已经得到了每对句子的相似度分数。将所有成对相似度得分存储在一个列表中。我的主要问题是:

如何构造一个包含这些与原始句子索引的相似度得分的矩阵?目前,该列表仅包含每对的分数。还没有找到将分数映射回句子本身的方法。

我理想的数据框如下所示:

>             Sentence1  Sentence2  Sentence3   
 Sentence1.     1          0.5        0.8
 Sentence2      0.5        1          0.4
 Sentence3      0.8        0.4        1

但是,我的相似度得分列表看起来像这样,没有索引:

[0.5, 0.8, 0.4]

如何将其转换为可以在其上运行 PCA 的数据帧?谢谢!

----构建成对相似度得分的步骤

# Tokenize all sentences in a column
tokenized_sentences = [s.split() for s in df[col]]

# calculate distance between 2 responses using wmd
def find_similar_docs(sentence_1, sentence_2):
   distance = model.wv.wmdistance(sentence_1, sentence_2)
   return distance

# find response pairs
pairs_sentences = list(combinations(tokenized_sentences, 2))

# get all similiarity scores between sentences
list_of_sim = []
for sent_pair in pairs_sentences:
   sim_curr_pair = find_similar_docs(sent_pair[0], sent_pair[1])
   list_of_sim.append(sim_curr_pair)

如果我有“1”而不是标记化的句子([“I”,“open”,“communication”,“culture”])作为索引会容易得多。 :) 所以我有点卡在这里......

【问题讨论】:

    标签: python matrix nlp word-embedding


    【解决方案1】:

    用 numpy 制作距离矩阵,然后转换为 pandas 数据框。

    import numpy as np
    import pandas as pd
    
    # calculate distance between 2 responses using wmd
    def find_similar_docs(sentence_1, sentence_2):
        distance = model.wv.wmdistance(sentence_1, sentence_2)
        return distance
      
    # create distance matrix
    tokenized_sentences = [s.split() for s in df[col]]
    l = len(tokenized_sentences)
    distances = np.zeros((l, l))
    for i in range(l):
        for j in range(l):
            distances[i, j] = find_similar_docs(tokenized_sentences[i], tokenized_sentences[j])
    
    # make pandas dataframe
    labels = ['sentence' + str(i + 1) for i in range(l)]
    df = pd.DataFrame(data=distances, index=labels, columns=labels)
    print(df)
    

    【讨论】:

    • 谢谢!我想使用与这些分数相关的原始索引。例如,可能是 sentence_2,而 sentence_4 与 0.5 相关联。有没有办法让我检索这些信息并将其用作标签?
    • 我需要知道如何创建相似度得分列表来获取原始标签/索引。
    • 感谢您的建议!刚刚更新了我原来的帖子。
    • 谢谢! 3小时后,成功了!快速跟进问题,列名是“sentence 1”,“sentence 2”。你知道我是否有办法追溯到原始数据框中的句子 1 指的是哪个句子?再次感谢!
    • Sentence1 将等同于 tokenized_sentences[0]
    猜你喜欢
    • 2017-09-12
    • 2020-04-22
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 2018-08-05
    • 2019-12-25
    • 1970-01-01
    • 2021-09-29
    相关资源
    最近更新 更多