pandas 数据框中的 Word2vec

Word2vec in pandas dataframe

我正在尝试应用 word2vec 来检查数据集中每行两列的相似性。

例如:

Sent1                                     Sent2
It is a sunny day                         Today the weather is good. It is warm outside
What people think about democracy         In ancient times, Greeks were the first to propose democracy  
I have never played tennis                I do not know who Roger Feder is 

为了应用word2vec,我考虑了以下几点:

import numpy as np

words1 = sentence1.split(' ')
words2 = sentence2.split(' ')
#The meaning of the sentence can be interpreted as the average of its words
sentence1_meaning = word2vec(words1[0])
count = 1
for w in words1[1:]:

    sentence1_meaning = np.add(sentence1_meaning, word2vec(w))
    count += 1
sentence1_meaning /= count

sentence2_meaning = word2vec(words1[0])
count = 1

for w in words1[1:]:
    sentence1_meaning = np.add(sentence1_meaning, word2vec(w))
    count += 1
sentence1_meaning /= count

sentence2_meaning = word2vec(words2[0])
count = 1
sentence2_meaning = word2vec(words2[0])
count = 1
for w in words2[1:]:
    sentence2_meaning = np.add(sentence2_meaning, word2vec(w))
    count += 1
sentence2_meaning /= count

#Similarity is the cosine between the vectors
similarity = np.dot(sentence1_meaning, sentence2_meaning)/(np.linalg.norm(sentence1_meaning)*np.linalg.norm(sentence2_meaning))

但是,这应该适用于不在 pandas 数据框中的两个句子。

你能告诉我在 pandas 数据帧的情况下应用 word2vec 来检查 sent1 和 sent2 之间的相似性需要做什么吗?我想要一个新的结果专栏。

我没有 word2vec 受过训练并且可用,所以我将展示如何使用伪造的 word2vec 来做你想做的事情,通过 tfidf 权重将单词转换为句子.

步骤 1。准备数据

from sklearn.feature_extraction.text import TfidfVectorizer
df = pd.DataFrame({"sentences": ["this is a sentence", "this is another sentence"]})

tfidf = TfidfVectorizer()
tfidf_matrix = tfidf.fit_transform(df.sentences).todense()
vocab = tfidf.vocabulary_
vocab
{'this': 3, 'is': 1, 'sentence': 2, 'another': 0}

步骤 2。有伪造的 word2vec(我们词汇量的大小)

word2vec = np.random.randn(len(vocab),300)

步骤3.计算一个包含句子word2vec的列:

sent2vec_matrix = np.dot(tfidf_matrix, word2vec) # word2vec here contains vectors in the same order as in vocab
df["sent2vec"] = sent2vec_matrix.tolist()
df

sentences   sent2vec
0   this is a sentence  [-2.098592110459085, 1.4292324332403232, -1.10...
1   this is another sentence    [-1.7879436822159966, 1.680865619703155, -2.00...

步骤 4. 计算相似度矩阵

from sklearn.metrics.pairwise import cosine_similarity
similarity = cosine_similarity(df["sent2vec"].tolist())
similarity
array([[1.        , 0.76557098],
       [0.76557098, 1.        ]])

为了使 word2vec 正常工作,您需要稍微调整第 2 步,以便 word2vec 以相同的顺序包含 vocab 中的所有单词(由值指定,或按字母顺序)。

对于你的情况应该是:

sorted_vocab = sorted([word for word,key in vocab.items()])
sorted_word2vec = []
for word in sorted_vocab:
    sorted_word2vec.append(word2vec[word])