gensim.corpora中Dictionaryd的用法

该博客介绍了gensim.corpora.Dictionary的使用方法,包括如何从二维列表创建字典,查看字典信息如单词id、文档频率、词频等,并展示了如何添加新语句、过滤词频以及将文本转换为词袋模型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

gensim.corpora中Dictionaryd的用法

调用

from gensim.corpora import Dictionary
dictionary = Dictionary(corpus)
这里的corpus需要时二维列表形式,如
corpus = [['我', '在', '玉龙雪山', '我', '我', '我', '我'], ['我', '喜欢', '玉龙雪山'], ['我', '还要', '去', '玉龙雪山']

得到的dictionary事宜个包含很多信息的集合,若要对其中信息进行查看可如下操作:
输出dictionary

print(str(dictionary))
>>>"Dictionary(75 unique tokens: ['\\n', '23', '、', '厂', '台积']...)"

查看 字典,{单词id,在所有文档中共出现几次}

print(dictionary.dfs)    #字典,{单词id,在多少文档中出现}
>>>{1: 7, 0: 1, 2: 3, 3: 1, 5: 1, 4: 1}

查看 字典,{单词id,在多少文档中出现}

print(dictionary.cfs)
>>>{1: 3, 0: 1, 2: 3, 3: 1, 5: 1, 4: 1}

查看 文档数目:

dictionary.num_docs     #文档数目
>>> 3

查看 dictionary 中 {词的id:词}

print (dict(dictionary. items()))
或者 
print(dictionary.id2token)
>>> {0: '在', 1: '我', 2: '玉龙雪山', 3: '喜欢', 4: '去', 5: '还要'}

查看 {词:词的id}

print(dictionary.token2id)
>>> {'在': 0, '我': 1, '玉龙雪山': 2, '喜欢': 3, '去': 4, '还要': 5}

查看共有多少个词,多少个不重复的词

print(dictionary.num_pos) #查看所有词的个数

print(dictionary.num_nnz) #查看所有词的个数

添加新的语句:

newlist=jieba.lcut('美国以应对芯片危机,美国出现投票信任危机')
result, missing = dictionary.doc2bow(newlist, allow_update=True, return_missing=True) # allow_update : 更新当前字典;return_missing : 返回字典中不存在的词,result为b文章转换得到的词袋,列表[(单词id,词频)]
result
>>> [(6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 2), (13, 1), (14, 1)]  #词袋 [(单词id,单词出现频率)]
missing
>>>[] #不在字典中的词及其词频,字典[(单词,词频)]
print(dict(dictionary.items()))  #查看加入后的{词:词id}
>>>{0: '在', 1: '我', 2: '玉龙雪山', 3: '喜欢', 4: '去', 5: '还要', 6: '以', 7: '信任危机', 8: '出现', 9: '危机', 10: '应对', 11: '投票', 12: '美国', 13: '芯片', 14: ','}

for id, freq in result:
    print(id, dictionary.id2token[id], freq) #查看bow的内容
>>>
61
7 信任危机 1
8 出现 1
9 危机 1
10 应对 1
11 投票 1
12 美国 2
13 芯片 1
141

过滤词频

过滤文档频率大于 no_below,小于 no_above*num_docs的词
dictionary.filter_extremes(no_below=2,no_above=0.5,keep_n=10)
print(dictionary.dfs) #查看结果

文章参考:该博客

<think>好的,我需要帮助用户使用Gensim构建LDA主题模型并提取最佳主题词。首先,我需要回忆Gensim中LDA的实现步骤。根据之前的引用,用户提到了数据预处理、模型训练和参数调整等部分。 首先,数据预处理是关键。用户需要将文本转换为词袋格式。引用[3]提到LDA是一种词袋方法,所以需要分词、去除停用词等步骤。然后,创建字典和语料库,这一步通常使用Gensimcorpora.Dictionary来处理。例如,过滤掉低频和高频词汇,生成字典,再将文档转换为向量。 接下来是模型训练。引用[1]和[3]指出,使用gensim.models.LdaModel来训练模型,需要指定主题数、迭代次数等参数。用户可能需要注意chunksize和passes参数,以确保模型收敛。训练完成后,如何提取主题词呢?应该使用show_topic方法,按概率排序获取每个主题的关键词。 然后是确定最佳主题数。引用[2]提到使用困惑度(Perplexity)和一致性分数(Coherence)来评估模型。困惑度越低越好,而一致性分数越高越好。用户需要尝试不同的主题数,计算这些指标,选择表现最好的模型。比如,在示例中,当主题数为5时,困惑度最低,一致性最高,因此选择5作为最佳主题数。 可视化部分,引用[4]提到了LDA可视化工具,如pyLDAvis,这能帮助用户直观理解主题分布。需要指导用户安装并使用该库生成交互式图表。 可能遇到的问题包括数据预处理不充分导致模型效果差,参数设置不当(如主题数过多或过少),以及评估指标的选择。需要提醒用户进行多次实验,调整参数,并交叉验证结果。 最后,生成相关问题时要覆盖模型评价、参数优化、应用场景和比较分析等方面,帮助用户深入理解LDA模型的应用和调整。 总结步骤:预处理数据、构建词典和语料、训练LDA模型、评估调整参数、提取主题词、可视化结果。确保每个步骤的代码示例正确,并引用相关参考资料。</think>### Gensim实现LDA主题模型分析步骤 #### **1. 数据预处理** - **文本清洗**:去除标点、停用词,并进行分词 ```python from gensim.utils import simple_preprocess from gensim.parsing.preprocessing import STOPWORDS def preprocess(text): return [token for token in simple_preprocess(text) if token not in STOPWORDS] documents = ["文本1内容", "文本2内容", ...] processed_docs = [preprocess(doc) for doc in documents] ``` - **构建词典与语料库** ```python from gensim import corpora dictionary = corpora.Dictionary(processed_docs) dictionary.filter_extremes(no_below=5, no_above=0.5) # 过滤低频/高频词 corpus = [dictionary.doc2bow(text) for text in processed_docs] # 词袋格式[^3] ``` #### **2. 训练LDA模型** ```python from gensim.models import LdaModel # 设置主题数k=5,迭代500次 lda_model = LdaModel( corpus=corpus, id2word=dictionary, num_topics=5, random_state=100, passes=20, chunksize=100 ) ``` #### **3. 提取主题词** ```python # 查看前5个主题的关键词(每个主题显示10个词) for topic_id in range(5): print(f"主题 {topic_id}: {lda_model.show_topic(topic_id, topn=10)}") ``` 输出示例: `主题 0: [('数据', 0.15), ('分析', 0.12), ('模型', 0.09), ...]`[^3] --- #### **4. 确定最佳主题数** - **方法1:计算困惑度(Perplexity)** $$ \text{Perplexity} = \exp\left(-\frac{\sum \log p(w_d)}{\sum N_d}\right) $$ ```python perplexity = lda_model.log_perplexity(corpus) print(f"困惑度: {perplexity}") # 值越小越好[^2] ``` - **方法2:一致性分数(Coherence)** ```python from gensim.models import CoherenceModel coherence_model = CoherenceModel( model=lda_model, texts=processed_docs, dictionary=dictionary, coherence='c_v' ) coherence = coherence_model.get_coherence() # 值越大越好[^2] ``` - **参数优化实验示例**: ```python topics_range = range(2, 10) coherence_scores = [] for k in topics_range: model = LdaModel(corpus, num_topics=k, id2word=dictionary) coherence = CoherenceModel(model, texts=processed_docs, dictionary=dictionary, coherence='c_v').get_coherence() coherence_scores.append(coherence) # 选择coherence最高对应的k值 ``` --- #### **5. 可视化分析** ```python import pyLDAvis.gensim vis = pyLDAvis.gensim.prepare(lda_model, corpus, dictionary) pyLDAvis.display(vis) # 生成交互式图表,显示主题间距离与关键词[^4] ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值