Python【极简】中文LDA模型

1、完整代码

from gensim import corpora, models
import jieba.posseg as jp
# 待分析文本集
text1 = '美国教练坦言,没输给中国女排,是输给了郎平'
text2 = '中国女排世界排名第一?真实水平如何,听听巴西和美国主教练的评价'
text3 = '为什么越来越多的人买MPV,而放弃SUV?跑一趟长途就知道了'
text4 = '跑了长途才知道,SUV和轿车之间的差距'
texts = [text1, text2, text3, text4]
# 过滤条件
flags = ('n', 'nr', 'ns', 'nt', 'eng', 'v', 'd')  # 词性
stopwords = ('没', '就', '知道', '是', '才', '听听', '坦言')  # 停词
# 分词
words_ls = []
for text in texts:
    words = [word.word for word in jp.cut(text) if word.flag in flags and word.word not in stopwords]
    words_ls.append(words)
# 构造词典
dictionary = corpora.Dictionary(words_ls)
# 基于词典,使【词】→【稀疏向量】,并将向量放入列表,形成【稀疏向量集】
corpus = [dictionary.doc2bow(words) for words in words_ls]
# lda模型,num_topics设置主题的个数
lda = models.ldamodel.LdaModel(corpus=corpus, id2word=dictionary, num_topics=2)
# 打印所有主题,每个主题显示3个词
for topic in lda.print_topics(num_words=3):
    print(topic)
# 主题推断
print(lda.inference(corpus))
结果
主题0关键词(汽车):0.077*" 长途" + 0.076*" SUV" + 0.070*" "
主题1关键词(体育):0.072*" 中国女排" + 0.068*" 输给" + 0.066*" 美国"

2、过程详解

2.1、打印中间件

print(words_ls)
[[‘美国’, ‘输给’, ‘中国女排’, ‘输给’, ‘郎平’],
[‘中国女排’, ‘真实’, ‘水平’, ‘巴西’, ‘美国’, ‘主教练’, ‘评价’],
[‘越来越’, ‘人’, ‘买’, ‘MPV’, ‘放弃’, ‘SUV’, ‘跑’, ‘长途’],
[‘跑’, ‘长途’, ‘SUV’, ‘轿车’, ‘差距’]]
print(dictionary.token2id)
{‘中国女排’: 0, ‘美国’: 1, ‘输给’: 2, ‘郎平’: 3, ‘主教练’: 4, ‘巴西’: 5, ‘水平’: 6, ‘真实’: 7, ‘评价’: 8, ‘MPV’: 9, ‘SUV’: 10, ‘买’: 11, ‘人’: 12, ‘放弃’: 13, ‘越来越’: 14, ‘跑’: 15, ‘长途’: 16, ‘差距’: 17, ‘轿车’: 18}
print(corpus)
[[(0, 1), (1, 1), (2, 2), (3, 1)],
[(0, 1), (1, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1)],
[(9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1)],
[(10, 1), (15, 1), (16, 1), (17, 1), (18, 1)]]
print(lda)
LdaModel(num_terms=19, num_topics=2, decay=0.5, chunksize=2000)

2.2、dictionary.doc2bow函数

[‘美国’, ‘输给’, ‘中国女排’, ‘输给’, ‘郎平’]
↓↓↓(美国→0、输给→ 2、中国女排→1、郎平→3)
[0, 2, 1, 2, 3]
↓↓↓2个,其它只有一个)
[(0, 1), (1, 1), ( 2, 2), (3, 1)]

2.3、主题推断

for e, values in enumerate(lda.inference(corpus)[0]):
    print(texts[e])
    for ee, value in enumerate(values):
        print('\t主题%d推断值%.2f' % (ee, value))

  美国教练坦言,没输给中国女排,是输给了郎平
    主题0推断值0.55
    主题1推断值5.45
  中国女排世界排名第一?真实水平如何,听听巴西和美国主教练的评价
    主题0推断值0.55
    主题1推断值7.45
  为什么越来越多的人买MPV,而放弃SUV?跑一趟长途就知道了
    主题0推断值8.36
    主题1推断值0.64
  跑了长途才知道,SUV和轿车之间的差距
    主题0推断值5.44
    主题1推断值0.56

text5 = '中国女排将在郎平的率领下向世界女排三大赛的三连冠发起冲击'
bow = dictionary.doc2bow([word.word for word in jp.cut(text5) if word.flag in flags and word.word not in stopwords])
ndarray = lda.inference([bow])[0]
print(text5)
for e, value in enumerate(ndarray[0]):
    print('\t主题%d推断值%.2f' % (e, value))

  中国女排将在郎平的率领下向世界女排三大赛的三连冠发起冲击
    主题0推断值0.53
    主题1推断值2.58

2.4、词和主题的关系

word_id = dictionary.doc2idx(['长途'])[0]
for i in lda.get_term_topics(word_id):
    print('【长途】与【主题%d】的关系值:%.2f%%' % (i[0], i[1]*100))

  【长途】与【主题0】的关系值:7.67%
  【长途】与【主题1】的关系值:2.36%

猜你喜欢

转载自blog.csdn.net/Yellow_python/article/details/83097994