当前位置:   article > 正文

Lda模型分析完整代码_lda模型一致性代码

lda模型一致性代码

之前参考博主的代码写的非常好,但是一些小白不是计算机的对于代码运行不起来,以至于后台私信我,这里统一放一份完整代码,代码是可以运行的,我也不是专业的,只是恰好使用到了,如有错误,多多包涵,我把完整的代码放上,大家记得给原博主点个赞,原博主代码链接

  1. import re
  2. import jieba as jb
  3. from gensim.models import LdaModel
  4. import pyLDAvis.gensim_models
  5. import codecs
  6. from gensim.models import LdaModel
  7. from gensim.models import CoherenceModel
  8. import gensim
  9. from gensim import corpora, models
  10. import matplotlib.pyplot as plt
  11. import matplotlib
  12. if __name__ == '__main__':
  13. #--------------------------句子拆分------------------------------
  14. def stopwordslist(filepath):
  15. stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]
  16. return stopwords
  17. # 对句子进行分词
  18. def seg_sentence(sentence):
  19. sentence = re.sub(u'[0-9\.]+', u'', sentence)
  20. # jb.add_word('词汇') # 这里是加入自定义的词来补充jieba词典
  21. sentence_seged = jb.cut(sentence.strip())
  22. stopwords = stopwordslist('自己搜来的停用词表.txt') # 这里加载停用词的路径
  23. outstr = ''
  24. for word in sentence_seged:
  25. if word not in stopwords and word.__len__() > 1:
  26. if word != '\t':
  27. outstr += word
  28. outstr += " "
  29. return outstr
  30. inputs = open('感想.txt', 'r', encoding='utf-8')
  31. outputs = open('感想分词.txt', 'w', encoding='utf-8')
  32. for line in inputs:
  33. line_seg = seg_sentence(line) # 这里的返回值是字符串
  34. outputs.write(line_seg + '\n')
  35. outputs.close()
  36. inputs.close()
  37. # --------------------------------开始构建lda模型-------------------------------
  38. train = []
  39. fp = codecs.open('感想分词.txt', 'r', encoding='utf8')
  40. for line in fp:
  41. if line != '':
  42. line = line.split()
  43. train.append([w for w in line])
  44. dictionary = corpora.Dictionary(train)
  45. corpus = [dictionary.doc2bow(text) for text in train]
  46. lda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=4, passes=100)
  47. # num_topics:主题数目
  48. # passes:训练伦次
  49. # num_words:每个主题下输出的term的数目
  50. for topic in lda.print_topics(num_words=20):
  51. termNumber = topic[0]
  52. print(topic[0], ':', sep='')
  53. listOfTerms = topic[1].split('+')
  54. for term in listOfTerms:
  55. listItems = term.split('*')
  56. print(' ', listItems[1], '(', listItems[0], ')', sep='')
  57. # -------------------------------可视化拆分-------------------------------------
  58. train = []
  59. fp = codecs.open('感想分词.txt', 'r', encoding='utf8')
  60. for line in fp:
  61. if line != '':
  62. line = line.split()
  63. train.append([w for w in line])
  64. dictionary = corpora.Dictionary(train)
  65. corpus = [dictionary.doc2bow(text) for text in train]
  66. lda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=4, passes=100)
  67. # num_topics:主题数目
  68. # passes:训练伦次
  69. # num_words:每个主题下输出的term的数目
  70. for topic in lda.print_topics(num_words=20):
  71. termNumber = topic[0]
  72. print(topic[0], ':', sep='')
  73. listOfTerms = topic[1].split('+')
  74. for term in listOfTerms:
  75. listItems = term.split('*')
  76. print(' ', listItems[1], '(', listItems[0], ')', sep='')
  77. d = pyLDAvis.gensim_models.prepare(lda, corpus, dictionary)
  78. '''
  79. lda: 计算好的话题模型
  80. corpus: 文档词频矩阵
  81. dictionary: 词语空间
  82. '''
  83. # pyLDAvis.show(d) #展示在浏览器
  84. # pyLDAvis.displace(d) #展示在notebook的output cell中
  85. pyLDAvis.save_html(d, 'lda_pass4.html')
  86. # ----------------------------困惑都计算--------------------------------------
  87. # 准备数据
  88. PATH = "感想分词.txt" # 已经进行了分词的文档(如何分词前面的文章有介绍)
  89. file_object2 = open(PATH, encoding='utf-8', errors='ignore').read().split('\n')
  90. data_set = [] # 建立存储分词的列表
  91. for i in range(len(file_object2)):
  92. result = []
  93. seg_list = file_object2[i].split() # 读取没一行文本
  94. for w in seg_list: # 读取每一行分词
  95. result.append(w)
  96. data_set.append(result)
  97. print(data_set) # 输出所有分词列表
  98. dictionary = corpora.Dictionary(data_set) # 构建 document-term matrix
  99. corpus = [dictionary.doc2bow(text) for text in data_set]
  100. Lda = gensim.models.ldamodel.LdaModel # 创建LDA对象
  101. # 计算困惑度
  102. def perplexity(num_topics):
  103. ldamodel = Lda(corpus, num_topics=num_topics, id2word=dictionary, passes=50) # passes为迭代次数,次数越多越精准
  104. print(ldamodel.print_topics(num_topics=num_topics, num_words=20)) # num_words为每个主题下的词语数量
  105. print(ldamodel.log_perplexity(corpus))
  106. return ldamodel.log_perplexity(corpus)
  107. # 绘制困惑度折线图
  108. x = range(1, 20) # 主题范围数量
  109. y = [perplexity(i) for i in x]
  110. plt.plot(x, y)
  111. plt.xlabel('主题数目')
  112. plt.ylabel('困惑度大小')
  113. plt.rcParams['font.sans-serif'] = ['SimHei']
  114. matplotlib.rcParams['axes.unicode_minus'] = False
  115. plt.title('主题-困惑度变化情况')
  116. plt.show()
  117. #-------------------------------一致性得分-------------------------------------
  118. # 准备数据
  119. PATH = "感想分词.txt" # 已经进行了分词的文档(如何分词前面的文章有介绍)
  120. file_object2 = open(PATH, encoding='utf-8', errors='ignore').read().split('\n')
  121. data_set = [] # 建立存储分词的列表
  122. for i in range(len(file_object2)):
  123. result = []
  124. seg_list = file_object2[i].split() # 读取没一行文本
  125. for w in seg_list: # 读取每一行分词
  126. result.append(w)
  127. data_set.append(result)
  128. print(data_set) # 输出所有分词列表
  129. dictionary = corpora.Dictionary(data_set) # 构建 document-term matrix
  130. corpus = [dictionary.doc2bow(text) for text in data_set]
  131. Lda = gensim.models.ldamodel.LdaModel # 创建LDA对象
  132. def coherence(num_topics):
  133. ldamodel = Lda(corpus, num_topics=num_topics, id2word=dictionary, passes=50) # passes为迭代次数,次数越多越精准
  134. coherence_model_lda = CoherenceModel(model=ldamodel, texts=data_set, dictionary=dictionary, coherence='c_v')
  135. coherence_lda = coherence_model_lda.get_coherence()
  136. print('\nCoherence Score: ', coherence_lda)
  137. return coherence_lda
  138. # 绘制困惑度折线图
  139. x = range(1, 2) # 主题范围数量
  140. y = [coherence(i) for i in x]
  141. plt.plot(x, y)
  142. plt.xlabel('主题数目')
  143. plt.ylabel('coherence大小')
  144. plt.rcParams['font.sans-serif'] = ['SimHei']
  145. matplotlib.rcParams['axes.unicode_minus'] = False
  146. plt.title('主题-coherence变化情况')
  147. plt.show()

