从成对的词移动距离得分列表构造数据帧

问题描述

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

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

我理想的数据框如下:

bool IsIpAddressOddOrEven(HttpContext context)

但是,我拥有的相似性得分列表如下所示:

[0.5,0.8,0.4]

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

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

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

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

解决方法

使用numpy创建距离矩阵,然后转换为熊猫数据框。

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)