- 在线时间
- 1630 小时
- 最后登录
- 2024-1-29
- 注册时间
- 2017-5-16
- 听众数
- 82
- 收听数
- 1
- 能力
- 120 分
- 体力
- 565622 点
- 威望
- 12 点
- 阅读权限
- 255
- 积分
- 174909
- 相册
- 1
- 日志
- 0
- 记录
- 0
- 帖子
- 5313
- 主题
- 5273
- 精华
- 3
- 分享
- 0
- 好友
- 163
TA的每日心情 | 开心 2021-8-11 17:59 |
|---|
签到天数: 17 天 [LV.4]偶尔看看III 网络挑战赛参赛者 网络挑战赛参赛者 - 自我介绍
- 本人女,毕业于内蒙古科技大学,担任文职专业,毕业专业英语。
 群组: 2018美赛大象算法课程 群组: 2018美赛护航培训课程 群组: 2019年 数学中国站长建 群组: 2019年数据分析师课程 群组: 2018年大象老师国赛优 |
LDA主题模型简介及Python实现- u) @: M& T ]
- U; G9 D) e7 z; B8 A5 n一、LDA主题模型简介1 W4 b* s! S4 z3 `, {
LDA主题模型主要用于推测文档的主题分布,可以将文档集中每篇文档的主题以概率分布的形式给出根据主题进行主题聚类或文本分类。/ {# y- q8 y# l: {. V0 M# k- K T
* o# t4 _$ T1 `; \+ \$ N
LDA主题模型不关心文档中单词的顺序,通常使用词袋特征(bag-of-word feature)来代表文档。词袋模型介绍可以参考这篇文章:文本向量化表示——词袋模型 - 知乎; m' B0 H! c1 s4 R
+ J" y5 f; q9 {, p2 Y 了解LDA模型,我们需要先了解LDA的生成模型,LDA认为一篇文章是怎么形成的呢?. e4 Y& t; N. `$ ]" M1 V( i! w0 ^+ [9 u
7 f" Z# H; h5 j+ c& m0 S
LDA模型认为主题可以由一个词汇分布来表示,而文章可以由主题分布来表示。
0 ~/ V) }0 s+ l. P
- { o' W2 X+ b) K+ }; w2 D- _ 比如有两个主题,美食和美妆。LDA说两个主题可以由词汇分布表示,他们分别是:
' D: q. M5 B) I, E* g
5 |& k" Q5 l# J. u{面包:0.4,火锅:0.5,眉笔:0.03,腮红:0.07}' N9 O9 [4 E! V9 g X% z# Y7 u% P
{眉笔:0.4,腮红:0.5,面包:0.03,火锅:0.07}
; ~ j% d# c; v# T# x: }7 y* r* f) y2 T, w( e" L, m
同样,对于两篇文章,LDA认为文章可以由主题分布这么表示:
; f- o. C" m( q0 i0 ]/ z+ \- e- k
《美妆日记》{美妆:0.8,美食:0.1,其他:0.1}- N. M1 W8 t, b- z: K
! E& c P6 C( A' P; ^
《美食探索》{美食:0.8,美妆:0.1,其他:0.1}
/ c1 l- H" {" }+ ^9 C- h' Q2 u3 X: L9 ?$ `9 ~
所以想要生成一篇文章,可以先以一定的概率选取上述某个主题,再以一定的概率选取那个主题下的某个单词,不断重复这两步就可以生成最终文章。
) N6 e( s0 [$ w$ v1 T6 g8 l9 `% m* y" p, B4 t
在LDA模型中,一篇文档生成的方式如下:
) j% [! Q/ C% U' c: e. a2 p4 O( }2 E! C2 n' Z4 f
6 H% ~; n7 S+ m; ~
9 g% x* [/ S# v0 c5 S 其中,类似Beta分布是二项式分布的共轭先验概率分布,而狄利克雷分布(Dirichlet分布)是多项式分布的共轭先验概率分布。
+ t. c5 w* S, C! w. k; {" u6 v; g+ f
b# x( e* N9 w \* f& h& y
4 K5 o- Z3 { w5 m% r5 B
如果我们要生成一篇文档,它里面的每个词语出现的概率为:, I) W V- ~5 ]7 ?8 ~) h
& ]" ^* y3 @4 U$ E# j# t8 U: v9 i8 s6 t
7 m0 i! l) m! x0 ?; j# r. m 更详细的数学推导可以见:通俗理解LDA主题模型_结构之法 算法之道-CSDN博客_lda模型7 L0 I4 @" h. s# p D4 g, a- `7 Z
% ~3 @' Z a! R6 Q6 t. j2 e% ^
看到文章推断其隐藏的主题分布,就是建模的目的。换言之,人类根据文档生成模型写成了各类文章,然后丢给了计算机,相当于计算机看到的是一篇篇已经写好的文章。现在计算机需要根据一篇篇文章中看到的一系列词归纳出当篇文章的主题,进而得出各个主题各自不同的出现概率:主题分布。2 y4 k- Y, m8 T! E
5 z$ u l' M; M2 o( s7 U
至于LDA主题模型在计算机中具体是怎么实现的,我们也可以不必细究,现在有很多可以直接用来进行LDA主题分析的包,我们直接用就行。(没错,我就是调包侠)
4 ^* {: N1 F" k N9 q; Q0 _. q1 d9 T) Y6 v) e! m
二、Python实现
1 V- t6 E2 S0 i: |& i# s) i2 x 在用Python进行LDA主题模型分析之前,我先对文档进行了分词和去停用词处理(详情可以看我之前的文章:用python对单一微博文档进行分词——jieba分词(加保留词和停用词)_阿丢是丢心心的博客-CSDN博客_jieba 停用词)' L% ^' j+ w% Y* |- Q
0 p, o# v) m. N3 e
我下面的输入文件也是已经分好词的文件7 E9 k! U1 Z6 b; K; t
$ k/ a, u& P7 V- ^( D8 A1.导入算法包! U U$ A7 M# V& f2 u* V6 z
import gensim& C! F) L' t1 o3 X6 `
from gensim import corpora
: }7 c3 T' B/ W: x" y8 D; \0 Ximport matplotlib.pyplot as plt1 m9 E" q: W4 u5 {* C
import matplotlib! ?. @0 |' U6 {# A2 Q+ t$ \
import numpy as np
, {0 U, W/ p' @& @1 t: dimport warnings2 O1 [2 a6 n8 j. A0 ~/ W
warnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarity$ x! U4 d! h0 j+ F5 n
' q9 y* `- ~" s1 V# D
from gensim.models.coherencemodel import CoherenceModel
$ e% z. G( A6 S* C. G8 H( Zfrom gensim.models.ldamodel import LdaModel
- \( c* j8 l, ~9 F! J+ q2.加载数据8 |2 g/ Q+ A0 W \5 H& c
先将文档转化为一个二元列表,其中每个子列表代表一条微博:
4 y3 s r" m4 _$ O# ^ r
; q; Z- ^- A$ U! r' S, ^PATH = "E:/data/output.csv"
, t a, r; J( H: E' v3 ^4 e% y, L, U" ]+ I1 f
file_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容
9 D8 }/ i2 i8 c1 B% Pdata_set=[] #建立存储分词的列表* u* H" C) m: L$ F
for i in range(len(file_object2)):$ |3 N+ m' A2 u1 U: B6 @
result=[]
9 o; z3 S) E- s seg_list = file_object2.split(); W/ _+ b- I, Y& F( N
for w in seg_list : #读取每一行分词: I# k/ J: h2 g- J
result.append(w)
& m' z9 D: ~4 K" A data_set.append(result)
- i/ ]7 x; ^( W5 ~& F0 v5 Jprint(data_set)( t2 W; i* G5 i9 a' }5 z2 V
构建词典,语料向量化表示:
. f' k$ a! K& w% g) M* e: O3 X+ a
h% L/ ~% g. G& `dictionary = corpora.Dictionary(data_set) # 构建词典! ?) Z6 @% J7 x3 v5 F8 d
corpus = [dictionary.doc2bow(text) for text in data_set] #表示为第几个单词出现了几次
8 `. X" x2 E; K; z) d' Y3.构建LDA模型/ D# U# s8 @: w5 @. P% B- S
ldamodel = LdaModel(corpus, num_topics=10, id2word = dictionary, passes=30,random_state = 1) #分为10个主题
^! m' t: `* d3 ~+ h. ^& h! Gprint(ldamodel.print_topics(num_topics=num_topics, num_words=15)) #每个主题输出15个单词
T/ m0 Z, \# D# Q8 m" X 这是确定主题数时LDA模型的构建方法,一般我们可以用指标来评估模型好坏,也可以用这些指标来确定最优主题数。一般用来评价LDA主题模型的指标有困惑度(perplexity)和主题一致性(coherence),困惑度越低或者一致性越高说明模型越好。一些研究表明perplexity并不是一个好的指标,所以一般我用coherence来评价模型并选择最优主题,但下面代码两种方法我都用了。
4 D* m/ D2 i3 p0 J
* t3 b0 c2 l, _# ~* g#计算困惑度
) G3 h- X) L1 j Q8 z. m8 U4 ddef perplexity(num_topics):4 {' S3 m# p& ]+ C+ u. h
ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30); ?1 Y: U0 x7 L* r) W! g3 i% }
print(ldamodel.print_topics(num_topics=num_topics, num_words=15))& i ~0 K7 E, D E
print(ldamodel.log_perplexity(corpus))
; i/ E$ a1 {) x return ldamodel.log_perplexity(corpus)6 ?0 j5 X6 z- n2 K- a& O% s
#计算coherence& J+ v1 N0 _) J! a
def coherence(num_topics):
% c6 v# n5 h6 k% U9 k ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30,random_state = 1)- ? G) x% F" h& @
print(ldamodel.print_topics(num_topics=num_topics, num_words=10))
( m( }# m$ p. K- k ldacm = CoherenceModel(model=ldamodel, texts=data_set, dictionary=dictionary, coherence='c_v')
* `2 G# `4 |7 u4 ~6 ~; ]$ Z7 c1 S5 R print(ldacm.get_coherence())
( T! V7 ~ b: }; f% b ]+ d return ldacm.get_coherence()! @) i* w- S2 l" \ p7 l
4.绘制主题-coherence曲线,选择最佳主题数
r1 X' L2 K' P1 Gx = range(1,15)( W! W- ?0 `* p. |
# z = [perplexity(i) for i in x] #如果想用困惑度就选这个
3 O( q% h% w; E( yy = [coherence(i) for i in x]
' o6 g$ g/ M9 ]4 \plt.plot(x, y)) r1 c% @. ]" O/ i- j
plt.xlabel('主题数目')
* V- x' o9 b* E, splt.ylabel('coherence大小'); u4 x, I; P% Z& t
plt.rcParams['font.sans-serif']=['SimHei']
3 W$ m0 |# P7 i% \+ w7 f3 V3 Y2 Nmatplotlib.rcParams['axes.unicode_minus']=False& C& _* T$ R% ]; d" y2 C
plt.title('主题-coherence变化情况')
& R" h! w+ S3 U6 [7 W" Wplt.show()
( V8 w+ W7 z; i; h0 O/ A 最终能得到各主题的词语分布和这样的图形:' m6 [. k. L' G( Z, x \
) l6 n5 t) e5 [( ` S- W i9 c
% v8 G' _% ?1 H6 U1 I$ z- y+ A# d+ I) _/ v a5 H
5.结果输出与可视化
$ ]0 {- V0 c1 ]( E9 a 通过上述主题评估,我们发现可以选择5作为主题个数,接下来我们可以再跑一次模型,设定主题数为5,并输出每个文档最有可能对应的主题; `; b. W1 q) P7 d7 n$ v
1 b' u; D& K; k, S; @4 e) I- L
from gensim.models import LdaModel
8 _3 K7 @' k' p* Qimport pandas as pd. u0 L m4 j4 | l' e! l
from gensim.corpora import Dictionary1 O3 d5 N$ _( C( @; A) n
from gensim import corpora, models% f- c; F& T2 G4 E" g2 f, }4 f8 f, C
import csv+ Z( T6 m+ V" G1 M! Q6 n6 Z
, [1 J* R6 L6 Q: j# 准备数据9 ~+ \* X: \9 w4 U0 Q
PATH = "E:/data/output1.csv"
; L; d$ Q0 Q1 T _6 O5 Z
% z) k- T9 g0 R% G( G! Ifile_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容
" G' Y" p7 m) ~7 Hdata_set=[] #建立存储分词的列表7 G' J$ ~; J7 i2 L2 R0 ^& X
for i in range(len(file_object2)):
* N# F; N6 s, [: [! W0 G. v9 c result=[]
) @: w) p: [/ g/ J$ D+ r! \ seg_list = file_object2.split(); u& W2 q& @( W3 Q
for w in seg_list :#读取每一行分词7 o& g* X$ k8 V- i- u
result.append(w)
3 k* z" F% U. a: @( G8 q1 u* | data_set.append(result)% u9 y0 p. S9 m* C7 I3 O
* A8 ?+ e. A7 S& W. P
dictionary = corpora.Dictionary(data_set) # 构建词典
# T; i# c9 e, w' [/ Acorpus = [dictionary.doc2bow(text) for text in data_set]
0 L i) f* e0 I2 j! ~- ]6 T8 M
6 H1 a A H7 ^# V$ W9 G& nlda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=5, passes = 30,random_state=1)
8 f; {1 w5 O. ?+ J- f3 ?topic_list=lda.print_topics()
2 Y9 ?( X/ Z( k q( q) @print(topic_list)$ \! D- y2 c1 t+ X- I
( Q5 i5 ?6 {+ H( P
for i in lda.get_document_topics(corpus)[:]:. g# [6 i( }3 l7 |: r# B8 H4 Y% f
listj=[], g7 J) l. ]$ e
for j in i:
" [+ [4 I; W7 o1 h7 K A listj.append(j[1])
9 {1 Z) R& |" l4 J+ h1 E- s; U9 K8 C- L bz=listj.index(max(listj))9 V* Z3 ^& Z( ^' _, }
print(i[bz][0])2 y+ C% }$ o2 k2 q" z
6 q! y) N, I# p& Q 同时我们可以用pyLDAvis对LDA模型结果进行可视化:
. h' l, W0 F8 X# R0 N: z" W# V9 A- b, D5 f& W
import pyLDAvis.gensim# y. u- F, J. u
pyLDAvis.enable_notebook()) r$ I* q. @: j* I# H' v) A4 g
data = pyLDAvis.gensim.prepare(lda, corpus, dictionary)
9 A% @& u( n. spyLDAvis.save_html(data, 'E:/data/3topic.html')
8 z" g0 f% ^# e# U# Y 大概能得到这样的结果:
, R: s' P# @' N+ @( m4 a( [% p7 [ e8 I+ s! m
9 {$ X( I2 ?- x% u) _: O/ m3 R9 ^" Y
左侧圆圈表示主题,右侧表示各个词语对主题的贡献度。5 l; W; a2 C+ k
& ?2 L3 `1 }* N! y! V
所有代码如下:; N& n; I8 {2 }) x J/ s/ F
import gensim8 T( z" d0 b! L1 A1 ?0 Y* {
from gensim import corpora% M, \9 t; d+ G. M
import matplotlib.pyplot as plt4 X/ E) q! I9 `) x9 {; X
import matplotlib
* A9 k* m0 }* b0 Z" X' V& @import numpy as np8 i. n% P% J& X4 V9 _
import warnings# b- @4 p x; a8 e
warnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarity
+ t+ d. i. F% t2 K) `
, B1 R1 s+ Y+ D0 m/ mfrom gensim.models.coherencemodel import CoherenceModel& O8 y$ b& `# E
from gensim.models.ldamodel import LdaModel
G3 e0 Y! c, n Q
! N) ?3 r: z0 d9 U3 ~) j9 q5 d! r3 Q: h' i$ F* b( g5 V
3 K$ h5 x& Q; w4 T
# 准备数据. I6 Z* l9 Z' h) t
PATH = "E:/data/output.csv"
: @8 `6 Z% v( T# E9 J
) v% k/ P2 t. X* F9 C% P4 Q! Efile_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容
7 R, v: G$ N2 A; b/ D. m' mdata_set=[] #建立存储分词的列表3 z* j, P0 q! s+ Q8 ]! o! ?
for i in range(len(file_object2)):
7 i& C3 V- f/ b8 x7 ? result=[]* J( r9 I. k" s6 N- j: q
seg_list = file_object2.split()
! h3 I. a" p+ E1 C& f. V' x; ]$ J8 l } for w in seg_list :#读取每一行分词- P# c8 ]3 ]4 @. P: |! j; R6 p
result.append(w)
6 x# b% L% Z* C/ L data_set.append(result)
/ s# m& r) Z9 Q& @7 Gprint(data_set)5 c* Q- x+ o- s0 }* e0 |
' Y, M! g8 x! @# D& H
- C# D; c' K# y, {dictionary = corpora.Dictionary(data_set) # 构建 document-term matrix; Z8 j$ x! h9 @) L
corpus = [dictionary.doc2bow(text) for text in data_set]3 m: N; y* m9 D; [+ q
#Lda = gensim.models.ldamodel.LdaModel # 创建LDA对象, M; [* a; A$ r6 ]6 O
5 h9 u( O0 D1 v8 f+ W: R A1 Z
#计算困惑度
4 z0 {* }# _7 r" Zdef perplexity(num_topics):8 Z7 `1 O0 b# w: L2 T' R; Z
ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30)6 b! K5 r2 I& X: ~; |& P' c2 a
print(ldamodel.print_topics(num_topics=num_topics, num_words=15))) b1 M0 y, I: y; S& b" z6 N4 ^2 `
print(ldamodel.log_perplexity(corpus))( d, V; i! T' K6 _- L2 g; m3 K
return ldamodel.log_perplexity(corpus)
( Y" x1 W" Q3 W1 ~6 x% J0 M8 h) j1 K
#计算coherence
, ]+ U. g9 o: ?) N0 x4 Qdef coherence(num_topics):) S4 r% a# B+ s9 d* G/ V7 m
ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30,random_state = 1)# g2 U% o, [1 c g3 ?
print(ldamodel.print_topics(num_topics=num_topics, num_words=10))$ P \- M0 P& f! B
ldacm = CoherenceModel(model=ldamodel, texts=data_set, dictionary=dictionary, coherence='c_v')8 f* s5 i) `$ s9 \6 z9 @
print(ldacm.get_coherence())6 {# g' M4 R& ?0 M
return ldacm.get_coherence()! G; y/ c$ V8 Z+ [9 H. i
P. F' p0 a. [/ W% N
# 绘制困惑度折线图
2 f* \4 f3 W3 R9 j5 J0 ?% rx = range(1,15)
; m8 G, c. z/ v) I. Y# z = [perplexity(i) for i in x]
* e& r& ]4 t4 I! b Z5 R& _, ky = [coherence(i) for i in x]
7 ^' y: w6 g7 i- g4 v$ _; D5 F! eplt.plot(x, y)
1 h$ ~: Z% j1 X4 ]: T& vplt.xlabel('主题数目')' E1 g. p6 Q: ]- ~/ f
plt.ylabel('coherence大小'). n' s& e" u+ O1 V, i& {
plt.rcParams['font.sans-serif']=['SimHei']/ ?2 z' o* ?6 ?0 a. {, N
matplotlib.rcParams['axes.unicode_minus']=False, C4 t/ I* M- N e) q+ U
plt.title('主题-coherence变化情况')
2 R0 _( Z$ k' J0 X- j# i# M" U* C3 hplt.show() L; e2 v* n; s+ G
( X1 S9 G( O) {* ]- afrom gensim.models import LdaModel
7 X( S5 H2 _( A. Ximport pandas as pd
3 C& H) _1 `# B/ `* Ifrom gensim.corpora import Dictionary1 ]+ W0 V" p$ {( E+ |- y# x
from gensim import corpora, models5 P6 i- a, @7 R: L7 l
import csv
1 ~% l' }4 ]. @! O( z" o0 x6 I# g" g3 F( o; B% ^
# 准备数据
n9 D5 ]5 T( J$ DPATH = "E:/data/output1.csv"
% {9 k; w$ G/ E
1 I; H: G" d2 Z7 ~file_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容
0 b/ H3 U& X& ^) c; j$ Y0 ?data_set=[] #建立存储分词的列表- L4 r" ?2 j2 W, Q4 K7 K3 c
for i in range(len(file_object2)):+ s+ s2 [/ Y4 a* [
result=[]9 Q* n! M W1 I4 z+ [0 v# e( Z& l
seg_list = file_object2.split() B3 f* p: p% ~% S% ^
for w in seg_list :#读取每一行分词! i& d) m7 z( q4 u; `
result.append(w)
0 b6 c5 r: S" |* t6 H! ? s: l data_set.append(result)6 \( y K! d6 o! E
: e# x* m: z' Z
dictionary = corpora.Dictionary(data_set) # 构建 document-term matrix( ]( D- }6 x5 s& P/ U& b/ J9 S
corpus = [dictionary.doc2bow(text) for text in data_set]# \7 T* U- D y1 Y- ~* E6 U
* C- K) K8 O, I5 V7 I& x" j
lda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=5, passes = 30,random_state=1)' N1 m$ k' |. t5 h
topic_list=lda.print_topics()$ ` G3 ]. i8 C( X+ }
print(topic_list)
" L! _: x+ n" @6 w6 B4 `
: `5 o0 P2 v3 J; O1 j+ z( h1 lresult_list =[]
# i! x" t2 J* F# z- d$ [' Nfor i in lda.get_document_topics(corpus)[:]:
/ U0 X, F! X1 Y( n listj=[]
' _, \4 ^7 t" q, n! ?5 X r3 o) T for j in i:
( S" ~! Z( c% P5 C# A( m- p listj.append(j[1])" P4 P# S5 i7 Z D" Y
bz=listj.index(max(listj))
/ W+ o# F/ S+ M3 q4 X( O% K result_list.append(i[bz][0])( w* X, ?* p. d' ^2 H
print(result_list)" J7 u5 g( l3 T6 I) Z- w
2 w9 E; q5 W5 B& C
import pyLDAvis.gensim" B& \8 b; j. l" \
pyLDAvis.enable_notebook()
, i3 H% T: n( _2 a/ D) ^data = pyLDAvis.gensim.prepare(lda, corpus, dictionary): R8 I" a6 L7 F
pyLDAvis.save_html(data, 'E:/data/topic.html')! \: v' f( p0 I' c* N6 S
有需要自取~
; K& K8 Z* p" F l4 O& e1 M3 _————————————————
- c( L1 m0 k, p7 J% e) Y2 p' G" {4 O版权声明:本文为CSDN博主「阿丢是丢心心」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
- S5 B9 }/ J3 F! ]: c4 x原文链接:https://blog.csdn.net/weixin_41168304/article/details/122389948, X" D0 d$ _5 D3 A- b* W. K1 b" Y
s2 a. j; u9 }- l1 H5 o9 y3 r0 \
- y: y+ {$ V1 Z3 B1 n5 D6 u$ q |
zan
|