LDA主题模型简介及Python实现 1 R0 U% w; h/ F' ?/ \- H5 Z& v5 i
一、LDA主题模型简介4 N2 u5 p. B* y" K# {1 y( z7 k6 ]
LDA主题模型主要用于推测文档的主题分布,可以将文档集中每篇文档的主题以概率分布的形式给出根据主题进行主题聚类或文本分类。- o a$ M- n# l, z' w- M
" u4 C0 ^$ z& g LDA主题模型不关心文档中单词的顺序,通常使用词袋特征(bag-of-word feature)来代表文档。词袋模型介绍可以参考这篇文章:文本向量化表示——词袋模型 - 知乎 , C* P. h8 G/ @; A- b. s0 W* y$ t, U i- ^
了解LDA模型,我们需要先了解LDA的生成模型,LDA认为一篇文章是怎么形成的呢?* h+ O H6 u# g7 O# T
* Y* V1 Y3 G. q1 B. X LDA模型认为主题可以由一个词汇分布来表示,而文章可以由主题分布来表示。 : i$ {1 M# ? r5 R* Y5 q9 B' U% v; L7 H8 Q: v2 O4 N. n
比如有两个主题,美食和美妆。LDA说两个主题可以由词汇分布表示,他们分别是:/ o" V, p* n2 R
P: s% H: k$ g! a{面包:0.4,火锅:0.5,眉笔:0.03,腮红:0.07} 6 |8 O% b$ O5 i6 @9 y3 U{眉笔:0.4,腮红:0.5,面包:0.03,火锅:0.07}, b5 M0 M( W" ?( k1 X+ ^2 N. ^
1 y. f, G5 s# N
同样,对于两篇文章,LDA认为文章可以由主题分布这么表示:) b2 L7 \$ ?: n5 t! s
" w# }) J" i t3 B' g8 b* p
《美妆日记》{美妆:0.8,美食:0.1,其他:0.1} F3 [+ M* N" D3 ]4 B& Q# a
/ W' s3 f/ H! H( B9 N
《美食探索》{美食:0.8,美妆:0.1,其他:0.1}- C8 z6 [9 H1 m# A* G8 e2 z' E
# z1 a# F% y$ r! T v 所以想要生成一篇文章,可以先以一定的概率选取上述某个主题,再以一定的概率选取那个主题下的某个单词,不断重复这两步就可以生成最终文章。* s% N) Y; \: K# ~
& B7 E6 m1 j! V8 g 在LDA模型中,一篇文档生成的方式如下:& _, ]3 g4 M" A) @! H
( r8 N7 s+ R0 O3 I
/ ~7 J/ S+ e* N0 J
6 B( ~- w* Z& q2 n 其中,类似Beta分布是二项式分布的共轭先验概率分布,而狄利克雷分布(Dirichlet分布)是多项式分布的共轭先验概率分布。 ! m3 M$ u/ [/ I+ ]4 g4 r & Y/ `* ~8 ?2 F2 P9 g; U * A/ w3 z3 `* S+ _* d8 K6 ~! q" }6 t7 y; e; X; a
如果我们要生成一篇文档,它里面的每个词语出现的概率为: - h0 C4 H( u, {8 E2 v2 }! D 8 M# G$ J# a6 g - C" Z- V0 `( d% V3 S% q r, g* H0 I7 \
更详细的数学推导可以见:通俗理解LDA主题模型_结构之法 算法之道-CSDN博客_lda模型 3 W" {3 U. i2 g8 v! h) P1 y. \# f. y. U a
看到文章推断其隐藏的主题分布,就是建模的目的。换言之,人类根据文档生成模型写成了各类文章,然后丢给了计算机,相当于计算机看到的是一篇篇已经写好的文章。现在计算机需要根据一篇篇文章中看到的一系列词归纳出当篇文章的主题,进而得出各个主题各自不同的出现概率:主题分布。 5 B* c' P& t. C5 P % f2 U9 ?# F3 t$ W6 _ 至于LDA主题模型在计算机中具体是怎么实现的,我们也可以不必细究,现在有很多可以直接用来进行LDA主题分析的包,我们直接用就行。(没错,我就是调包侠), Q+ d. f& b# j! ^4 [ D
% `9 g ]" n, S
二、Python实现" y5 ^' B: s/ N; {+ D
在用Python进行LDA主题模型分析之前,我先对文档进行了分词和去停用词处理(详情可以看我之前的文章:用python对单一微博文档进行分词——jieba分词(加保留词和停用词)_阿丢是丢心心的博客-CSDN博客_jieba 停用词)! }$ l8 F( z ^6 X% M1 N
. I" S, N9 R9 |7 W, @' z 我下面的输入文件也是已经分好词的文件4 j5 b. Q! [- f4 h) v/ o" A
a1 i" f& H0 z8 n1.导入算法包 ' z$ L) e( V+ r' m* U$ N/ o3 Timport gensim " d, |/ b: I: b2 ^, {. afrom gensim import corpora , l. e8 s2 m" t3 D( Wimport matplotlib.pyplot as plt / R/ K% E8 f/ Jimport matplotlib + l' C3 Z2 V* O# vimport numpy as np5 U* b5 {" o& R9 M: I) i
import warnings % _9 t+ d* C1 V$ a$ r1 U3 i" Kwarnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarity* o; y4 V: M7 j/ w2 `2 E- m
5 q: U% `6 Z9 X _& m/ E8 L" S4 J
from gensim.models.coherencemodel import CoherenceModel4 r1 G, v% ?, U3 t& O5 F) Q
from gensim.models.ldamodel import LdaModel . x1 F" U. |2 b% e# S, u2.加载数据7 i0 J7 I* V& C2 P
先将文档转化为一个二元列表,其中每个子列表代表一条微博:% f/ q! h5 o+ ^4 q- w. o
F( d5 G6 f, O3 APATH = "E:/data/output.csv") d% L" U/ d h( r# i
7 L& D. G. `+ d- L! Afile_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容/ l2 }$ c5 H* L
data_set=[] #建立存储分词的列表 " D8 K, I/ ^. \& z$ afor i in range(len(file_object2)): 0 \ i5 T* O: Y9 i; M result=[] + O" ]. A2 G' S4 T) Y# ~ seg_list = file_object2.split() : p) ^* O4 A/ Q/ B) V, i- y( F for w in seg_list : #读取每一行分词 . }+ r, n" Y6 F$ o r result.append(w) 9 k5 _# S! o8 L- `2 T- n, f" E data_set.append(result)) h+ g0 E# _, g5 k
print(data_set)3 s' k7 z& _7 P$ T
构建词典,语料向量化表示: - u4 G0 G6 Q5 K' M/ B; v' j& I* i' D# I( g% N
dictionary = corpora.Dictionary(data_set) # 构建词典' y. O: P2 L" |* A$ s& }
corpus = [dictionary.doc2bow(text) for text in data_set] #表示为第几个单词出现了几次 0 n. b8 e2 r2 \% J F# y3.构建LDA模型 ; {5 T, ~) @+ ]5 jldamodel = LdaModel(corpus, num_topics=10, id2word = dictionary, passes=30,random_state = 1) #分为10个主题2 O4 P. Y$ Q' h1 Q
print(ldamodel.print_topics(num_topics=num_topics, num_words=15)) #每个主题输出15个单词 " c! y: Z. P/ k% A1 x) i. B 这是确定主题数时LDA模型的构建方法,一般我们可以用指标来评估模型好坏,也可以用这些指标来确定最优主题数。一般用来评价LDA主题模型的指标有困惑度(perplexity)和主题一致性(coherence),困惑度越低或者一致性越高说明模型越好。一些研究表明perplexity并不是一个好的指标,所以一般我用coherence来评价模型并选择最优主题,但下面代码两种方法我都用了。2 P4 b& F& \# w" D6 F+ W/ O
0 ?( I' h1 s4 B9 p
#计算困惑度 d, M: c2 o) O8 ldef perplexity(num_topics):1 D8 ~2 O" @, V4 }1 }
ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30): B, G* s! n1 P/ _
print(ldamodel.print_topics(num_topics=num_topics, num_words=15)), l% v8 Q2 |7 h& d9 H
print(ldamodel.log_perplexity(corpus)) 0 E' \, M, u9 ~ return ldamodel.log_perplexity(corpus)4 P* r9 c& |. \" _! U3 M
#计算coherence 5 s1 R" K) A0 M3 h9 ^1 c- R$ Fdef coherence(num_topics):# P9 F' p, m5 T+ {3 N7 R1 p
ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30,random_state = 1)2 p; T9 I; a+ y' ?1 s% c
print(ldamodel.print_topics(num_topics=num_topics, num_words=10))1 L' W0 u: [$ [* i" I" p
ldacm = CoherenceModel(model=ldamodel, texts=data_set, dictionary=dictionary, coherence='c_v'): S& A; g7 j7 A1 w( D% e: D0 M2 u( Y
print(ldacm.get_coherence())7 r$ w" J( f a$ `
return ldacm.get_coherence()2 }! C" `0 }; t+ ]+ M/ g
4.绘制主题-coherence曲线,选择最佳主题数" ?* o- R2 `3 ` d
x = range(1,15)+ ]/ I/ d$ r# @7 X$ ]
# z = [perplexity(i) for i in x] #如果想用困惑度就选这个1 x5 k* p* j0 q9 ?' Z1 U
y = [coherence(i) for i in x]! j' b' Y* W/ Q* ]) K
plt.plot(x, y); t3 e; t1 A7 k6 |; \+ @, F
plt.xlabel('主题数目')# Z2 x) L. i$ e5 ]' h. t% @
plt.ylabel('coherence大小')) V4 o! _* m* @: o, y- J
plt.rcParams['font.sans-serif']=['SimHei'] 8 {" N0 H- N9 g+ A' Pmatplotlib.rcParams['axes.unicode_minus']=False: `9 [. D9 ^# u9 m
plt.title('主题-coherence变化情况') 4 J2 a" M2 C+ n. j$ b# f7 u- Jplt.show()' |: w- m) G' i C
最终能得到各主题的词语分布和这样的图形: & O$ X( x$ C5 L- R7 i: C% n" P+ v# v5 U4 F
' h) A+ A6 P1 H2 Y+ L1 b
' I ?1 Q5 ]0 S) T 5.结果输出与可视化 ; p5 j/ w! g; t3 x( q" p- \. V( V+ m 通过上述主题评估,我们发现可以选择5作为主题个数,接下来我们可以再跑一次模型,设定主题数为5,并输出每个文档最有可能对应的主题# S' }& ^6 Z& z+ U2 Z) ]5 t2 Y$ K% ?
* P$ ]' X/ U/ E' e7 J$ M9 g% n2 zfrom gensim.models import LdaModel ; k6 ?3 c- M% v6 [. ^+ Yimport pandas as pd/ Q8 A Y( [9 h& q; l: _0 @
from gensim.corpora import Dictionary5 l7 |+ n2 s& e& k7 T
from gensim import corpora, models0 I9 s* c; n( `" |6 F- A- E
import csv8 ~7 b. R9 Z; A9 C1 T! G' y
: y5 ~! S) L( o' H3 s( |
# 准备数据6 S! x3 X9 |( _" U' F. k+ N
PATH = "E:/data/output1.csv"% H1 N$ Y% V G U. V5 D' o2 }
; e, Z- }7 d" j" k9 l- j: C
file_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容 ! w' L& P( C9 qdata_set=[] #建立存储分词的列表 w: ]8 E8 ?) t$ v& |3 q- u5 Lfor i in range(len(file_object2)):5 K* c( \( o! Z S
result=[] ; d7 ~3 n& K" t- K1 ~/ [+ h |3 x3 b seg_list = file_object2.split(): e- d( H, s: A$ E
for w in seg_list :#读取每一行分词" c+ G$ }# H; T/ [# U
result.append(w)5 R2 l3 M# R b" N- f
data_set.append(result)" u. b2 l D1 {- \( H* W& o
' s8 h; n- x8 i, l' }) }
dictionary = corpora.Dictionary(data_set) # 构建词典/ j5 q5 s' q# m6 k* U
corpus = [dictionary.doc2bow(text) for text in data_set]% Z: W, X. O$ s/ ]: ~- k! i
! Z. }6 }+ o9 x5 u, ?* r4 z( llda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=5, passes = 30,random_state=1) % M2 K# J; f% M$ |2 c; j( P `topic_list=lda.print_topics() 2 L' n2 w. h! D9 j% fprint(topic_list)+ M7 A8 d7 n& R
; k6 F; O9 M' x9 `
for i in lda.get_document_topics(corpus)[:]: 8 L& _1 x$ w( q% B listj=[] ! }5 a- |( ^; x) N) S for j in i:' M6 |1 R8 S- V0 {2 Z" ^( l
listj.append(j[1]) * n* o0 [' U5 ~3 { bz=listj.index(max(listj)) 8 G/ U. I4 ]# f3 T print(i[bz][0]) ' f8 a4 p" O$ m# |4 N: M 1 L# i; M' L$ { `% P: T" V6 |6 M 同时我们可以用pyLDAvis对LDA模型结果进行可视化:3 R* Q+ p4 Y" G4 R- y# g3 U0 @4 ^* ~
2 K' f1 Z( u8 F7 R& C" R6 |: D6 o6 ]
import pyLDAvis.gensim ! `6 s& O- G! v- fpyLDAvis.enable_notebook() " O4 @3 X/ s% b/ q5 ^data = pyLDAvis.gensim.prepare(lda, corpus, dictionary) ( \" ~$ O0 t9 @pyLDAvis.save_html(data, 'E:/data/3topic.html') & O9 A) [5 N0 g8 } 大概能得到这样的结果:3 U1 C5 n- F6 n# I1 _& U
: b) V' f0 s2 V
. T% C. Q7 l1 e5 U" u) t- R3 B' {
% @6 D/ C6 \. m+ R 左侧圆圈表示主题,右侧表示各个词语对主题的贡献度。6 F( X- ]' T. H6 V# n
# I& }8 E9 E% v& W
所有代码如下:3 u: Y- M# a. `; S$ u# X; F
import gensim) @5 h, i1 V U" ]6 \' U8 {
from gensim import corpora & F9 d0 Y/ A* Q/ w7 s% t+ ?& }" z$ simport matplotlib.pyplot as plt/ c5 D% a( a; z; T2 e
import matplotlib1 \: I1 R5 f! w; `
import numpy as np! I6 P) g# V5 y# K
import warnings 1 h: j0 k8 h8 Hwarnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarity" A9 N+ }* P( N$ Y( _
/ S1 B4 h8 q4 m: }! Rfrom gensim.models.coherencemodel import CoherenceModel 2 T$ C- z8 d* T2 Efrom gensim.models.ldamodel import LdaModel 7 ^! V- w+ a2 W% }4 R7 ]" U / P \$ A; Z8 o, H8 g * }6 j3 V$ s4 f6 p, C + u* W0 v* C, {" F# m # 准备数据( |8 e! ?$ y4 q; j1 x4 L
PATH = "E:/data/output.csv" / _) Z& P {9 v; J( x2 i1 | 9 W. t m. ~3 J4 c7 rfile_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容 ) T7 X' b" F" ?9 ? P( r+ \( E! sdata_set=[] #建立存储分词的列表 + d; s+ R2 m3 h8 r9 U+ }for i in range(len(file_object2)):9 b3 V0 a x4 f6 T d7 U* V
result=[] 3 G/ X- s( A( ` seg_list = file_object2.split() 2 Q1 e+ X: T( d- d4 P* B for w in seg_list :#读取每一行分词7 d, w8 \1 P+ M z* S$ I9 z0 y4 b9 l. c
result.append(w) - y; Z$ ~% V: [: n' W6 x; q9 M9 i3 H, I data_set.append(result)5 ]0 z7 O& D$ W2 a: R( ^
print(data_set)# M! _8 n, A" e" y! {9 f- @
7 M% D% S. `3 c( ?; o+ [
& F0 o+ O. {5 l9 z! N* y2 adictionary = corpora.Dictionary(data_set) # 构建 document-term matrix2 ]% b i" ~7 Y: \& j* V/ \
corpus = [dictionary.doc2bow(text) for text in data_set] - L! _, }9 a. ^$ ^0 W8 J#Lda = gensim.models.ldamodel.LdaModel # 创建LDA对象 2 V5 ?2 D, w5 `9 t $ H' ], g" J C" u#计算困惑度( t1 z2 k' L4 y, E
def perplexity(num_topics): 2 E7 E( b6 Y; I1 A9 M5 O; }1 h ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30) 5 [5 |- H3 _# i print(ldamodel.print_topics(num_topics=num_topics, num_words=15)) R' Z I: l! K7 y; r" R print(ldamodel.log_perplexity(corpus))1 [% ~) ~5 q4 x
return ldamodel.log_perplexity(corpus). |' z" u1 T: Y1 W" x
^0 H' V; o! |/ {' ^. A) }) Z, A#计算coherence ' y: d/ C6 r+ M8 B, \5 e% Adef coherence(num_topics):. B( O# F( s5 L
ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30,random_state = 1) ( ?- E8 T3 e6 _* n5 g3 r print(ldamodel.print_topics(num_topics=num_topics, num_words=10)) ! `: ^+ M V+ L6 e, R+ m ldacm = CoherenceModel(model=ldamodel, texts=data_set, dictionary=dictionary, coherence='c_v') ! f5 O& l6 y- I1 H5 W& Z print(ldacm.get_coherence())$ V9 x* ]9 c2 s# X5 Y B
return ldacm.get_coherence()1 ]2 |0 v9 X; U
9 _1 A9 h X& o* T0 {$ \
# 绘制困惑度折线图* q& V) j ?3 K* P1 g5 }
x = range(1,15)2 z, t8 `. L. q) p" s$ T, O$ O
# z = [perplexity(i) for i in x] & E: y, t1 b, K5 w- a" Py = [coherence(i) for i in x] Z, T5 O/ b; \
plt.plot(x, y)4 m+ m1 N& } z* [3 P0 i! U
plt.xlabel('主题数目')& j1 N8 X0 h) g7 r+ R+ v" Q
plt.ylabel('coherence大小')" H- m3 P: d+ i
plt.rcParams['font.sans-serif']=['SimHei']" v! W8 R d2 t) C/ N
matplotlib.rcParams['axes.unicode_minus']=False, H! M( {& B: j" v @/ V! [5 S4 @
plt.title('主题-coherence变化情况')( g" I1 H5 Z9 z- y9 a6 h5 m( P5 H
plt.show()( G5 [9 z5 a- q, U! S
$ j" H7 {$ `1 K6 `from gensim.models import LdaModel 3 s+ P8 U! J6 f! u' F; iimport pandas as pd & i# w4 E/ j: r+ @$ ~* c( P/ mfrom gensim.corpora import Dictionary9 I5 P- P5 X$ F f; J$ ^
from gensim import corpora, models. B! d. p) [) z
import csv + a( N9 b3 n( n/ q( q% c$ o" L) k ; |1 f& X9 I p# d5 G+ p b# 准备数据 + R' s6 o# `) s' \PATH = "E:/data/output1.csv" ! x1 Y* H# a1 Y 6 P6 X; N7 z- o8 [4 r( lfile_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容/ x8 r+ o f" b8 S
data_set=[] #建立存储分词的列表: K6 r$ ^& F M1 {2 y
for i in range(len(file_object2)):' ~) L/ e: |; H4 J2 I0 f, C
result=[]0 {' f0 [ Z+ d3 y) P7 G
seg_list = file_object2.split() , d7 ~5 a5 V- b' h; X; H0 \ for w in seg_list :#读取每一行分词 ) g' S! R% w% _8 _" O result.append(w) / N1 y7 s- d2 `' r! p; r5 X- c8 C data_set.append(result) $ v8 Q; ~& P- a$ N$ s S8 P% F: r 3 ~7 }" A+ Q$ A" jdictionary = corpora.Dictionary(data_set) # 构建 document-term matrix 8 L, Y6 F) \$ Q& ]corpus = [dictionary.doc2bow(text) for text in data_set] 1 h& c( ?9 c2 t# W2 l 8 Z3 T$ M- o5 ~; i7 P/ S) x* u$ [lda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=5, passes = 30,random_state=1)- U: [# O3 ~6 X/ f9 c9 J
topic_list=lda.print_topics()+ }; s K- p% u6 T1 H) U% B3 _
print(topic_list)6 q. P+ X1 k" C% H9 w
4 Y6 @. T& B5 m! `* q: q/ T
result_list =[]+ E* e0 R' t9 C O
for i in lda.get_document_topics(corpus)[:]:8 ~- _$ w( z4 J1 D Y& a( h
listj=[] - i5 Y" t$ Y- @+ g7 m/ z' _5 v for j in i:' ^1 w, G: r2 x
listj.append(j[1]) m. Q! R7 c# Y% p% H
bz=listj.index(max(listj))# }/ r5 M) E7 E# ?# c
result_list.append(i[bz][0]) 5 n" T; m) K$ V* ^/ e5 ?, _print(result_list) 5 h _) Y6 X( A" H8 l 5 S [1 n3 f1 e9 u3 e8 R9 ^% Jimport pyLDAvis.gensim & [4 x8 ]8 [' {0 _* a! ^4 v. ?pyLDAvis.enable_notebook() + d5 B) V8 ~" ldata = pyLDAvis.gensim.prepare(lda, corpus, dictionary) 1 I8 O% w' F7 k/ g! @pyLDAvis.save_html(data, 'E:/data/topic.html') ; G2 {: u" h8 F+ {# ]& t# J4 A有需要自取~% q" D. F' ?7 d) B
————————————————/ T2 ?) }9 L, T! L7 m l; m
版权声明:本文为CSDN博主「阿丢是丢心心」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。+ M& E: R1 ]* ^! y8 p6 y# _
原文链接:https://blog.csdn.net/weixin_41168304/article/details/122389948 * Z) x0 V- t; ^2 }* X) Q% N1 ~" H, T( _. o) g' Q8 l
! h# h) t6 G- v5 V$ H$ N