【问题标题】:Gensim: raise KeyError("word '%s' not in vocabulary" % word)Gensim: raise KeyError("单词 '%s' 不在词汇表中" % word)
【发布时间】:2018-09-02 17:21:53
【问题描述】:

我有这个代码,我有文章列表作为数据集。每个raw都有一篇文章。

我运行这段代码:

import gensim    
docgen = TokenGenerator( raw_documents, custom_stop_words )    
# the model has 500 dimensions, the minimum document-term frequency is 20    
w2v_model = gensim.models.Word2Vec(docgen, size=500, min_count=20, sg=1)    
print( "Model has %d terms" % len(w2v_model.wv.vocab) )    
w2v_model.save("w2v-model.bin")    
# To re-load this model, run    
#w2v_model = gensim.models.Word2Vec.load("w2v-model.bin")    
    def calculate_coherence( w2v_model, term_rankings ):
        overall_coherence = 0.0
        for topic_index in range(len(term_rankings)):
            # check each pair of terms
            pair_scores = []
            for pair in combinations(term_rankings[topic_index], 2 ):
                pair_scores.append( w2v_model.similarity(pair[0], pair[1]) )
            # get the mean for all pairs in this topic
            topic_score = sum(pair_scores) / len(pair_scores)
            overall_coherence += topic_score
        # get the mean score across all topics
        return overall_coherence / len(term_rankings)

import numpy as np    
def get_descriptor( all_terms, H, topic_index, top ):    
    # reverse sort the values to sort the indices    
    top_indices = np.argsort( H[topic_index,:] )[::-1]    
    # now get the terms corresponding to the top-ranked indices    
    top_terms = []    
    for term_index in top_indices[0:top]:    
        top_terms.append( all_terms[term_index] )    
    return top_terms    
from itertools import combinations    
k_values = []    
coherences = []    
for (k,W,H) in topic_models:    
    # Get all of the topic descriptors - the term_rankings, based on top 10 terms
    term_rankings = []    
    for topic_index in range(k):
        term_rankings.append( get_descriptor( terms, H, topic_index, 10 ) )

    # Now calculate the coherence based on our Word2vec model
    k_values.append( k )
    coherences.append( calculate_coherence( w2v_model, term_rankings ) )
    print("K=%02d: Coherence=%.4f" % ( k, coherences[-1] ) )

我遇到了这个错误:

raise KeyError("word '%s' not in vocabulary" % word)

KeyError: u"单词 'business' 不在词汇表中"

原始代码非常适合他们的数据集。

https://github.com/derekgreene/topic-model-tutorial

你能帮忙看看这个错误是什么吗?

【问题讨论】:

    标签: python nlp gensim word2vec topic-modeling


    【解决方案1】:

    如果您在错误消息周围包含更多信息(例如多行调用帧,可以清楚地指示您的代码的哪一行触发了错误),这可能会对回答者有所帮助。

    但是,如果您收到错误 KeyError: u"word 'business' not in vocabulary",您可以相信您的 Word2Vec 实例 w2v_model 从未学习过 'business' 这个词。

    这可能是因为它没有出现在模型呈现的训练数据中,或者可能出现但少于min_count 次。

    由于您没有显示您的 raw_documents 变量的类型/内容,或您的 TokenGenerator 类的代码,因此尚不清楚为什么会出错 - 但这些是可以查看的地方。仔细检查raw_documents 的内容是否正确,docgen 可迭代对象中的各个项目看起来像是Word2Vec 的正确输入。

    docgen 可迭代对象中的每个项目都应该是字符串令牌列表,而不是纯字符串或其他任何内容。而且,docgen 可迭代对象必须可以被多次迭代。例如,如果您执行以下两行,您应该会看到相同的两个字符串列表标记(类似于 ['hello', 'world']:

    print(iter(docgen).next())
    print(iter(docgen).next())
    

    如果您看到纯字符串,则表明 docgen 没有为 Word2Vec 提供正确类型的项目。如果您只看到打印了一个项目,docgen 可能是一个简单的单遍迭代器,而不是一个可迭代的对象。

    您还可以在INFO 级别启用日志记录,并仔细观察Word2Vec 步骤期间的输出,并特别注意任何看起来不协调的数字/步骤。 (例如,是否有任何步骤表明没有发生任何事情,或者单词/文本示例的计数似乎不正确?)

    【讨论】:

    • 这是原始代码 github.com/derekgreene/topic-model-tutorial 位与我的数据集它面临此错误
    • 鉴于您的磁盘文件,您确定您的raw_documents 填写正确吗?您是否验证了我建议的打印语句显示了正确格式的合理结果?您是否在 INFO 级别启用了日志记录并查找异常情况?如果你得到你得到的错误,那么训练语料库中就没有'business'这个词。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    相关资源
    最近更新 更多