1 D) p7 K% p2 @/ d% l& F" y《美妆日记》{美妆:0.8,美食:0.1,其他:0.1}$ o3 C0 c8 t2 |% R8 `
3 j" P6 Z( r6 a1 r% E" W) I6 b
《美食探索》{美食:0.8,美妆:0.1,其他:0.1} 7 p+ ?2 q2 k+ b5 x: r ; m. I- {3 H8 ~- y- x 所以想要生成一篇文章,可以先以一定的概率选取上述某个主题,再以一定的概率选取那个主题下的某个单词,不断重复这两步就可以生成最终文章。; r8 ?9 e ?9 T
' q* K1 m) } b# y J; a+ ~6 R# f 在LDA模型中,一篇文档生成的方式如下:2 _, ~, y& h: E& L) |
" S7 A) a+ `# T" D + q7 Z P7 u0 s$ k) ~6 o1 B* q) L; m# W
其中,类似Beta分布是二项式分布的共轭先验概率分布,而狄利克雷分布(Dirichlet分布)是多项式分布的共轭先验概率分布。 : _( z: c0 f- \( V# T" j: K% w: {/ D/ }, F1 f! h0 d0 Q: D7 o
+ c" V, m" B' q) T( ? Y1 ]
3 E2 C' `9 B% q$ V4 C 如果我们要生成一篇文档,它里面的每个词语出现的概率为:) q+ W3 u: q% K4 n( t
% y; J" T( R4 `) G: f3 A2 X& k t0 o! ~% |# O$ r
* ?8 I. ~. \9 F0 u
更详细的数学推导可以见:通俗理解LDA主题模型_结构之法 算法之道-CSDN博客_lda模型 - N+ t3 Y3 g9 E) z4 t; l+ b) u! d2 {( ]% k8 X6 S* E! \ y
看到文章推断其隐藏的主题分布,就是建模的目的。换言之,人类根据文档生成模型写成了各类文章,然后丢给了计算机,相当于计算机看到的是一篇篇已经写好的文章。现在计算机需要根据一篇篇文章中看到的一系列词归纳出当篇文章的主题,进而得出各个主题各自不同的出现概率:主题分布。 8 V$ y$ l5 M0 d5 w) S$ n7 [8 U: f8 S( `" N
至于LDA主题模型在计算机中具体是怎么实现的,我们也可以不必细究,现在有很多可以直接用来进行LDA主题分析的包,我们直接用就行。(没错,我就是调包侠)( k2 D0 n- y6 a: O9 X8 Q
" Y, _* d7 m( `% Z! d
二、Python实现* \9 r4 j" @& E N
在用Python进行LDA主题模型分析之前,我先对文档进行了分词和去停用词处理(详情可以看我之前的文章:用python对单一微博文档进行分词——jieba分词(加保留词和停用词)_阿丢是丢心心的博客-CSDN博客_jieba 停用词) 6 ?/ p7 X# n" p" ?# v' }" K) d& \! n8 g* b7 } ?/ K
我下面的输入文件也是已经分好词的文件 : ~2 V4 B+ ^1 a+ T) t6 G8 Y. q, P
1.导入算法包' @2 _6 b/ K" \
import gensim a( T0 U! W) s' }from gensim import corpora 9 ?* t* R+ X1 g* I1 O$ Qimport matplotlib.pyplot as plt8 V) Q* g0 r, }$ X3 _
import matplotlib1 {/ k5 s# c9 @" n
import numpy as np / j+ \8 b) _9 S- }7 L. Zimport warnings 4 i. t. U$ a) o" G) Z" hwarnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarity, l( w5 p* h ]+ k* `
- G, A5 E7 x* P/ }
from gensim.models.coherencemodel import CoherenceModel b" F3 P( f8 m$ N+ w4 ~( lfrom gensim.models.ldamodel import LdaModel# `; D- j5 s# r+ J0 ] L' g
2.加载数据$ I M5 w% t/ Z' D' {. ]; b" j
先将文档转化为一个二元列表,其中每个子列表代表一条微博:6 u H5 d, m# ~
* |, g' S9 n [1 t" yPATH = "E:/data/output.csv" 4 e' S" w4 H& J8 ^ }% N* [) } K/ P% i2 v+ M! e X
file_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容 # G. h8 s' U% Y# L' \) `2 Bdata_set=[] #建立存储分词的列表 ; A0 w8 T' T6 `7 O4 ]9 q: y' e$ Z2 dfor i in range(len(file_object2)):& Y/ u2 |9 R `3 _/ I
result=[]" l5 s" e1 ~' J! T8 ^. h1 _
seg_list = file_object2.split() 0 F- D; k8 h r7 T! @% u$ R for w in seg_list : #读取每一行分词 ; ^2 [( W2 S9 L/ D. h result.append(w) : e7 R1 {" H+ D' K1 F data_set.append(result)+ Z7 Z' S, r4 {0 S
print(data_set) , v- Y+ a# r3 ? d2 K 构建词典,语料向量化表示:2 X( y |9 f; Z% X& d w; }: k
4 r% J6 I# [7 e1 rdictionary = corpora.Dictionary(data_set) # 构建词典3 Q# w/ K* ^ u$ U* F k- ?0 p4 J
corpus = [dictionary.doc2bow(text) for text in data_set] #表示为第几个单词出现了几次 $ m7 d5 T; _% ~4 A- R. R G2 X3.构建LDA模型/ V5 I1 I1 {& `8 m2 a: S# q8 G) P
ldamodel = LdaModel(corpus, num_topics=10, id2word = dictionary, passes=30,random_state = 1) #分为10个主题0 a6 C( X/ z5 @ _1 R
print(ldamodel.print_topics(num_topics=num_topics, num_words=15)) #每个主题输出15个单词 " t$ t+ r3 Z7 ?8 b, V( w2 a3 n/ p 这是确定主题数时LDA模型的构建方法,一般我们可以用指标来评估模型好坏,也可以用这些指标来确定最优主题数。一般用来评价LDA主题模型的指标有困惑度(perplexity)和主题一致性(coherence),困惑度越低或者一致性越高说明模型越好。一些研究表明perplexity并不是一个好的指标,所以一般我用coherence来评价模型并选择最优主题,但下面代码两种方法我都用了。7 F" L5 X3 X/ A% F
6 V3 i. C* B# ~, @#计算困惑度 % V7 S# R7 i. X3 X/ A6 I6 Pdef perplexity(num_topics):( L: g) R* \! z# x3 h
ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30)% @# H& o" [) g' p+ K) _/ F: @7 P% K
print(ldamodel.print_topics(num_topics=num_topics, num_words=15)) , q. p" x, v6 j# c3 b" L print(ldamodel.log_perplexity(corpus))6 v- B3 c" \4 R3 E! L
return ldamodel.log_perplexity(corpus)! Y9 w k! _7 T; n
#计算coherence) ^& ^ j% O* z' i7 }
def coherence(num_topics):' C1 d6 ^0 V2 u2 f- l- z
ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30,random_state = 1) , a. w# j7 m+ p+ H7 x2 o/ n print(ldamodel.print_topics(num_topics=num_topics, num_words=10)) . ^3 T9 P5 o# I ldacm = CoherenceModel(model=ldamodel, texts=data_set, dictionary=dictionary, coherence='c_v') 3 h: G6 Z( e5 W. o2 @7 q print(ldacm.get_coherence()) 6 f% n' l8 c8 Q return ldacm.get_coherence()$ ~5 O/ B/ J/ C: s4 x: q4 _% A8 C
4.绘制主题-coherence曲线,选择最佳主题数 ( N* W. T7 D$ N! U7 j5 N$ ~x = range(1,15) / o$ ?) u+ W8 P8 y" u# z = [perplexity(i) for i in x] #如果想用困惑度就选这个! o" `" T7 L: B4 m4 C. L8 C8 H/ o$ d
y = [coherence(i) for i in x]2 y' g3 R1 g* S* }
plt.plot(x, y) ! g( Z7 f. ?' vplt.xlabel('主题数目')4 e S3 w! g3 d0 R, m
plt.ylabel('coherence大小') - L* ` i0 S( U3 @1 iplt.rcParams['font.sans-serif']=['SimHei'] , r% f8 Y) S! h: |matplotlib.rcParams['axes.unicode_minus']=False+ G6 ~+ Z+ X$ N5 f
plt.title('主题-coherence变化情况')3 H+ G- w1 P8 ^+ m& Y* A4 [0 {* N
plt.show()6 Y' D' m5 k# L/ n- t2 ^) {+ |
最终能得到各主题的词语分布和这样的图形:9 a# P0 e4 |% C* H' d
# l- d$ X+ h, G9 R 5 g1 G* X+ i' [: O9 P ; r- r) i9 g4 k3 a6 q# A/ i0 k% I 5.结果输出与可视化) ]1 q% ?. L+ h4 W% g8 C' t
通过上述主题评估,我们发现可以选择5作为主题个数,接下来我们可以再跑一次模型,设定主题数为5,并输出每个文档最有可能对应的主题 8 C t; m' I1 I* L6 l7 K5 t! U2 d$ ~
from gensim.models import LdaModel G7 z+ J2 G7 Z3 h0 e8 c- K3 \import pandas as pd : Z# ~( {' j; Y" f8 |6 h* N: b, jfrom gensim.corpora import Dictionary7 c: I# t% ~* k
from gensim import corpora, models 6 Y! Q: f% z+ W4 B; m" Ximport csv 6 t) a) `; Y: m u9 X& N 5 P6 [: V; I5 n J$ n/ g# 准备数据9 v [% B1 F2 {8 q1 c* D
PATH = "E:/data/output1.csv" 3 p7 R1 l) [$ y# T & f! S' E7 G8 g U7 Q: I bfile_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容 # K. I: _0 b7 ]3 N+ [* ] Wdata_set=[] #建立存储分词的列表% U9 T5 q$ d8 f5 J5 Q
for i in range(len(file_object2)): H/ d B, j3 ~- `2 M* s$ {
result=[] + G( j4 {/ G o seg_list = file_object2.split() . t3 y" O0 F! i k; [/ ` for w in seg_list :#读取每一行分词 " [$ y1 j. A+ _0 B' g7 | result.append(w) ' \* b' ^) U2 l. X data_set.append(result)6 ^- E7 c& v5 H- F
7 z# Q% t1 U8 y9 [# udictionary = corpora.Dictionary(data_set) # 构建词典. p: Z1 L% i* \0 K- d9 v
corpus = [dictionary.doc2bow(text) for text in data_set]8 N0 R' f( O% J# u
/ j; |# ?" u0 y7 ylda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=5, passes = 30,random_state=1) + e8 O2 f4 d4 a) ?+ ^( gtopic_list=lda.print_topics()) i0 ^& {; B) n4 v, d6 P5 u
print(topic_list)/ f! n0 A% y+ ]
$ j) P/ y$ {' K: r% Z8 m$ p/ K' ~
for i in lda.get_document_topics(corpus)[:]:; i, Y7 Y" Q% L4 }9 y1 h
listj=[] ! N1 {" X% G/ H+ x; c6 c- D# W for j in i: ; ` u! Z% n9 u+ Y) V listj.append(j[1])% K( n/ }( |& n9 n/ K
bz=listj.index(max(listj)): A3 b7 S! w4 o- {$ Y
print(i[bz][0]). _/ p, d: y8 {# ] O- c+ |8 j
( @7 p+ X" T4 A- q& w' z/ ^
同时我们可以用pyLDAvis对LDA模型结果进行可视化:+ ]; ?$ Y+ }, H0 x' h. b
& o( m8 H- ^* l& {import pyLDAvis.gensim / N6 i& y" {5 j) WpyLDAvis.enable_notebook()) c* f+ v" _* j9 @
data = pyLDAvis.gensim.prepare(lda, corpus, dictionary) # L% B' d+ ]! |- e. n. ~" xpyLDAvis.save_html(data, 'E:/data/3topic.html') * S O% h1 \4 B* N5 y. ~ 大概能得到这样的结果: . Y( _$ N" S8 F# v v' O9 j. ]# l. Y0 s! z1 }$ ?; h7 K, R6 |" x
1 Q5 [: y5 e0 M9 s- n
) [" J4 w$ i" [ y+ I! g
左侧圆圈表示主题,右侧表示各个词语对主题的贡献度。 M) g! O9 D- ~6 t! e4 T # {7 I$ d0 }! k' \1 e, {) e5 Y1 Y所有代码如下:+ l3 o O8 U. U# \1 A( x
import gensim: |; ^/ M6 }6 z+ |
from gensim import corpora; v+ E" J& {6 ?& K4 O0 M
import matplotlib.pyplot as plt- A, C+ Q% v) Z5 z7 N" L
import matplotlib 5 }+ m, y% `( H$ jimport numpy as np4 i& E# W! P3 e. O, h
import warnings& a) u9 N$ g- n" k& M
warnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarity 9 F* }( ]- s8 f " K5 ?& w. v6 b; J5 P- g& xfrom gensim.models.coherencemodel import CoherenceModel7 P& a! Q; b" F% m8 l- f
from gensim.models.ldamodel import LdaModel, v% X) G" s0 }6 X H
. t9 p. S0 t* t7 A/ A, J) J/ O
! ~7 p; A& V8 H! e6 K( W
0 y; @) D) P9 L
# 准备数据 6 l6 n6 [ _1 W ]PATH = "E:/data/output.csv"* A# i- b' m1 R" {
. D) o1 y; ]5 S; a% D9 ?0 ^
file_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容 % P* m7 K/ v0 l8 ~/ T gdata_set=[] #建立存储分词的列表- s9 i7 `3 i# B; l% r, l* Z7 f
for i in range(len(file_object2)): R' @( d" X/ Z1 O7 {+ H
result=[]8 W% V" u# ?- s1 D" }! t
seg_list = file_object2.split()- g* c$ g+ I3 J
for w in seg_list :#读取每一行分词; b+ q7 f8 ^: Y6 v8 _) b0 p
result.append(w) : c" Q" K$ F0 |6 Z# }6 n- i% D data_set.append(result)+ ]: }+ |: l$ ^6 l
print(data_set), r, @, @( b; J9 D& G+ I
3 \" R! @+ X! {, h+ C& p- Z j! ~
dictionary = corpora.Dictionary(data_set) # 构建 document-term matrix7 H* [2 P" d$ o7 H* @: f
corpus = [dictionary.doc2bow(text) for text in data_set] 3 z5 P4 z- l2 O#Lda = gensim.models.ldamodel.LdaModel # 创建LDA对象& O% y' c* _9 T) }1 h
+ M1 [! T; E, D0 e$ U2 U# Q#计算困惑度 $ d0 {% R j- ]3 H& G5 w3 T* t8 u/ sdef perplexity(num_topics): ! C$ l- }7 O* k/ ` ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30)$ r& T, H% L' o/ s1 X2 U
print(ldamodel.print_topics(num_topics=num_topics, num_words=15))! D- A) o% V5 {6 t
print(ldamodel.log_perplexity(corpus))+ `$ @: S. D* ?+ g. G. v
return ldamodel.log_perplexity(corpus) - G5 L! [7 [+ c0 \. N# l# K2 P/ s ^& f6 g1 i$ L. Q9 c
#计算coherence! I: O# w) r/ W# u5 g# e( l2 g
def coherence(num_topics):" R/ }/ S( R6 o1 P7 H3 N, w+ g, M
ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30,random_state = 1)1 J1 E( |7 I8 u1 `/ w# ?# t7 `
print(ldamodel.print_topics(num_topics=num_topics, num_words=10))0 o! K/ U8 }8 W. [: C7 b, {
ldacm = CoherenceModel(model=ldamodel, texts=data_set, dictionary=dictionary, coherence='c_v')! H4 t- y9 F; h6 @4 K3 l
print(ldacm.get_coherence())( |! j) b2 Q% w3 t9 Z
return ldacm.get_coherence()! ]# h1 x5 g, J! o% T
+ _3 ^( b: C+ |% h: D1 |
# 绘制困惑度折线图, R F4 Y7 w' V) U7 u4 h1 `. a
x = range(1,15) - A2 E/ T1 Q9 A, P# z = [perplexity(i) for i in x]/ A; _; T# Q" X
y = [coherence(i) for i in x] 5 I- e( I8 w0 B# a" t: Lplt.plot(x, y) * N* E0 F8 `5 v. jplt.xlabel('主题数目')0 |! R/ x2 G# `" Z+ ]* @" h
plt.ylabel('coherence大小') " t) s8 n* G1 t6 Aplt.rcParams['font.sans-serif']=['SimHei']$ g- p8 I2 d0 |9 q/ k$ q
matplotlib.rcParams['axes.unicode_minus']=False0 y i1 }0 o5 b q
plt.title('主题-coherence变化情况'), H5 g! d4 S, u' R4 I2 h4 q% z
plt.show() & t/ Z, L4 s0 v9 H! f- N8 t ! z# F9 h% M% Z& Afrom gensim.models import LdaModel, u: a$ m) z. f' _; j2 j
import pandas as pd 3 {/ H( g3 n1 kfrom gensim.corpora import Dictionary 2 L" T0 ~# x7 c2 ~+ ]" Xfrom gensim import corpora, models) j7 I; _- w$ b! I
import csv E2 j6 g3 A: T
9 [4 s) ] O1 U' V! `% n/ e
# 准备数据 ( Y a) c6 [0 `0 q% Y1 CPATH = "E:/data/output1.csv"0 C) T4 a; V& T5 H' H
0 W' P: O. G% N# G. rfile_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容- ~( h4 ^2 u) @! A. l( e
data_set=[] #建立存储分词的列表" J) W. z, Q; X2 Z+ u
for i in range(len(file_object2)):7 _. N' T9 d* j p" q. `; |7 c
result=[] g+ J( e+ E7 W& y6 |2 M seg_list = file_object2.split() 6 w- d. s4 u( y for w in seg_list :#读取每一行分词 - d) S0 p* s- z- e4 c5 \/ N0 n/ C' L result.append(w) / k b; A; {) \( M9 b H data_set.append(result): _" j3 G0 B8 D7 t1 H" D" }% D
4 C5 E' g' o8 n% c
dictionary = corpora.Dictionary(data_set) # 构建 document-term matrix 0 B2 @5 c, z/ S& E8 j- O( Ycorpus = [dictionary.doc2bow(text) for text in data_set]& F& F: f/ \* b, ~: Z8 J0 J
& A: H3 s/ [% v! m& @lda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=5, passes = 30,random_state=1)# X3 \. @7 `$ N# b) x
topic_list=lda.print_topics() % y. H4 ?, u( R# W1 ?8 `( vprint(topic_list) - ]( f/ P5 [$ c; X, U2 C2 v. @" z. {5 Y6 X
result_list =[]9 ]1 b |3 `8 X
for i in lda.get_document_topics(corpus)[:]: & W! D4 J3 L( r listj=[] & P- \; T& P9 F0 @9 o0 b; I for j in i:9 X& T- q* h5 b* y- w
listj.append(j[1]): M) S' S* H$ K; X! N6 \4 `
bz=listj.index(max(listj)) 9 E) Y) U$ B& u/ \5 o# x# _2 p result_list.append(i[bz][0]) $ _2 J h1 T9 ^8 Q3 _& {7 n) s4 Hprint(result_list) : Z& n* e* C2 J6 j: q7 X% m8 x " r1 Y1 I1 v, Z" Y( Timport pyLDAvis.gensim: G: ?" j9 A' s
pyLDAvis.enable_notebook()0 x/ e) Q- I7 o. \4 m$ M0 M
data = pyLDAvis.gensim.prepare(lda, corpus, dictionary)" j4 i1 ]7 N9 Q6 ~' v+ C
pyLDAvis.save_html(data, 'E:/data/topic.html') ( C, N. b$ K8 E* e8 Y; L% J有需要自取~, `& C4 A1 g7 b* G/ l
————————————————5 H V* o m4 G# R w5 p
版权声明:本文为CSDN博主「阿丢是丢心心」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 * s+ v& P6 r7 L原文链接:https://blog.csdn.net/weixin_41168304/article/details/122389948% y& {6 L: i: v+ M) b
5 e2 p4 c( l0 m( E6 E
, @: v$ }; r- K4 f- k