【问题标题】:Saved Gensim LdaMallet model not working in different console保存的 Gensim LdaMallet 模型在不同的控制台中不起作用
【发布时间】:2019-10-15 05:17:11
【问题描述】:

我正在用 python 训练一个 ldamallet 模型并保存它。我还保存了训练字典,以后可以用它来为看不见的文档创建语料库。如果我在同一个控制台中执行每个操作(即训练模型、保存训练模型、加载保存的模型、推断看不见的语料库),一切正常。但是,我想在不同的控制台/计算机中使用经过训练的模型。

我在训练时传递了前缀来查看模型创建的临时文件。训练模型时会创建以下文件:

'corpus.mallet'

'corpus.txt'

'doctopics'txt'

inferencer.mallet'

'state.mallet.gz'

'topickeys.txt'

现在,当我在不同的控制台中加载保存的模型并推断使用保存的字典创建的看不见的语料库时,我看不到其他临时文件正在创建并产生以下错误:

FileNotFounderror: No such file or directory : 'my_directory\\doctopics.txt.infer'

出于某种奇怪的原因,如果我在同一个控制台(训练它的控制台)中加载保存的模型并像上面那样推断看不见的语料库,则会更新“corpus.txt”并创建两个新的临时文件:

'corpus.mallet.infer'

'doctopics.txt.infer'

知道我为什么会遇到这个问题吗?

我尝试使用 LdaModel 代替 LdaMallet,无论我是在同一个控制台还是在不同的控制台中执行整个任务,LdaModel 都能正常工作。

下面是我正在使用的代码的 sn-p。

    def find_optimum_model(self):
        lemmatized_words = self.lemmatization()
        id2word = corpora.Dictionary(lemmatized_words)
        all_corpus = [id2word.doc2bow(text) for text in lemmatized_words]

        #For two lines below update with your path to new_mallet
        os.environ['MALLET_HOME'] = r'C:\\users\\axk0er8\\Sentiment_Analysis_Working\\new_mallet\\mallet-2.0.8'
        mallet_path = r'C:\\users\\axk0er8\\Sentiment_Analysis_Working\\new_mallet\\mallet-2.0.8\\bin\\mallet.bat'
        prefix_path = r'C:\\users\\axk0er8\\Sentiment_Analysis_Working\\new_mallet\\mallet_temp\\'

    def compute_coherence_values(dictionary, all_corpus, texts, limit, start=2, step=4):
        coherence_values = []
        model_list = []
        num_topics_list = []


        for num_topics in range(start, limit, step):
            model = gensim.models.wrappers.LdaMallet(mallet_path, corpus=all_corpus, num_topics=num_topics, id2word=dictionary,
                                                random_seed=42)
            #model = gensim.models.ldamodel.LdaModel(corpus=all_corpus,num_topics=num_topics,id2word=dictionary,eval_every=1,
            #                                        alpha='auto',random_state=42)
            model_list.append(model)
            coherencemodel = CoherenceModel(model=model, texts=texts, dictionary=dictionary, coherence='c_v')
            coherence_values.append(coherencemodel.get_coherence())
            num_topics_list.append(num_topics)

        return model_list, coherence_values, num_topics_list

    model_list, coherence_values, num_topics_list = compute_coherence_values(dictionary=id2word,all_corpus=all_corpus,
                                                                                texts=lemmatized_words,start=5,limit=40, step=6)
    model_values_df = pd.DataFrame({'model_list':model_list,'coherence_values':coherence_values,'num_topics':num_topics_list})

    optimal_num_topics = model_values_df.loc[model_values_df['coherence_values'].idxmax()]['num_topics']

    optimal_model = gensim.models.wrappers.LdaMallet(mallet_path, corpus=all_corpus, num_topics=optimal_num_topics, id2word=id2word,
                                                        prefix=prefix_path, random_seed=42)

    #joblib.dump(id2word,'id2word_dictionary_mallet.pkl')
    #joblib.dump(optimal_model,'optimal_ldamallet_model.pkl')
    id2word.save('id2word_dictionary.gensim')
    optimal_model.save('optimal_lda_model.gensim')

    def generate_dominant_topic(self):
        lemmatized_words = self.lemmatization()
        id2word = corpora.Dictionary.load('id2word_dictionary.gensim')
        #id2word = joblib.load('id2word_dictionary_mallet.pkl')
        new_corpus = [id2word.doc2bow(text) for text in lemmatized_words]
        optimal_model = gensim.models.wrappers.LdaMallet.load('optimal_lda_model.gensim')
        #optimal_model = joblib.load('optimal_ldamallet_model.pkl')


        def format_topics_sentences(ldamodel, new_corpus):
            sent_topics_df = pd.DataFrame()
            for i, row in enumerate(ldamodel[new_corpus]):
                row = sorted(row, key=lambda x: (x[1]), reverse=True)
                for j, (topic_num, prop_topic) in enumerate(row):
                    if j == 0:
                        wp = ldamodel.show_topic(topic_num)
                        topic_keywords = ", ".join([word for word, prop in wp])
                        sent_topics_df = sent_topics_df.append(pd.Series([int(topic_num), round(prop_topic,4), topic_keywords]),
                                                               ignore_index=True)
                    else:
                        break
            sent_topics_df.columns = ['Dominant_Topic', 'Perc_Contribution', 'Topic_Keywords']
            return (sent_topics_df)

我的期望是对训练数据使用find_optimum_model 函数并保存最佳模型和字典。保存后,使用generate_dominant_topic 函数加载保存的模型和字典,为看不见的文本创建语料库并运行模型以获得所需的主题建模输出。

【问题讨论】:

    标签: python gensim lda mallet


    【解决方案1】:

    加载模型后,您可以像这样指定新的前缀路径:

    ldamodel.prefix = 'path/to/new/prefix'
    

    【讨论】:

      【解决方案2】:

      是的,您需要随身携带这些文件:https://github.com/RaRe-Technologies/gensim/issues/818

      【讨论】:

      【解决方案3】:

      尽管有名称,但这些实际上并不是“临时”文件,因为模型需要它们才能运行。我强烈建议您将它们复制到与旧控制台相同的相对位置(前缀)中的新控制台(以便模型知道在哪里寻找它们。)希望这会奏效。不过我自己没试过。

      当您从训练到使用模型进行分类时,就会出现推断文件。我认为他们需要构建推理器...... 由于这些文件经常损坏,我不得不多次删除和重新训练我的槌模型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        • 2016-11-01
        相关资源
        最近更新 更多