1.使用gensim包中的word2vec模型对每个句子中的单词进行向量化处理。
2.对每个句子或文档中的所有单词计算平均向量。
import numpy as np
from scipy import spatial
index2word_set = set(model.wv.index2word)
def avg_feature_vector(sentence, model, num_features, index2word_set):
words = sentence.split()
feature_vec = np.zeros((num_features, ), dtype='float32')
n_words = 0
for word in words:
if word in index2word_set:
n_words += 1
feature_vec = np.add(feature_vec, model[word])
if (n_words > 0):
feature_vec = np.divide(feature_vec, n_words)
return feature_vec
3. 接下来计算这两个平均向量之间的余弦相似度。
s1_afv = avg_feature_vector('this is a sentence', model=model,
num_features=300, index2word_set=index2word_set)
s2_afv = avg_feature_vector('this is also sentence', model=model,
num_features=300, index2word_set=index2word_set)
sim = 1 - spatial.distance.cosine(s1_afv, s2_afv)
print(sim)
参考stackoverflow问题: 如何使用gensim中的word2vec模型和Python计算句子相似度
需要以下挑战的帮助:
我想创建一个模型,可以预测两个句子之间的语义相似性,但我不确定:
1.哪种模型最适合此问题
2.更重要的是如何训练该模型?
我应该创建一个矩阵,其中每行将包含两个句子:sen1和sen2,并对它们进行向量化并计算余弦相似度(根据上述方法)吗?
然后对于训练数据:
X_Train:sen1和sen2的平均向量及其余弦相似度值
y_Train(prediction):一组二进制值(如果余弦相似度> 0.7,则为1或类似值,否则为0)
我很困惑我的方法是否正确以及如何以可工作的代码形式提出正确的方法。
因为互联网和在线材料是我学习ML的唯一教师,所以请求您的指导,帮助我消除理解上的差距,并帮忙为我的问题提供一个良好的工作模型。