Skip to content

[SPARK-10809] [MLlib] Single-document topicDistributions method for LocalLDAModel #9484

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,32 @@ class LocalLDAModel private[spark] (
}
}

/**
* Predicts the topic mixture distribution for a document (often called "theta" in the
* literature). Returns a vector of zeros for an empty document.
*
* Note this means to allow quick query for single document. For batch documents, please refer
* to [[topicDistributions()]] to avoid overhead.
*
* @param document document to predict topic mixture distributions for
* @return topic mixture distribution for the document
*/
@Since("2.0.0")
def topicDistribution(document: Vector): Vector = {
val expElogbeta = exp(LDAUtils.dirichletExpectation(topicsMatrix.toBreeze.toDenseMatrix.t).t)
if (document.numNonzeros == 0) {
Vectors.zeros(this.k)
} else {
val (gamma, _) = OnlineLDAOptimizer.variationalTopicInference(
document,
expElogbeta,
this.docConcentration.toBreeze,
gammaShape,
this.k)
Vectors.dense(normalize(gamma, 1.0).toArray)
}
}

/**
* Java-friendly version of [[topicDistributions]]
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -366,17 +366,26 @@ class LDASuite extends SparkFunSuite with MLlibTestSparkContext {
(0, 0.99504), (1, 0.99504),
(1, 0.99504), (1, 0.99504))

val actualPredictions = ldaModel.topicDistributions(docs).map { case (id, topics) =>
val actualPredictions = ldaModel.topicDistributions(docs).cache()
val topTopics = actualPredictions.map { case (id, topics) =>
// convert results to expectedPredictions format, which only has highest probability topic
val topicsBz = topics.toBreeze.toDenseVector
(id, (argmax(topicsBz), max(topicsBz)))
}.sortByKey()
.values
.collect()

expectedPredictions.zip(actualPredictions).forall { case (expected, actual) =>
expected._1 === actual._1 && (expected._2 ~== actual._2 relTol 1E-3D)
expectedPredictions.zip(topTopics).foreach { case (expected, actual) =>
assert(expected._1 === actual._1 && (expected._2 ~== actual._2 relTol 1E-3D))
}

docs.collect()
.map(doc => ldaModel.topicDistribution(doc._2))
.zip(actualPredictions.map(_._2).collect())
.foreach { case (single, batch) =>
assert(single ~== batch relTol 1E-3D)
}
actualPredictions.unpersist()
}

test("OnlineLDAOptimizer with asymmetric prior") {
Expand Down