' l5 r% |+ P& T; \5 }- h主题词数:组成一个主题所需要的词的数量。这些词的数量通常根据需求得到,如果说需求是抽取特征或者关键词,那么主题词数比较少,如果是抽取概念或者论点,那么主题词数比较多。) B% N2 l* d! s, X* Q0 r
( L5 k8 c1 ^4 \9 b( T
迭代次数:使得 LDA 算法收敛的最大迭代次数+ m6 p+ H2 p' c! Z" T. h7 J
4 d# A. Y9 a" d5 a) R' O! s9 X8 x$ e0 e1 ^/ o
5 f& m5 T/ |& h p; E T四、Running in Python$ o: F- y2 W( W3 |: K7 F' c
准备文档集合' }9 M# S y# m
doc1 = "Sugar is bad to consume. My sister likes to have sugar, but not my father." 3 G4 f* Z% b0 Mdoc2 = "My father spends a lot of time driving my sister around to dance practice."4 C: j$ ^ Q5 H9 e
doc3 = "Doctors suggest that driving may cause increased stress and blood pressure." 9 K( I0 L3 {3 ? J& l, tdoc4 = "Sometimes I feel pressure to perform well at school, but my father never seems to drive my sister to do better." : D9 h3 B$ o( p, b& G4 N- o; Cdoc5 = "Health experts say that Sugar is not good for your lifestyle."7 U+ Q. D2 u0 u' c
0 F$ I7 i1 I( v# 整合文档数据 / K! R, }, d) B5 tdoc_complete = [doc1, doc2, doc3, doc4, doc5] 2 v3 P n* R: ~7 |7 Q: a: Q. H! U* Y" N' B# J4 v
数据清洗和预处理 : m+ G5 q2 y8 ~数据清洗对于任何文本挖掘任务来说都非常重要,在这个任务中,移除标点符号,停用词和标准化语料库(Lemmatizer,对于英文,将词归元)。 2 w+ F6 H4 F! U% {" c) v$ I8 O+ C5 |0 k
from nltk import stopwords $ F% M' E% `- k. V# g# ]5 H2 @7 vfrom nltk.stem.wordnet import WordNetLemmatizer 9 I7 `7 |1 V: ]import string / z a; Z9 @/ D( c) b+ v+ W8 ?' B( t, ?" @( \
stop = set(stopwords.words('english')). Z/ l. p" D; h: F
exclude = set(string.punctuation): L' N" d7 ~ c1 V6 a0 H& n. G3 x
lemma = WordNetLemmatizer() 9 e; s' R. K- G! U( S 7 J2 u9 X( F# m( o$ U5 w. N$ h! Ddef clean(doc): & M* k; t9 E- e! _) p stop_free = " ".join([i for i in doc.lower().split() if i not in stop])( g# f! j2 M t6 i) k+ }
punc_free = ''.join(ch for ch in stop_free if ch not in exclude)5 B" e! a# M% z% w
normalized = " ".join(lemma.lemmatize(word) for word in punc_free.split())5 T' A2 w* T8 ^1 [2 V
return normalized7 m/ u6 m5 k P$ ^3 X
]2 S, T3 U: a: t' i8 vdoc_clean = [clean(doc).split() for doc in doc_complete] ' b1 R5 O6 W) K4 P$ c 1 A4 c9 M8 } {/ ^准备 Document - Term 矩阵 9 L) ]6 E: H# L/ n8 H1 n% J语料是由所有的文档组成的,要运行数学模型,将语料转化为矩阵来表达是比较好的方式。LDA 模型在整个 DT 矩阵中寻找重复的词语模式。Python 提供了许多很好的库来进行文本挖掘任务,“genism” 是处理文本数据比较好的库。下面的代码掩饰如何转换语料为 Document - Term 矩阵:. F* ^! _7 t) {* S: G
* c0 ~2 r% Y' S5 yimport genism6 e# `( l; B' s8 G( `
from gensim import corpora 5 U. A" M- v# _7 L+ I3 l# I# h5 p1 P& l% n
# 创建语料的词语词典,每个单独的词语都会被赋予一个索引: j6 m; R, u u7 P/ r4 Y
dictionary = corpora.Dictionary(doc_clean)/ k. q8 _' _) _+ `- b: U
) q0 T# y% A1 Z6 ?9 O
# 使用上面的词典,将转换文档列表(语料)变成 DT 矩阵 * e- J; t: t' E ?doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean] ! r. f# l7 P( i2 X$ X! `* w1 I, ?0 `3 `6 u& F
构建 LDA 模型 9 T V+ Z9 @8 n* R c创建一个 LDA 对象,使用 DT 矩阵进行训练。训练需要上面的一些超参数,gensim 模块允许 LDA 模型从训练语料中进行估计,并且从新的文档中获得对主题分布的推断。 y( H- |. T8 n: ]9 e: }
8 ~2 @" C# d, o! c- n
# 使用 gensim 来创建 LDA 模型对象 : r$ z$ V+ _6 tLda = genism.models.ldamodel.LdaModel3 ] k% F. Y! w$ @