【发布时间】:2017-07-14 12:01:35
【问题描述】:
我有来自官方 github 存储库的 predict_output_word 方法。它只需要用skip-gram训练的wod2vec模型,并尝试通过对所有输入词的索引的向量求和来预测中间词和 将其除以输入单词索引的 np_sum 的长度。然后你考虑输出并在你将所有这些概率相加得到最可能的词之后,使用 softmax 来得到预测词的概率。有没有更好的方法来解决这个问题以获得更好的单词,因为这会给较短的句子带来非常糟糕的结果。 下面是来自github的代码。
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。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。特别是,提供一个给你带来麻烦的小数据集。没有一个,不清楚问题出在算法、训练强度还是缺乏可靠数据。