我尝试使用Latent Dirichlet分配LDA来提取一些主题。
最近我们被客户要求撰写关于主题建模的研究报告,包括一些图形和统计输出。 本教程以自然语言处理流程为特色,从原始数据开始,准备,建模,可视化论文。
我们将涉及以下几点
使用LDA进行主题建模
使用pyLDAvis可视化主题模型
使用t-SNE可视化LDA结果
文本挖掘:主题模型(LDA)及R语言实现分析游记数据
时长12:59
In [1]:
from scipy import sparse as sp
Populating the interactive namespace from numpy and matplotlib
In [2]:
docs = array(p_df['PaperText'])
In [3]:
- from nltk.stem.wordnet import WordNetLemmatizer
- from nltk.tokenize import RegexpTokenizer
-
- def docs_preprocessor(docs):
- tokenizer = RegexpTokenizer(r'\w+')
- for idx in range(len(docs)):
- docs[idx] = docs[idx].lower() # Convert to lowercase.
- docs[idx] = tokenizer.tokenize(docs[idx]) # Split into words.
-
- # 删除数字,但不要删除包含数字的单词。
-
- docs = [[token for token in doc if not token.isdigit()] for doc in docs]
-
- # 删除仅一个字符的单词。
-
- docs = [[token for token in doc if len(token) > 3] for doc in docs]
-
- # 使文档中的所有单词规则化
-
- lemmatizer = WordNetLemmatizer()
- docs = [[lemmatizer.lemmatize(token) for token in doc] for doc in docs]
-
- return docs
In [4]:
docs = docs_preprocessor(docs)
主题非常相似,可以区分它们是短语而不是单个单词。
In [5]:
- from gensim.models import Phrases
- # 向文档中添加双字母组和三字母组(仅出现10次或以上的文档)。
- bigram = Phrases(docs, min_count=10)
- trigram = Phrases(bigram[docs])
-
- for idx in range(len(docs)):
- for token in bigram[docs[idx]]:
- if '_' in token:
- # Token is a bigram, add to document.
- docs[idx].append(token)
- for token in trigram[docs[idx]]:
- if '_' in token:
- # token是一个二元组,添加到文档中。
- docs[idx]