如何使用 spacy 在数据框的 2 列中查找句子的相似性

How to find the similarity of sentences in 2 columns of a dataframe using spacy

我从 https://spacy.io/universe/project/spacy-sentence-bert

中提取了这段代码
    import spacy_sentence_bert
    # load one of the models listed at https://github.com/MartinoMensio/spacy-sentence-bert/
    nlp = spacy_sentence_bert.load_model('en_roberta_large_nli_stsb_mean_tokens')
    # get two documents
    doc_1 = nlp('Hi there, how are you?')
    doc_2 = nlp('Hello there, how are you doing today?')
    # use the similarity method that is based on the vectors, on Doc, Span or Token
    print(doc_1.similarity(doc_2[0:7]))

我有一个包含 2 列的数据框,其中包含如下句子。我试图找到每一行中句子之间的相似性。我尝试了几种不同的方法,但运气不佳,所以我想在这里问一下。谢谢大家

当前 df

句子1 |句子2

另一个句子1 |另一个句子2

还有一个句子1 | Yet-Another-Sentence2

目标输出:

句子1 |句子2 |相似度-分数-句子 1-句子 2

另一个句子1 |另一个句子2 |相似度得分-另一个句子 1-另一个句子 2

还有一个句子1 | Yet-Another-Sentence2 |相似度分数 - 另一个句子 1 - 另一个句子 2

我假设你的第一行由headers组成,数据将从header之后的下一行开始,并假设你正在使用panda将csv转换为dataframe,以下代码适用于我的环境。

import spacy_sentence_bert
import pandas as pd
nlp = spacy_sentence_bert.load_model('en_roberta_large_nli_stsb_mean_tokens')
df = pd.read_csv('testing.csv')
similarityValue = []

for i in range(df.count()[0]):
    sentence_1 = nlp(df.iloc[i][0])
    sentence_2 = nlp(df.iloc[i][1])
    similarityValue.append(sentence_1.similarity(sentence_2))
    print(sentence_1, '|', sentence_2, '|', sentence_1.similarity(sentence_2))

df['Similarity'] = similarityValue
print(df)

输入 CSV:

输出: