Github user witgo commented on a diff in the pull request:
https://github.com/apache/spark/pull/2388#discussion_r18768316
--- Diff:
mllib/src/main/scala/org/apache/spark/mllib/feature/TopicModeling.scala ---
@@ -0,0 +1,682 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.mllib.feature
+
+import java.util.Random
+
+import breeze.linalg.{DenseVector => BDV, SparseVector => BSV, sum =>
brzSum}
+
+import org.apache.spark.annotation.Experimental
+import org.apache.spark.broadcast.Broadcast
+import org.apache.spark.graphx._
+import org.apache.spark.Logging
+import org.apache.spark.mllib.linalg.distributed.{MatrixEntry, RowMatrix}
+import org.apache.spark.mllib.linalg.{DenseVector => SDV, SparseVector =>
SSV, Vector => SV}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.serializer.KryoRegistrator
+import org.apache.spark.storage.StorageLevel
+import org.apache.spark.SparkContext._
+
+import TopicModeling._
+
+class TopicModeling private[mllib](
+ @transient var corpus: Graph[VD, ED],
+ val numTopics: Int,
+ val numTerms: Int,
+ val alpha: Double,
+ val beta: Double,
+ @transient val storageLevel: StorageLevel)
+ extends Serializable with Logging {
+
+ def this(docs: RDD[(TopicModeling.DocId, SSV)],
+ numTopics: Int,
+ alpha: Double,
+ beta: Double,
+ storageLevel: StorageLevel = StorageLevel.MEMORY_AND_DISK,
+ computedModel: Broadcast[TopicModel] = null) {
+ this(initializeCorpus(docs, numTopics, storageLevel, computedModel),
+ numTopics, docs.first()._2.size, alpha, beta, storageLevel)
+ }
+
+
+ /**
+ * The number of documents in the corpus
+ */
+ val numDocs = docVertices.count()
+
+ /**
+ * The number of terms in the corpus
+ */
+ private val sumTerms = corpus.edges.map(e =>
e.attr.size.toDouble).sum().toLong
+
+ /**
+ * The total counts for each topic
+ */
+ @transient private var globalTopicCounter: BDV[Count] =
collectGlobalCounter(corpus, numTopics)
+ assert(brzSum(globalTopicCounter) == sumTerms)
+
+ @transient private val sc = corpus.vertices.context
+ @transient private val seed = new Random().nextInt()
+ @transient private var innerIter = 1
+ @transient private var cachedEdges: EdgeRDD[ED, VD] = corpus.edges
+ @transient private var cachedVertices: VertexRDD[VD] = corpus.vertices
+
+ private def termVertices = corpus.vertices.filter(t => t._1 >= 0)
+
+ private def docVertices = corpus.vertices.filter(t => t._1 < 0)
+
+ private def checkpoint(): Unit = {
+ if (innerIter % 10 == 0 && sc.getCheckpointDir.isDefined) {
+ val edges = corpus.edges.map(t => t)
+ edges.checkpoint()
+ val newCorpus: Graph[VD, ED] = Graph.fromEdges(edges, null,
+ storageLevel, storageLevel)
+ corpus = updateCounter(newCorpus, numTopics).cache()
+ }
+ }
+
+ private def gibbsSampling(): Unit = {
+ val corpusTopicDist = collectTermTopicDist(corpus, globalTopicCounter,
+ sumTerms, numTerms, numTopics, alpha, beta)
+
+ val corpusSampleTopics = sampleTopics(corpusTopicDist,
globalTopicCounter,
+ sumTerms, innerIter + seed, numTerms, numTopics, alpha, beta)
+ corpusSampleTopics.edges.setName(s"edges-$innerIter").cache().count()
+ Option(cachedEdges).foreach(_.unpersist())
+ cachedEdges = corpusSampleTopics.edges
+
+ corpus = updateCounter(corpusSampleTopics, numTopics)
+ corpus.vertices.setName(s"vertices-$innerIter").cache()
+ globalTopicCounter = collectGlobalCounter(corpus, numTopics)
+ assert(brzSum(globalTopicCounter) == sumTerms)
+ Option(cachedVertices).foreach(_.unpersist())
+ cachedVertices = corpus.vertices
+
+ checkpoint()
+ innerIter += 1
+ }
+
+ def saveTopicModel(burnInIter: Int): TopicModel = {
+ val topicModel = TopicModel(numTopics, numTerms, alpha, beta)
+ for (iter <- 1 to burnInIter) {
+ logInfo("Save TopicModel (Iteration %d/%d)".format(iter, burnInIter))
+ gibbsSampling()
+ updateTopicModel(termVertices, topicModel)
+ }
+ topicModel.gtc :/= burnInIter.toDouble
+ topicModel.ttc.foreach(_ :/= burnInIter.toDouble)
+ topicModel
+ }
+
+ def runGibbsSampling(iterations: Int): Unit = {
+ for (iter <- 1 to iterations) {
+ logInfo("Start Gibbs sampling (Iteration %d/%d)".format(iter,
iterations))
+ gibbsSampling()
+ }
+ }
+
+ @Experimental
+ def mergeDuplicateTopic(threshold: Double = 0.95D): Map[Int, Int] = {
+ val rows = termVertices.map(t => t._2.counter).map { bsv =>
+ val length = bsv.length
+ val used = bsv.used
+ val index = bsv.index.slice(0, used)
+ val data = bsv.data.slice(0, used).map(_.toDouble)
+ new SSV(length, index, data).asInstanceOf[SV]
+ }
+ val simMatrix = new RowMatrix(rows).columnSimilarities()
+ val minMap = simMatrix.entries.filter { case MatrixEntry(row, column,
sim) =>
+ sim > threshold && row != column
+ }.map { case MatrixEntry(row, column, sim) =>
+ (column.toInt, row.toInt)
+ }.groupByKey().map { case (topic, simTopics) =>
+ (topic, simTopics.min)
+ }.collect().toMap
+ if (minMap.size > 0) {
+ corpus = corpus.mapEdges(edges => {
+ edges.attr.map { topic =>
+ minMap.get(topic).getOrElse(topic)
+ }
+ })
+ corpus = updateCounter(corpus, numTopics)
+ }
+ minMap
+ }
+
+ def perplexity(): Double = {
+ val totalTopicCounter = this.globalTopicCounter
+ val numTopics = this.numTopics
+ val numTerms = this.numTerms
+ val alpha = this.alpha
+ val beta = this.beta
+
+ val newCounts = corpus.mapReduceTriplets[Int](triplet => {
+ val size = triplet.attr.size
+ val docId = triplet.dstId
+ val wordId = triplet.srcId
+ Iterator((docId, size), (wordId, size))
+ }, (a, b) => a + b)
+ val (termProb, totalNum) = corpus.outerJoinVertices(newCounts) {
+ (_, f, n) =>
+ (f.counter, n.get)
+ }.mapTriplets {
+ triplet =>
+ val (termCounter, _) = triplet.srcAttr
+ val (docTopicCounter, docTopicCount) = triplet.dstAttr
+ var probWord = 0D
+ val size = triplet.attr.size
+ (0 until numTopics).foreach {
+ topic =>
+ val phi = (termCounter(topic) + beta) /
(totalTopicCounter(topic) + numTerms * beta)
+ val theta = (docTopicCounter(topic) + alpha) / (docTopicCount
+ alpha * numTopics)
+ probWord += phi * theta
+ }
+ (Math.log(probWord * size) * size, size)
+ }.edges.map(t => t.attr).reduce {
+ (lhs, rhs) =>
+ (lhs._1 + rhs._1, lhs._2 + rhs._2)
+ }
+ math.exp(-1 * termProb / totalNum)
+ }
+}
+
+
+object TopicModeling {
+
+ private[mllib] type DocId = VertexId
+ private[mllib] type WordId = VertexId
+ private[mllib] type Count = Int
+ private[mllib] type ED = Array[Count]
+
+ private[mllib] case class VD(counter: BSV[Count], dist: BSV[Double],
dist1: BSV[Double])
+
+ def train(docs: RDD[(DocId, SSV)],
+ numTopics: Int = 2048,
+ totalIter: Int = 150,
+ burnIn: Int = 5,
+ alpha: Double = 0.1,
+ beta: Double = 0.01): TopicModel = {
+ require(totalIter > burnIn, "totalIter is less than burnIn")
+ require(totalIter > 0, "totalIter is less than 0")
+ require(burnIn > 0, "burnIn is less than 0")
+ val topicModeling = new TopicModeling(docs, numTopics, alpha, beta)
+ topicModeling.runGibbsSampling(totalIter - burnIn)
+ topicModeling.saveTopicModel(burnIn)
+ }
+
+ def incrementalTrain(docs: RDD[(DocId, SSV)],
+ computedModel: TopicModel,
+ totalIter: Int = 150,
+ burnIn: Int = 5): TopicModel = {
+ require(totalIter > burnIn, "totalIter is less than burnIn")
+ require(totalIter > 0, "totalIter is less than 0")
+ require(burnIn > 0, "burnIn is less than 0")
+ val numTopics = computedModel.ttc.size
+ val alpha = computedModel.alpha
+ val beta = computedModel.beta
+
+ val broadcastModel = docs.context.broadcast(computedModel)
+ val topicModeling = new TopicModeling(docs, numTopics, alpha, beta,
+ computedModel = broadcastModel)
+ broadcastModel.unpersist()
+ topicModeling.runGibbsSampling(totalIter - burnIn)
+ topicModeling.saveTopicModel(burnIn)
+ }
+
+ private[mllib] def collectTermTopicDist(graph: Graph[VD, ED],
+ totalTopicCounter: BDV[Count],
+ sumTerms: Long,
+ numTerms: Int,
+ numTopics: Int,
+ alpha: Double,
+ beta: Double): Graph[VD, ED] = {
+ val newVD = graph.vertices.filter(_._1 >= 0).map { v =>
+ val vertexId = v._1
+ val termTopicCounter = v._2.counter
+ termTopicCounter.compact()
+ val length = termTopicCounter.length
+ val used = termTopicCounter.used
+ val index = termTopicCounter.index
+ val data = termTopicCounter.data
+ val w = new Array[Double](used)
+ val w1 = new Array[Double](used)
+
+ var wi = 0D
+ var i = 0
+
+ while (i < used) {
+ val topic = index(i)
+ val count = data(i)
+ var adjustment = 0D
+ val alphaAS = alpha
+
+ w(i) = count * ((totalTopicCounter(topic) * (alpha * numTopics)) +
+ (alpha * numTopics) * (adjustment + alphaAS) +
+ adjustment * (sumTerms - 1 + (alphaAS * numTopics))) /
+ (totalTopicCounter(topic) + (numTerms * beta)) /
--- End diff --
There is a small bug.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]