Spark MLlib LDA主題模型

Spark MLlib LDA主題模型(1)

Spark MLlib LDA主題模型是Spark1.3開始加入的,具體介紹看以下文檔:

官方編程指南:

http://spark.apache.org/docs/latest/mllib-clustering.html#latent-dirichlet-allocation-lda

Spark MLlib LDA 簡介:

http://blog.jobbole.com/86130/

關於LDA主題模型的理論知識講解放在下期。

1.1 LDA實例

實例步驟:

1)加載數據

返回的數據格式爲:documents: RDD[(Long, Vector)],其中:Long爲文章ID,Vector爲文章分詞後的詞向量;用戶可以讀取指定目錄下的數據,通過分詞以及數據格式的轉換,轉換成RDD[(Long, Vector)]即可。

2)建立模型

模型參數設置說明:

k: 主題數,或者聚類中心數

DocConcentration:文章分佈的超參數(Dirichlet分佈的參數),必需>1.0

TopicConcentration:主題分佈的超參數(Dirichlet分佈的參數),必需>1.0

MaxIterations:迭代次數

setSeed:隨機種子

CheckpointInterval:迭代計算時檢查點的間隔

Optimizer:優化計算方法,目前支持"em", "online"

3)結果輸出

topicsMatrix以及topics(word,topic))輸出。

實例代碼如下: 

import org.apache.log4j.{ Level, Logger }
import org.apache.spark.{ SparkConf, SparkContext }
import org.apache.spark.mllib.clustering.LDA
import org.apache.spark.mllib.linalg.Vectors

object lda {

  def main(args: Array[String]) {
    //0 構建Spark對象
    val conf = new SparkConf().setAppName("lda")
    val sc = new SparkContext(conf)
    Logger.getRootLogger.setLevel(Level.WARN)
    
    //1 加載數據,返回的數據格式爲:documents: RDD[(Long, Vector)]
    // 其中:Long爲文章ID,Vector爲文章分詞後的詞向量
    // 可以讀取指定目錄下的數據,通過分詞以及數據格式的轉換,轉換成RDD[(Long, Vector)]即可
    val data = sc.textFile("data/mllib/sample_lda_data.txt")
    val parsedData = data.map(s => Vectors.dense(s.trim.split(' ').map(_.toDouble)))
    // Index documents with unique IDs
    val corpus = parsedData.zipWithIndex.map(_.swap).cache()

    //2 建立模型,設置訓練參數,訓練模型
    /**
     * k: 主題數,或者聚類中心數
     * DocConcentration:文章分佈的超參數(Dirichlet分佈的參數),必需>1.0
     * TopicConcentration:主題分佈的超參數(Dirichlet分佈的參數),必需>1.0
     * MaxIterations:迭代次數
     * setSeed:隨機種子
     * CheckpointInterval:迭代計算時檢查點的間隔
     * Optimizer:優化計算方法,目前支持"em", "online"
     */
    val ldaModel = new LDA().
      setK(3).
      setDocConcentration(5).
      setTopicConcentration(5).
      setMaxIterations(20).
      setSeed(0L).
      setCheckpointInterval(10).
      setOptimizer("em").
      run(corpus)

    //3 模型輸出,模型參數輸出,結果輸出
    // Output topics. Each is a distribution over words (matching word count vectors)
    println("Learned topics (as distributions over vocab of " + ldaModel.vocabSize + " words):")
    val topics = ldaModel.topicsMatrix
    for (topic <- Range(0, 3)) {
      print("Topic " + topic + ":")
      for (word <- Range(0, ldaModel.vocabSize)) { print(" " + topics(word, topic)); }
      println()
    }

  }

}

轉載請註明出處:

http://blog.csdn.net/sunbow0/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章