gensim中动态主题模型(DTM)两种实现方法(二)

第一部分内容请点此阅读:gensim中动态主题模型(DTM)两种实现方法(一)

目录

(二)gensim.models.wrappers.dtmmodel.DtmModel包

   1、如何使用呢?

   2、c语言运行的二进制文件作为参数

   3、基本函数的使用   


(二)gensim.models.wrappers.dtmmodel.DtmModel包

       在gensim中还有一个包,也可以用于DTM主题建模。该包的路径中有一个单词wrappers(封装)。所以我的理解是,这个包是对原始C语言版的封装。与第一个包明显的不同是,该包仅仅是个外壳,提供一些基本方法的借口和调用格式。内核的东西还是C语言的。因此,网上有不少利用这个包的教程,基本上是不能直接运行出结果的。但是这个包与第一个python包比较,有两点吸引人:一个是它的运行时间(本人电脑的测试结果是,这个模型运行上文同样的数据集,大概需要不到2个小时的时间,上文需要的是4-5个小时);还有一个比较吸引人的地方是它实现了DIM模型。可以用model.influences_time方法获取文档重要程度的度量结果。

   1、如何使用呢?

       该模型该如何使用呢?注意看源代码中的注释说明。尤其是warnings下的说明。该说明告诉我们,如果想使用它训练模型的话,必须要安装原始实现(blei等人的c语言实现)二进制文件。因此,使用的最基本方法是将原始c语言版本下载运行出一个可执行文件(.exe文件,即注释中说的binary path)。然后需要将该exe文件的path作为模型初始化的第一个参数(dtm_path)。  如何运行c语言版本,网上的教程较多,在此不做介绍了。那么,有没有办法不运行c语言程序也可以使用呢?请看第2部分。

class DtmModel(utils.SaveLoad):
    """Python wrapper using `DTM implementation <https://github.com/magsilva/dtm/tree/master/bin>`_.

    Communication between DTM and Python takes place by passing around data files on disk and executing
    the DTM binary as a subprocess.

    Warnings
    --------
    This is **only** python wrapper for `DTM implementation <https://github.com/magsilva/dtm/tree/master/bin>`_,
    you need to install original implementation first and pass the path to binary to ``dtm_path``.

    """
    def __init__(self, dtm_path, corpus=None, time_slices=None, mode='fit', model='dtm', num_topics=100,
                 id2word=None, prefix=None, lda_sequence_min_iter=6, lda_sequence_max_iter=20, lda_max_em_iter=10,
                 alpha=0.01, top_chain_var=0.005, rng_seed=0, initialize_lda=True):
        """

        Parameters
        ----------
        dtm_path : str
            Path to the dtm binary, e.g. `/home/username/dtm/dtm/main`.

   2、c语言运行的二进制文件作为参数

         重新编译C语言,然后将exe文件作为参数传递固然可行,但有没有更加便捷的方法呢?请注意继续深入研读注释部分,warnings中的那段话。发现软件开发人员还是很有良心的。在注释中,那个网址已经清晰的告诉我们可以怎么办了。怎么办呢。打开https://github.com/magsilva/dtm/tree/master/bin ,发现github上已经提供编译好的二进制文件了。还贴心的提供了不同的版本。

 

     因此,可以将需要的版本下载到指定目录,备用。

   3、基本函数的使用   

    有了上面的基本准备后,就可以使用 gensim.models.wrappers.dtmmodel.DtmModel包的模型训练函数了。

    训练模型的基本方法:    

model = DTM.dtm_model('yourpath\dtm-win64.exe',
                       corpus=corpus,time_seq=time_slice,num_topics=numTopics)

      这个里面尤其要注意第一个参数,也就是初始化函数中的dtm_path。这个参数是模型运行的核心。因为正是这个exe文件才实现了DTM的e-step和m-step以及DIM模型。

      除此之外,还有几个常用的函数,功能与第一个模型类似,但是名称有所区别,因此使用时,注意不要两个模型搞混了。

def print_topics(self, num_topics=10, times=5, num_words=10):

def show_topics(self, num_topics=10, times=5, num_words=10, log=False, formatted=True):

def show_topic(self, topicid, time, topn=50, num_words=None):

def print_topic(self, topicid, time, topn=10, num_words=None):

model.influences_time[time][document][topic]   #这是模型训练出的一个三维矩阵。

     写到这里,感觉这两个模型同时放到gensim.models之下,确实容易让我们初学主题模型的人产生误解或混用的情况(实际上,网上的教程有混用的问题)。在这里给我的提醒是在使用别人源码时,一定要阅读源码,尤其是源码中的关键注释也不能放过。这样才能更好地理解代码作者的基本思路,同时,也才能提升自己的分析和理解问题的能力。

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
首先,需要安装gensim库,可以使用以下命令进行安装: ``` pip install gensim ``` 接下来,我们使用gensim实现LDA主题模型文本分析及可视化的步骤如下: 1. 导入所需的库和数据集 ``` import logging import gensim from gensim import corpora from gensim.models.ldamodel import LdaModel from gensim.models import CoherenceModel import pyLDAvis.gensim import pandas as pd logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) # 导入数据集 df = pd.read_csv('data.csv') texts = df['text'].tolist() ``` 2. 对文本进行预处理 ``` from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer import string stop = set(stopwords.words('english')) exclude = set(string.punctuation) lemma = WordNetLemmatizer() def clean(doc): stop_free = " ".join([i for i in doc.lower().split() if i not in stop]) punc_free = ''.join(ch for ch in stop_free if ch not in exclude) normalized = " ".join(lemma.lemmatize(word) for word in punc_free.split()) return normalized doc_clean = [clean(doc).split() for doc in texts] ``` 3. 创建词袋模型,并生成LDA模型 ``` # 创建词袋模型 dictionary = corpora.Dictionary(doc_clean) doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean] # 生成LDA模型 lda_model = LdaModel(doc_term_matrix, num_topics=10, id2word=dictionary, passes=50) ``` 4. 计算主题模型的一致性得分 ``` coherence_model_lda = CoherenceModel(model=lda_model, texts=doc_clean, dictionary=dictionary, coherence='c_v') coherence_lda = coherence_model_lda.get_coherence() print('Coherence Score:', coherence_lda) ``` 5. 可视化主题模型 ``` vis = pyLDAvis.gensim.prepare(lda_model, doc_term_matrix, dictionary) pyLDAvis.display(vis) ``` 以上就是使用gensim实现LDA主题模型文本分析及可视化的步骤。需要注意的是,这里仅提供了一个简单的示例,实际应用还需要根据具体情况进行调整和优化。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值