lda主题评论文本python_[翻译] 在Python中使用LDA处理文本

本文演示了如何在Python中使用LDA(潜在 Dirichlet 分配)处理文本数据,包括安装lda库、加载 Reuters 数据集、查看词汇表、训练LDA模型,并展示每个主题的关键词分布。
摘要由CSDN通过智能技术生成

说明:

安装

$ pip install lda --user

示例

from __future__ import division, print_function

import numpy as np

import lda

import lda.datasets

# document-term matrix

X = lda.datasets.load_reuters()

print("type(X): {}".format(type(X)))

print("shape: {}\n".format(X.shape))

print(X[:5, :5])

'''输出:

type(X):

shape: (395L, 4258L)

[[ 1 0 1 0 0]

[ 7 0 2 0 0]

[ 0 0 0 1 10]

[ 6 0 1 0 0]

[ 0 0 0 2 14]]

'''

X为395*4298的矩阵,意味着395个文本,共4258个单词。值代表出现次数。

看一下是哪些单词:

# the vocab

vocab = lda.datasets.load_reuters_vocab()

print("type(vocab): {}".format(type(vocab)))

print("len(vocab): {}\n".format(len(vocab)))

print(vocab[:6])

&#

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值