- 在线时间
- 1630 小时
- 最后登录
- 2024-1-29
- 注册时间
- 2017-5-16
- 听众数
- 82
- 收听数
- 1
- 能力
- 120 分
- 体力
- 564496 点
- 威望
- 12 点
- 阅读权限
- 255
- 积分
- 174572
- 相册
- 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* a% e0 @0 o3 ]6 S- `3 q/ @2 }$ a- k" d2 L2 _' p. ^
一、LDA主题模型简介
0 e; h/ w) r( Z0 L8 A LDA主题模型主要用于推测文档的主题分布,可以将文档集中每篇文档的主题以概率分布的形式给出根据主题进行主题聚类或文本分类。& E7 \( s5 Y9 b. R1 f8 B
; g4 L) d0 h9 Q9 b7 z6 F# a LDA主题模型不关心文档中单词的顺序,通常使用词袋特征(bag-of-word feature)来代表文档。词袋模型介绍可以参考这篇文章:文本向量化表示——词袋模型 - 知乎) O# R6 b- M6 r
7 O$ n) [+ m. S2 W
了解LDA模型,我们需要先了解LDA的生成模型,LDA认为一篇文章是怎么形成的呢?8 L/ k1 v) M2 x `
! {9 b0 D' U, r; U
LDA模型认为主题可以由一个词汇分布来表示,而文章可以由主题分布来表示。8 g+ g9 H0 P$ f* m
2 i# b/ \6 }6 Y; S6 w! N6 ]$ \* |# ]
比如有两个主题,美食和美妆。LDA说两个主题可以由词汇分布表示,他们分别是:
. F0 O! h3 ] S! C
' F1 `; ^" _! e6 x1 F{面包:0.4,火锅:0.5,眉笔:0.03,腮红:0.07}
6 A* z5 Y4 U& g: r{眉笔:0.4,腮红:0.5,面包:0.03,火锅:0.07}
8 A! l$ [% Q# K$ X& S+ z B2 _
- e& W; Y N5 b0 O! n 同样,对于两篇文章,LDA认为文章可以由主题分布这么表示:# U0 X( f' @! [' F* L* W
6 `5 n; H2 y2 T2 O' |( r; I
《美妆日记》{美妆:0.8,美食:0.1,其他:0.1}
2 G8 d0 [3 G# x8 s
* z* d9 c8 v3 K9 [+ ?4 B《美食探索》{美食:0.8,美妆:0.1,其他:0.1}! ~# ~$ F4 ?3 Y& g* \
8 B5 k" p# q. h5 M/ y0 U 所以想要生成一篇文章,可以先以一定的概率选取上述某个主题,再以一定的概率选取那个主题下的某个单词,不断重复这两步就可以生成最终文章。* @5 W! w" ^% s( Q8 u) }# A
, }$ u d. q' S+ e' t8 w. K! R0 T
在LDA模型中,一篇文档生成的方式如下:
F6 H% a4 v# z1 v6 G; A# m5 d
1 q" h. ]2 G9 s! `/ h
' S6 l! h3 A: D* J5 _+ G1 Q, {( o! b7 S
其中,类似Beta分布是二项式分布的共轭先验概率分布,而狄利克雷分布(Dirichlet分布)是多项式分布的共轭先验概率分布。* m5 h! O- R4 `
$ `+ I5 `7 `1 g) g5 s- l/ g
# G; B' L' N% x& Y0 i t2 C. v$ Q( L- E9 x
如果我们要生成一篇文档,它里面的每个词语出现的概率为:! a* B; E, c) f1 G
5 D/ x1 u, I+ q5 h3 \
* v* O5 m& [9 c' A# C0 v9 a8 K) j( b6 o
更详细的数学推导可以见:通俗理解LDA主题模型_结构之法 算法之道-CSDN博客_lda模型! B7 V o, @8 e' I3 M( r
# h+ ~( g' ]/ z# x/ } 看到文章推断其隐藏的主题分布,就是建模的目的。换言之,人类根据文档生成模型写成了各类文章,然后丢给了计算机,相当于计算机看到的是一篇篇已经写好的文章。现在计算机需要根据一篇篇文章中看到的一系列词归纳出当篇文章的主题,进而得出各个主题各自不同的出现概率:主题分布。7 X5 w9 a2 D M9 H" m
" s: M3 e: \6 F 至于LDA主题模型在计算机中具体是怎么实现的,我们也可以不必细究,现在有很多可以直接用来进行LDA主题分析的包,我们直接用就行。(没错,我就是调包侠)
0 H S2 E. I, a: J: A8 Y) @# G3 K; K& t( T
二、Python实现. |& J6 H9 X5 [2 x6 w- e
在用Python进行LDA主题模型分析之前,我先对文档进行了分词和去停用词处理(详情可以看我之前的文章:用python对单一微博文档进行分词——jieba分词(加保留词和停用词)_阿丢是丢心心的博客-CSDN博客_jieba 停用词)
0 ?2 r1 D4 F& X( \$ _/ {! A, T; C6 o. b. {" b
我下面的输入文件也是已经分好词的文件
8 M3 R* k; ]2 P( i4 t/ M5 C3 Y# Q$ I9 T
1.导入算法包0 S! a$ l& B# g7 C! @
import gensim
& d. {2 @9 b6 o' p7 O- H! N( efrom gensim import corpora
, f/ t/ H/ ?& O. d% \import matplotlib.pyplot as plt
0 X, s+ x( o+ S$ Q2 l& u1 e2 ]+ o# simport matplotlib3 W* o" W! q2 s. A* R0 f
import numpy as np7 `, o$ C8 i# r1 l& a
import warnings+ Y3 {9 @- [1 K! V# Q
warnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarity
: h8 O% c: {$ ?& q, ^! {# `, z% f1 K9 X1 a6 h2 {7 {
from gensim.models.coherencemodel import CoherenceModel4 T: X( ~% b; H7 a8 N
from gensim.models.ldamodel import LdaModel
' v# U4 X9 x2 ]) t6 o- S2.加载数据
7 O4 k0 n; `" x5 P4 r 先将文档转化为一个二元列表,其中每个子列表代表一条微博:- b9 Z( n2 u5 \, p; Q
" @9 I- a; S: I( DPATH = "E:/data/output.csv"3 b' _9 [- [% t5 x
" d. Z& B4 T& T: |0 o5 c% rfile_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容
$ I# O2 I4 c1 H* J1 G7 _2 @( Tdata_set=[] #建立存储分词的列表- H' k0 e1 Y0 N& t0 {
for i in range(len(file_object2)):
( |. G2 ^9 T- g& T7 k result=[]( m9 R5 x8 p: B4 r0 e4 x" d& V4 {
seg_list = file_object2.split()
) x- @, w4 K; Y* U- B1 F for w in seg_list : #读取每一行分词2 ^. r# v+ f2 i2 M
result.append(w)2 B+ c4 m5 q# J% |
data_set.append(result)' }& {# M; p" q5 Z* v8 f
print(data_set)/ Z9 x, ~0 V: \
构建词典,语料向量化表示:8 _* `& f9 B# U& \; }& b: W0 Z
# I. ~; P7 E4 |) t5 D6 `
dictionary = corpora.Dictionary(data_set) # 构建词典
, A! U; |8 m+ R. A9 A; V8 j' C7 @corpus = [dictionary.doc2bow(text) for text in data_set] #表示为第几个单词出现了几次
2 n1 R! W$ L, Y$ {: J3.构建LDA模型
% t6 G5 e1 E! k1 o( R7 H, Lldamodel = LdaModel(corpus, num_topics=10, id2word = dictionary, passes=30,random_state = 1) #分为10个主题( B* x0 v; z8 ~9 L+ B% X
print(ldamodel.print_topics(num_topics=num_topics, num_words=15)) #每个主题输出15个单词- m: p9 P, S5 ]1 A3 U
这是确定主题数时LDA模型的构建方法,一般我们可以用指标来评估模型好坏,也可以用这些指标来确定最优主题数。一般用来评价LDA主题模型的指标有困惑度(perplexity)和主题一致性(coherence),困惑度越低或者一致性越高说明模型越好。一些研究表明perplexity并不是一个好的指标,所以一般我用coherence来评价模型并选择最优主题,但下面代码两种方法我都用了。- ~! u5 M( g8 N, u
0 L% W$ a% ?8 a$ x9 P! h5 {( M#计算困惑度4 P' H2 w) \$ e i6 A: x
def perplexity(num_topics):
7 w& c V+ ?/ K) y ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30)9 n; t2 K4 @, B3 v7 D0 [5 Q
print(ldamodel.print_topics(num_topics=num_topics, num_words=15))2 q( I# R' x/ _& h( y* @
print(ldamodel.log_perplexity(corpus))( V. Q, D$ n* n% w1 o, d% t! {, a
return ldamodel.log_perplexity(corpus)
$ K h u3 O' E/ R5 ~. ~8 G8 B7 w4 K2 A4 X#计算coherence6 Z! ^, i* H9 l% W
def coherence(num_topics):
& R1 y5 E& E/ h ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30,random_state = 1)
; x& v# e3 z9 \0 ^; M print(ldamodel.print_topics(num_topics=num_topics, num_words=10))# R( z7 L. {% F j) _' w: p
ldacm = CoherenceModel(model=ldamodel, texts=data_set, dictionary=dictionary, coherence='c_v')
% o) c2 P, b5 b4 t print(ldacm.get_coherence())* h, {1 L9 t, b! s0 h9 x3 C+ J! ]
return ldacm.get_coherence()% ^- M1 S/ t7 R* W1 D# s9 y5 ]8 g
4.绘制主题-coherence曲线,选择最佳主题数
; _: S( l: }8 K9 I V% R3 Tx = range(1,15)
4 a: P7 @: S1 r" A7 m8 O$ Q& V# z = [perplexity(i) for i in x] #如果想用困惑度就选这个5 k/ \7 I0 u9 q) h' Y8 j) P
y = [coherence(i) for i in x]
9 L9 L/ w+ ]/ ^! \% q9 m+ f% Pplt.plot(x, y)* \. O) R* S8 u' q6 s9 n
plt.xlabel('主题数目')) w" o: H; q) F6 j
plt.ylabel('coherence大小')# T; U$ D" {- ^5 x1 ]) z! Y
plt.rcParams['font.sans-serif']=['SimHei']/ v$ @: |2 ]! L( m( {! ^$ U/ ~
matplotlib.rcParams['axes.unicode_minus']=False; ^# \+ q- M% F4 ?( r. i' X
plt.title('主题-coherence变化情况')
4 `% m% m# X# P5 L- [) W8 B* Rplt.show()! \+ }& }+ D. b# V( \
最终能得到各主题的词语分布和这样的图形:( c U7 z8 a3 j% A r! Z' n. N; x
' P) r1 Z% Q* D; r P% o
1 {( O8 e6 f1 F0 F. u* q0 L( A7 E) Y2 z( k8 ~
5.结果输出与可视化
% f0 V; |8 p+ `% w* E8 k 通过上述主题评估,我们发现可以选择5作为主题个数,接下来我们可以再跑一次模型,设定主题数为5,并输出每个文档最有可能对应的主题* r& [7 ?( w2 ~% d3 H4 w; f; g( m
0 Y6 s; H; p5 qfrom gensim.models import LdaModel
& i9 c8 g% f( f; ?5 b! F/ {7 B/ D: V8 \import pandas as pd
) c0 _8 ]6 I! ^; {" `( dfrom gensim.corpora import Dictionary. f5 x# l# Z6 |$ y. J
from gensim import corpora, models
: X2 A$ _, [) q- H6 f v; z% l" _( zimport csv
3 D# i+ g7 Y/ l- A) A8 _# H* W0 U7 }' b& H6 r. g9 l- }( m9 O
# 准备数据! v2 r0 z9 T J" f
PATH = "E:/data/output1.csv"( r% N& g, j: \1 E0 [8 a6 E
7 O' C: G7 I( C9 y* a; sfile_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容
/ {/ k* s2 D' gdata_set=[] #建立存储分词的列表
# N! M/ |; l7 |- |# F E# ifor i in range(len(file_object2)):
: R7 B5 ?* l; a result=[]
$ y4 O) T3 Q- f5 |. G seg_list = file_object2.split()% n( ?) p. l1 L( y5 ]; _: C
for w in seg_list :#读取每一行分词/ P- t$ ]7 |/ ~, R. U9 [! l- S
result.append(w)* c* }, t% O' y4 m5 L
data_set.append(result)
G3 i: ]/ u0 b
% C0 r) ~1 Q! [ h/ i3 A! Ddictionary = corpora.Dictionary(data_set) # 构建词典* V( J5 b) \8 ?! ^* S6 Y8 W9 e2 u
corpus = [dictionary.doc2bow(text) for text in data_set]
w( t2 e0 ?5 C, B) J/ Q0 ?. b$ t) x# T- X- _8 q3 `1 [
lda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=5, passes = 30,random_state=1)
9 k1 n* ]+ f* _9 R3 \topic_list=lda.print_topics(), n2 K& l$ a8 A. [6 V+ C; |6 U+ | M
print(topic_list)
+ K& Z3 s& R( i
: B) r. _, }9 q& nfor i in lda.get_document_topics(corpus)[:]:2 d+ q. ? s9 H/ I5 ~! x2 C
listj=[]+ I& \4 r) e) @% D6 S
for j in i:
5 {2 p P% o- s* _3 i9 S; x( J- Z; D listj.append(j[1])
2 r* n% `- T* P+ ?& M" i bz=listj.index(max(listj))0 B$ w0 z0 a* _' O) C
print(i[bz][0])
5 V# X" X" F0 R, f- f
; h$ `; }8 F" C" Y2 V 同时我们可以用pyLDAvis对LDA模型结果进行可视化:
" h+ v* F4 o# b; B9 M5 ?. ?. e2 A7 ?7 W$ B: B1 d
import pyLDAvis.gensim
% L# ]* j. x2 [( k5 F8 t, fpyLDAvis.enable_notebook()
6 F2 F6 J$ J+ V3 H' Ndata = pyLDAvis.gensim.prepare(lda, corpus, dictionary)7 C M( ^7 d3 p6 ^6 B/ e
pyLDAvis.save_html(data, 'E:/data/3topic.html'): p- t( ]$ M/ t0 `) J" g i3 ?
大概能得到这样的结果:
% ?3 B6 [ y4 ~% [- [7 ]" U- K
" f" z& b! K' E8 N9 }& k! Y D1 s5 J9 n: @, S9 P5 n
9 g2 ?! m% k8 s
左侧圆圈表示主题,右侧表示各个词语对主题的贡献度。
0 ^& Z+ p' ~3 ]
/ b5 R/ p; F* ?4 o0 A9 x9 s8 Q, n所有代码如下:
$ I" Y7 K9 r* A! ?& m+ H. ~import gensim
1 ^$ {4 n- e, S) l5 @from gensim import corpora( m: Z' |* ~$ U4 I
import matplotlib.pyplot as plt
" `2 z% r8 ?9 u& c0 rimport matplotlib
" f) J# G7 e- O; C5 Cimport numpy as np
8 ~6 f$ p# U9 T: J' C4 Cimport warnings% ?0 u+ f+ s, V9 t+ r! S! I& n! B
warnings.filterwarnings('ignore') # To ignore all warnings that arise here to enhance clarity# j0 Z4 j6 }! n
0 J: \: y4 t9 C
from gensim.models.coherencemodel import CoherenceModel
; s* x+ T0 N" \% w* d8 @from gensim.models.ldamodel import LdaModel" h- ^; z# u# U# b) U
# a/ U- {$ s3 ]. X+ q
& F$ ~" v8 m- [: g2 j- R- _5 ^) E; b
# 准备数据
, T& N7 J3 \- [PATH = "E:/data/output.csv", f2 _! s7 S( Y" f q! L4 g1 d0 `4 f
9 q) e$ f& ^; H: ^9 v8 s+ j$ Sfile_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容
$ S) H8 a/ ^3 z odata_set=[] #建立存储分词的列表- `, g4 K5 M) x2 p, V( d
for i in range(len(file_object2)):7 i$ g. S9 B& e3 d5 q0 |
result=[]
0 P+ `/ Y" K5 O3 ]: V ] seg_list = file_object2.split()& z o3 Q. m- f9 F' q2 z; \, n
for w in seg_list :#读取每一行分词! f/ e- I) |6 A( ?4 L8 [% X- {
result.append(w)
: _) u5 Q! k7 o- S0 H3 O data_set.append(result)
) z4 `7 d- q" j$ ~' u. xprint(data_set)6 g) [9 n& y- |6 \
P7 U$ `7 C. U# Q7 Y% X: |
* \% M4 j( W: l3 \0 v% @
dictionary = corpora.Dictionary(data_set) # 构建 document-term matrix
; L- o' n' t6 h3 W ^/ zcorpus = [dictionary.doc2bow(text) for text in data_set]3 p# y& p" Q9 C& l! @. i) [. \
#Lda = gensim.models.ldamodel.LdaModel # 创建LDA对象5 u/ u9 k9 ~, t0 }- `% N! U
6 y0 Q9 P6 h0 q+ f#计算困惑度
6 ^; U/ n D" K5 v) Adef perplexity(num_topics):
5 S5 ~* C8 ]& t" C ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30)8 K3 w. t) Z1 c3 p2 F7 H1 k. b
print(ldamodel.print_topics(num_topics=num_topics, num_words=15))1 M2 ]7 L- m6 ~3 X/ P
print(ldamodel.log_perplexity(corpus))
6 p ~+ G) \ K% ^7 s/ p1 ?( K return ldamodel.log_perplexity(corpus)) P0 s( s0 \* o( i& Y. F- w( a
( E; f9 y) P5 Q o7 j3 g
#计算coherence
% ^; O3 ^: |1 B' S; qdef coherence(num_topics):
, i6 p3 ]& @9 \! g! ] ldamodel = LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=30,random_state = 1)$ e/ a1 J7 C! \+ Q, \) d* O
print(ldamodel.print_topics(num_topics=num_topics, num_words=10)): w3 ]2 \9 |) { D- A# W* z N
ldacm = CoherenceModel(model=ldamodel, texts=data_set, dictionary=dictionary, coherence='c_v')( g( M4 H9 e+ O0 Y% D0 d
print(ldacm.get_coherence())
8 V8 I; }( D7 K, _ return ldacm.get_coherence()" _( ]! u; U+ h# S& F
# f) N A6 d! a# 绘制困惑度折线图
5 r. l& N$ _. i: mx = range(1,15)
2 G% e0 L$ n( f# H* ]# z = [perplexity(i) for i in x]
. b0 E+ i! F" L) @9 ]" Zy = [coherence(i) for i in x]
0 x2 u2 a9 \- w- ^plt.plot(x, y)( l0 p ]9 ?5 |: N
plt.xlabel('主题数目')% x8 D8 P" ~+ f" @ h! k! i
plt.ylabel('coherence大小')8 ?+ p7 z5 i! [
plt.rcParams['font.sans-serif']=['SimHei']
- a x# g" d) B# F1 w2 E' Rmatplotlib.rcParams['axes.unicode_minus']=False0 T9 i; p, v' o% V1 M
plt.title('主题-coherence变化情况')
1 J9 e2 a7 ]6 @1 T/ ?plt.show()
- A. z0 f* A' K
& _% C9 W2 q' d6 A. ]from gensim.models import LdaModel# F, ]! }! i1 w, k
import pandas as pd
& m! E7 P4 U0 m5 j* ~: Ufrom gensim.corpora import Dictionary$ D+ R Z/ u! h! l5 V
from gensim import corpora, models% d3 T' c. h$ G
import csv+ c9 r3 |0 l/ \$ R3 Q
7 O! m# x6 u! R& U& z
# 准备数据 [* k/ z' U9 @5 m' C3 P* @% F5 `
PATH = "E:/data/output1.csv"
0 G+ k J. @9 ]& _
9 x7 I }8 X5 a" a! c2 z: jfile_object2=open(PATH,encoding = 'utf-8',errors = 'ignore').read().split('\n') #一行行的读取内容* `' H8 i+ g# {* i/ k! x
data_set=[] #建立存储分词的列表5 ?% {( A0 p1 c1 N! H& v2 v
for i in range(len(file_object2)):" d& S0 c) ~$ {) g* F* p
result=[]
- f. k, N4 |% ~# f/ F4 b seg_list = file_object2.split()8 c6 V) r& I5 O" d/ s6 |$ a
for w in seg_list :#读取每一行分词* a: V+ I- P2 x0 K; ~ T
result.append(w)
0 _9 {# j5 |- I- f1 `) e. b& T data_set.append(result)* ]2 L# p% _7 s4 n4 {
* A0 A6 w! u/ `) F" o+ ^& c4 Rdictionary = corpora.Dictionary(data_set) # 构建 document-term matrix* n; j) Z- A( X9 j+ t6 O! D# Q
corpus = [dictionary.doc2bow(text) for text in data_set]
! S4 A9 L8 |9 \0 I" O. Z& `3 S7 g" S& z7 @$ x7 r5 @) _
lda = LdaModel(corpus=corpus, id2word=dictionary, num_topics=5, passes = 30,random_state=1)
: Z" C8 ~$ M5 F i6 `topic_list=lda.print_topics()- K$ q, @. J9 R
print(topic_list)
2 B5 R0 _4 p) d; z1 r" S) c1 t% z d" w7 Z$ B- p
result_list =[]
: j8 O) [0 b) ?, Sfor i in lda.get_document_topics(corpus)[:]:
{ Y( D; M _2 ]6 a% B listj=[]1 F) Z, @& o! ?* V( W, [
for j in i:$ i# ^3 o! J5 ~& x1 X
listj.append(j[1])) d1 e! `: ]4 O" f6 x6 T. ^
bz=listj.index(max(listj))
1 H5 t' Y! _$ A5 V' n. L3 H8 K result_list.append(i[bz][0])
, M1 \0 j0 x( f5 U$ a, ?" M# S/ Pprint(result_list)% U9 c3 C4 c7 B7 \3 K$ s' @* y2 L
8 W/ ]8 D9 } `import pyLDAvis.gensim) L# r. K5 g0 W; x4 o* b
pyLDAvis.enable_notebook()
1 z! H A* F6 }+ k$ ^4 {data = pyLDAvis.gensim.prepare(lda, corpus, dictionary)* m6 z; M# ]( h( N
pyLDAvis.save_html(data, 'E:/data/topic.html')$ t4 y/ w) i5 K6 G" u
有需要自取~
- F) X* z8 w- f) e; f; j7 O! b————————————————9 h- G, n+ Q( o+ n6 H
版权声明:本文为CSDN博主「阿丢是丢心心」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
0 ^" {- _" G* [2 f原文链接:https://blog.csdn.net/weixin_41168304/article/details/122389948
' E3 {% f+ z. x0 V; M& C6 Q7 { U2 _( e% T7 F
5 a- ?' @6 b$ T. z% f |
zan
|