除此以外,你还需要在同级目录下,存放一下四个文件,

其中情感分析.py,可以自己找,我只提供一个参考,让你们知道文件内是什么

  1. from textblob import TextBlob
  2. # 创建一个TextBlob对象
  3. text = TextBlob("I am feel sad")
  4. # 分析情感
  5. sentiment = text.sentiment.polarity
  6. # 输出情感分析结果
  7. print(sentiment)
  8. if sentiment > 0:
  9. print("积极的")
  10. elif sentiment == 0:
  11. print("中性词")
  12. else:
  13. print("消极的")

感想.txt内容需要自己爬虫收集,以下只是部分例子,理论上你是需要非常多行数据的

  1. 甘蓝甜甜的,不像超市的苦有农药味,以后就在这家买了
  2. 卷心菜每次必选 。烩点儿饼丝 。凉拌非常好吃 。
  3. 卷心菜也非常新鲜 ,全部原拍
  4. 太惊喜了,超级新鲜,以后就这家了
  5. 包菜之前也拍过,炒出来味道好像甜一些,对于市场打药多的包菜,有机虽然贵很多,但吃着放心。
  6. 经常回购这家,包装很好,夏季保鲜有保证。
  7. 质量不好
  8. 不是很鲜
  9. 不错,菜真新鲜
  10. 蔬菜收到很新鲜,吃起来口感很好。已是第二次回购!
  11. 冬瓜特別好吃 感覺還是吃有機的安全 會一直回購的
  12. 再次买了,是新鲜的有机蔬菜,很好吃,有需要还会再来光顾,满意的好评!
  13. 菜很新鲜,有机放心,继续回购。

自己搜来的停用词表.txt里面是你要去查找的用来分割句子的单词,大概是以下样子,你百度一下就有了

  1. 哎呀
  2. 哎哟
  3. 俺们
  4. 按照
  5. 吧哒
  6. 罢了
  7. 本着
  8. 比方
  9. 比如
  10. 鄙人
  11. 彼此
  12. 别的
  13. 别说

最后感想分词.txt是我们运行程序生成的,不是你自己搜集的文件。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/719883
推荐阅读
相关标签
  

闽ICP备14008679号