【问题标题】:Predict middle word word2vec预测中间词 word2vec
【发布时间】: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 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。特别是,提供一个给你带来麻烦的小数据集。没有一个,不清楚问题出在算法、训练强度还是缺乏可靠数据。

标签: machine-learning word2vec


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 2022-01-03
    • 2018-09-04
    • 1970-01-01
    • 2019-07-07
    • 2023-01-27
    • 1970-01-01
    相关资源
    最近更新 更多