我有官方github仓库中的predict_output_word方法。它只采用用skip-gram训练过的wod2vec模型,并尝试通过将所有输入词的索引的向量相加来预测中间词,并且通过输入词索引的np_sum的长度来分割该中间词。然后,考虑输出并采用softmax获得预测词的概率,然后将所有这些概率相加得到最可能的单词。有没有更好的方法来处理这个问题,以获得更好的单词,因为这给较短的句子带来了非常不好的结果。下面的代码是github的代码。预测中间词word2vec
def predict_output_word(model, context_words_list, topn=10):
from numpy import exp, dtype, float32 as REAL,\
ndarray, empty, sum as np_sum,
from gensim import utils, matutils
"""Report the probability distribution of the center word given the context words as input to the trained model."""
if not model.negative:
raise RuntimeError("We have currently only implemented predict_output_word "
"for the negative sampling scheme, so you need to have "
"run word2vec with negative > 0 for this to work.")
if not hasattr(model.wv, 'syn0') or not hasattr(model, 'syn1neg'):
raise RuntimeError("Parameters required for predicting the output words not found.")
word_vocabs = [model.wv.vocab[w] for w in context_words_list if w in model.wv.vocab]
if not word_vocabs:
warnings.warn("All the input context words are out-of-vocabulary for the current model.")
return None
word2_indices = [word.index for word in word_vocabs]
#sum all the indices
l1 = np_sum(model.wv.syn0[word2_indices], axis=0)
if word2_indices and model.cbow_mean:
#l1 = l1/len(word2_indices)
l1 /= len(word2_indices)
prob_values = exp(dot(l1, model.syn1neg.T)) # propagate hidden -> output and take softmax to get probabilities
prob_values /= sum(prob_values)
top_indices = matutils.argsort(prob_values, topn=topn, reverse=True)
return [(model.wv.index2word[index1], prob_values[index1]) for index1 in top_indices] #returning the most probable output words with their probabilities
欢迎来到StackOverflow。请阅读并遵守帮助文档中的发布准则。 [最小,完整,可验证的示例](http://stackoverflow.com/help/mcve)适用于此处。在发布您的MCVE代码并准确描述问题之前,我们无法为您提供有效的帮助。 我们应该能够将发布的代码粘贴到文本文件中,并重现您描述的问题。特别是,提供一个小数据集,给你带来麻烦。没有一个,目前还不清楚问题是算法,训练的强度还是缺乏可靠的数据。 – Prune