【问题标题】:How to convert topic index to topic words in LDA如何将主题索引转换为 LDA 中的主题词
【发布时间】:2017-01-10 01:31:35
【问题描述】:

如何从 LDA 模型 (org.apache.spark.ml.clustering.LDA) 中获取 vocabArray。我只是得到 vocabSize ,它返回扫描的单词数。

理想情况下,我需要模型中的实际单词数组,然后根据终端,我想查看存储桶中的单词。

我需要在 scala 中执行此操作。任何建议都会有所帮助。

到目前为止我尝试过的事情,我的 topicIndices 是一个数据框

topicIndices: org.apache.spark.sql.DataFrame = [topic: int, termIndices: array<int>, termWeights: array<double>]

我正在尝试获取这样的主题

val topics = topicIndices.map { case (terms, termWeights) =>
      terms.zip(termWeights).map { case (term, weight) => (vocabArray(term.toInt), weight) }
    }

但它会引发以下错误

> 

val topics = topicIndices.map { case (terms, termWeights) =>
      terms.zip(termWeights).map { case (term, weight) => (vocabArray(term.toInt), weight) }
    } <console>:96: error: constructor cannot be instantiated to expected type;  found   : (T1, T2)  required: org.apache.spark.sql.Row
       val topics = topicIndices.map { case (terms, termWeights) =>
                                            ^ <console>:97: error: not found: value terms
             terms.zip(termWeights).map { case (term, weight) => (vocabArray(term.toInt), weight) }
             ^

【问题讨论】:

  • 你使用的是 spark-shell 吗?
  • 我正在使用 databricks 笔记本进行此实验。
  • 问题出在旧的 mllib LDA 中,描述了用于返回主题数组的主题。每个主题都是(术语索引,主题中的术语权重)。在 ml LDA describetopics 中返回 [topic: int, termIndices: array, termWeights: array] 。之前很容易映射键值对,有什么想法我们应该如何在这个新的映射中映射?

标签: scala apache-spark lda


【解决方案1】:

问题已解决。这是缺少的部分。一旦你从 describetopics 获得 df,这里的代码就可以帮助获得相应的单词。 (注意:此代码适用于 LDA 的 ml 库)

val topicDF = model.describeTopics(maxTermsPerTopic = 10)
for ((row) <- topicDF) {
        val topicNumber = row.get(0)
        val topicTerms  = row.get(1)
        println ("Topic: "+ topicNumber)
}

import scala.collection.mutable.WrappedArray

val vocab = vectorizer.vocabulary

for ((row) <- topicDF) {
    val topicNumber = row.get(0)
    //val terms = row.get(1)
    val terms:WrappedArray[Int] = row.get(1).asInstanceOf[WrappedArray[Int]]
    for ((termIdx) <- 0 until 4) {
        println("Topic:" + topicNumber + " Word:" + vocab(termIdx))
    }
}

topicDF.printSchema
import org.apache.spark.sql.Row

topicDF.collect().foreach { r => 
                r match {
                        case _: Row => ("Topic:" + r)
                        case unknow => println("Something Else")
        }
}

topicDF.collect().foreach { r => {
                        println("Topic:" + r(0))
                        val terms:WrappedArray[Int] = r(1).asInstanceOf[WrappedArray[Int]]
                        terms.foreach {
                                t => {
                                        println("Term:" + vocab(t))
                                }
                        }
                }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 2017-03-09
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多