GENSIM 使用笔记2 — 主题模型和相似性查询

这篇笔记详细介绍了如何使用GENSIM库创建主题模型,如TF-IDF、LSI和LDA,并执行相似性查询。首先,通过加载上文创建的字典和语料库,构建TF-IDF模型并序列化。接着,利用TF-IDF模型生成LSI和LDA模型,展示主题信息。最后,阐述了如何进行简单的相似性查询,构建索引进行高效检索。
摘要由CSDN通过智能技术生成

GENSIM 使用笔记1 — 语料和向量空间
GENSIM 使用笔记2 — 主题模型和相似性查询
在上一个笔记当中,使用gensim针对中文预料创建了字典和语料库,在这一章节中,主要讲下如何创建相应的主题模型和相似度的匹配,对应原教程的第二章和第三章

模型创建

在GENSIM当中,最基本的就是创建TF-IDF模型,随后可以在TF-IDF的基础上创建LSI/LDA等等的主题模型。
GENSIM已经封装的很好了,所以其实这部分会过的非常快(算法具体的内容这里不讲)

那么,首先我们需要加载上一篇笔记当中的数据:

# 首先加载语料库
if os.path.exists('mydict.dic') and os.path.exists('corpus.mm'):
    dictionary = corpora.Dictionary.load('mydict.dic')
    corpus = corpora.MmCorpus('corpus.mm')
    print 'used files generated from string2vector'
else:
    print 'please run string2vector firstly'

随后,我们需要首先创建最关键的TF-IDF模型,并且可以生成TF-IDF的语料库,并将其序列化,以方便我们的后续使用

#创建一个model
tfidf = models.Tfidf
首先,需要安装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主题模型文本分析及可视化的步骤。需要注意的是,这里仅提供了一个简单的示例,实际应用中还需要根据具体情况进行调整和优化。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值