pyLDAvis生成LDA主题并可视化
这里写自定义目录标题
- pyLDAvis运行代码
- 注意:
pyLDAvis运行代码
- 加载相关模块
import gensim
from gensim import corpora
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import warnings# from gensim.models import LdaModel
import pandas as pd
from gensim.corpora import Dictionary
from gensim import corpora, models
import csv
import pyLDAvis.gensim_models as gensims
import pyLDAvis
warnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarityfrom gensim.models.coherencemodel import CoherenceModel
from gensim.models.ldamodel import LdaModel
- 计算困惑度和coherence
# 准备数据
PATH = "C:\\\\Users\\\\mat\\\\Desktop\\data\\\\各阶段关键短语抽取\\\\stage1_关键短语.txt"
file_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\\n') #一行行的读取内容
data_set=[] #建立存储分词的列表
for i in range(len(file_object2)):result=[]seg_list = file_object2[i].split()for w in seg_list :#读取每一行分词result.append(w)data_set.append(result)
# print(data_set)
dictionary = corpora.Dictionary(data_set) # 构建 document-term matrix
corpus = [dictionary.doc2bow(text) for text in data_set]
#Lda = gensim.models.ldamodel.LdaModel # 创建LDA对象#计算困惑度
def perplexity(num_topics):ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30)
# print(ldamodel.print_topics(num_topics=num_topics, num_words=15))
# print(ldamodel.log_perplexity(corpus))return ldamodel.log_perplexity(corpus)#计算coherence
def coherence(num_topics):ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30,random_state = 1)
# print(ldamodel.print_topics(num_topics=num_topics, num_words=10))ldacm = CoherenceModel(model=ldamodel, texts=data_set, dictionary=dictionary, coherence='c_v')
# print(ldacm.get_coherence())return ldacm.get_coherence()# 绘制困惑度折线图
x = range(1,15)
# z = [perplexity(i) for i in x]
y = [coherence(i) for i in x]
plt.plot(x, y)
plt.xlabel('主题数目')
plt.ylabel('coherence大小')
plt.rcParams['font.sans-serif']=['SimHei']
matplotlib.rcParams['axes.unicode_minus']=False
plt.title('主题-coherence变化情况')
plt.show()
- LDA模型生成与可视化
# 准备数据
PATH = "C:\\\\Users\\\\mat\\\\Desktop\\data\\\\各阶段关键短语抽取\\\\stage1_关键短语.txt"
file_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\\n') #一行行的读取内容
data_set=[] #建立存储分词的列表
for i in range(len(file_object2)):result=[]seg_list = file_object2[i].split()for w in seg_list :#读取每一行分词result.append(w)data_set.append(result)
print(len(data_set))
dictionary = corpora.Dictionary(data_set) # 构建 document-term matrix
corpus = [dictionary.doc2bow(text) for text in data_set]
#Lda = gensim.models.ldamodel.LdaModel # 创建LDA对象lda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=13, passes = 20,random_state=1)
topic_list=lda.print_topics()
# print(topic_list)result_list =[]
for i in lda.get_document_topics(corpus)[:]:listj=[]for j in i:listj.append(j[1])bz=listj.index(max(listj))result_list.append(i[bz][0])
# print(result_list)# 可视化
data = gensims.prepare(lda, corpus, dictionary)
pyLDAvis.save_html(data, 'C:\\\\Users\\\\mat\\\\Desktop\\\\res\\\\topic-1-emo.html')
注意:
- 本代码输入文件为分好词之后的txt;
- 如果运行代码过程中遇到如下错误:
TypeError: drop() takes from 1 to 2 positional arguments but 3 were given
需要修改_prepare.py文件【路径请看相应的错误提示】 ,将243行代码改为 default_term_info = default_term_info.sort_values(
by=‘saliency’, ascending=False).head®.drop(‘saliency’, axis=1)即可。 此错误的修改参考博文Jupytor运行pyLDAvis输出结果时报错