首页 文章

预测中间词word2vec

提问于
浏览
1

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

1 回答

  • 1

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

    大多数word2vec实现甚至没有为单个单词预测提供特定的接口 . 在gensim中, predict_output_word() 最近才被添加 . 它仅适用于某些模式 . 它并没有像训练期间那样对待 window - 对每个单词进行预测,然后报告前N个 . (在培训期间发生的'prediction'更加高效 - 只需运行足够的模型就可以在单个示例中推动它更好 . )

    如果单词预测是你真正的目标,你可以从其他方法中获得更好的结果,包括只计算一个大的查找表,其中常常出现在其他n-gram附近或接近其他n-gram的单词 .

相关问题