使用Spark LDA可视化主题

Vad*_*kov 5 lda apache-spark apache-spark-ml

我正在使用pySpark ML LDA库来适合sklearn的20个新闻组数据集上的主题模型。我正在训练语料库上进行标准标记化,停用词删除和tf-idf转换。最后,我可以获取主题并打印出单词索引及其权重:

topics = model.describeTopics()
topics.show()
+-----+--------------------+--------------------+
|topic|         termIndices|         termWeights|
+-----+--------------------+--------------------+
|    0|[5456, 6894, 7878...|[0.03716766297248...|
|    1|[5179, 3810, 1545...|[0.12236370744240...|
|    2|[5653, 4248, 3655...|[1.90742686393836...|
...
Run Code Online (Sandbox Code Playgroud)

但是,如何从术语索引映射到实际单词以可视化主题?我正在将HashingTF应用于字符串的标记化列表,以得出术语索引。如何生成用于可视化主题的字典(从索引到单词的映射)?

Vad*_*kov 6

HashingTF 的替代方案是生成词汇表的 CountVectorizer:

count_vec = CountVectorizer(inputCol="tokens_filtered", outputCol="tf_features", vocabSize=num_features, minDF=2.0)
count_vec_model = count_vec.fit(newsgroups)  
newsgroups = count_vec_model.transform(newsgroups)
vocab = count_vec_model.vocabulary
Run Code Online (Sandbox Code Playgroud)

给定一个词汇表作为单词列表,我们可以对其进行索引以可视化主题:

topics = model.describeTopics()   
topics_rdd = topics.rdd

topics_words = topics_rdd\
       .map(lambda row: row['termIndices'])\
       .map(lambda idx_list: [vocab[idx] for idx in idx_list])\
       .collect()

for idx, topic in enumerate(topics_words):
    print "topic: ", idx
    print "----------"
    for word in topic:
       print word
    print "----------"
Run Code Online (Sandbox Code Playgroud)