预测中间词word2vec

Predict middle word word2vec

我有来自官方 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

虽然 word2vec 算法通过尝试预测单词来训练单词向量,然后这些单词向量可能用于其他目的,但如果单词预测是您的真正目标,它可能不是理想的算法。

大多数 word2vec 实现甚至没有为单个单词预测提供特定接口。在 gensim 中,predict_output_word() 是最近才添加的。它仅适用于某些模式。它对 window 的处理方式与训练期间的处理方式并不完全相同——没有有效的距离加权。而且,它相当昂贵——本质上是检查模型对每个单词的预测,然后报告前 N 个单词。 (训练期间发生的 'prediction' 是 'sparse' 并且效率更高 - 只需 运行 就足以使模型在单个示例中变得更好。)

如果单词预测是您的真正目标,您可能会从其他方法中获得更好的结果,包括仅计算一个大查找 - table 单词彼此靠近或靠近其他 n- 的频率克。