Github user jkbradley commented on a diff in the pull request:
https://github.com/apache/spark/pull/9513#discussion_r44354764
--- Diff: mllib/src/main/scala/org/apache/spark/ml/clustering/LDA.scala ---
@@ -0,0 +1,668 @@
+/*
+ * 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.ml.clustering
+
+import org.apache.spark.Logging
+import org.apache.spark.annotation.{Experimental, Since}
+import org.apache.spark.ml.util.{SchemaUtils, Identifiable}
+import org.apache.spark.ml.{Estimator, Model}
+import org.apache.spark.ml.param.shared.{HasCheckpointInterval,
HasFeaturesCol, HasSeed, HasMaxIter}
+import org.apache.spark.ml.param._
+import org.apache.spark.mllib.clustering.{DistributedLDAModel =>
OldDistributedLDAModel,
+ EMLDAOptimizer => OldEMLDAOptimizer, LDA => OldLDA, LDAModel =>
OldLDAModel,
+ LDAOptimizer => OldLDAOptimizer, LocalLDAModel => OldLocalLDAModel,
+ OnlineLDAOptimizer => OldOnlineLDAOptimizer}
+import org.apache.spark.mllib.linalg.{VectorUDT, Vectors, Matrix, Vector}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{SQLContext, DataFrame, Row}
+import org.apache.spark.sql.functions.{col, monotonicallyIncreasingId, udf}
+import org.apache.spark.sql.types.StructType
+
+
+private[clustering] trait LDAParams extends Params with HasFeaturesCol
with HasMaxIter
+ with HasSeed with HasCheckpointInterval {
+
+ /**
+ * Param for the number of topics (clusters) to infer. Must be > 1.
Default: 10.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val k = new IntParam(this, "k", "number of topics (clusters) to
infer",
+ ParamValidators.gt(1))
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getK: Int = $(k)
+
+ /**
+ * Concentration parameter (commonly named "alpha") for the prior placed
on documents'
+ * distributions over topics ("theta").
+ *
+ * This is the parameter to a Dirichlet distribution, where larger
values mean more smoothing
+ * (more regularization).
+ *
+ * If set to a singleton vector [-1], then docConcentration is set
automatically. If set to
+ * singleton vector [alpha] where alpha != -1, then alpha is replicated
to a vector of
+ * length k in fitting. Otherwise, the [[docConcentration]] vector must
be length k.
+ * (default = [-1] = automatic)
+ *
+ * Optimizer-specific parameter settings:
+ * - EM
+ * - Currently only supports symmetric distributions, so all values
in the vector should be
+ * the same.
+ * - Values should be > 1.0
+ * - default = uniformly (50 / k) + 1, where 50/k is common in LDA
libraries and +1 follows
+ * from Asuncion et al. (2009), who recommend a +1 adjustment for
EM.
+ * - Online
+ * - Values should be >= 0
+ * - default = uniformly (1.0 / k), following the implementation from
+ * [[https://github.com/Blei-Lab/onlineldavb]].
+ * @group param
+ */
+ @Since("1.6.0")
+ final val docConcentration = new DoubleArrayParam(this,
"docConcentration",
+ "Concentration parameter (commonly named \"alpha\") for the prior
placed on documents'" +
+ " distributions over topics (\"theta\").", validDocConcentration)
+
+ /** Check that the docConcentration is valid, independently of other
Params */
+ private def validDocConcentration(alpha: Array[Double]): Boolean = {
+ if (alpha.length == 1) {
+ alpha(0) == -1 || alpha(0) >= 1.0
+ } else if (alpha.length > 1) {
+ alpha.forall(_ >= 1.0)
+ } else {
+ false
+ }
+ }
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getDocConcentration: Array[Double] = $(docConcentration)
+
+ /**
+ * Concentration parameter (commonly named "beta" or "eta") for the
prior placed on topics'
+ * distributions over terms.
+ *
+ * This is the parameter to a symmetric Dirichlet distribution.
+ *
+ * Note: The topics' distributions over terms are called "beta" in the
original LDA paper
+ * by Blei et al., but are called "phi" in many later papers such as
Asuncion et al., 2009.
+ *
+ * If set to -1, then topicConcentration is set automatically.
+ * (default = -1 = automatic)
+ *
+ * Optimizer-specific parameter settings:
+ * - EM
+ * - Value should be > 1.0
+ * - default = 0.1 + 1, where 0.1 gives a small amount of smoothing
and +1 follows
+ * Asuncion et al. (2009), who recommend a +1 adjustment for EM.
+ * - Online
+ * - Value should be >= 0
+ * - default = (1.0 / k), following the implementation from
+ * [[https://github.com/Blei-Lab/onlineldavb]].
+ * @group param
+ */
+ @Since("1.6.0")
+ final val topicConcentration = new DoubleParam(this,
"topicConcentration",
+ "Concentration parameter (commonly named \"beta\" or \"eta\") for the
prior placed on topic'" +
+ " distributions over terms.", (beta: Double) => beta == -1 || beta
>= 0.0)
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getTopicConcentration: Double = $(topicConcentration)
+
+ /** Supported values for Param [[optimizer]]. */
+ final val supportedOptimizers: Array[String] = Array("online", "em")
+
+ /**
+ * Optimizer or inference algorithm used to estimate the LDA model.
+ * Currently supported (case-insensitive):
+ * - "online": Online Variational Bayes (default)
+ * - "em": Expectation-Maximization
+ *
+ * For details, see the following papers:
+ * - Online LDA:
+ * Hoffman, Blei and Bach. "Online Learning for Latent Dirichlet
Allocation."
+ * Neural Information Processing Systems, 2010.
+ *
[[http://www.cs.columbia.edu/~blei/papers/HoffmanBleiBach2010b.pdf]]
+ * - EM:
+ * Asuncion et al. "On Smoothing and Inference for Topic Models."
+ * Uncertainty in Artificial Intelligence, 2009.
+ * [[http://arxiv.org/pdf/1205.2662.pdf]]
+ *
+ * @group param
+ */
+ @Since("1.6.0")
+ final val optimizer = new Param[String](this, "optimizer", "Optimizer or
inference" +
+ " algorithm used to estimate the LDA model. Supported: " +
supportedOptimizers.mkString(", "),
+ (o: String) =>
ParamValidators.inArray(supportedOptimizers).apply(o.toLowerCase))
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getOptimizer: String = $(optimizer)
+
+ /**
+ * Output column with estimates of the topic mixture distribution for
each document (often called
+ * "theta" in the literature). Returns a vector of zeros for an empty
document.
+ *
+ * This uses a variational approximation following Hoffman et al.
(2010), where the approximate
+ * distribution is called "gamma." Technically, this method returns
this approximation "gamma"
+ * for each document.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val topicDistributionCol = new Param[String](this,
"topicDistribution", "Output column" +
+ " with estimates of the topic mixture distribution for each document
(often called \"theta\"" +
+ " in the literature). Returns a vector of zeros for an empty
document.")
+
+ setDefault(topicDistributionCol -> "topicDistribution")
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getTopicDistributionCol: String = $(topicDistributionCol)
+
+ /**
+ * A (positive) learning parameter that downweights early iterations.
Larger values make early
+ * iterations count less.
+ * Default: 1024, following the Online LDA paper (Hoffman et al., 2010).
+ * @group expertParam
+ */
+ @Since("1.6.0")
+ final val tau0 = new DoubleParam(this, "tau0", "A (positive) learning
parameter that" +
+ " downweights early iterations. Larger values make early iterations
count less.",
+ ParamValidators.gt(0))
+
+ /** @group expertGetParam */
+ @Since("1.6.0")
+ def getTau0: Double = $(tau0)
+
+ /**
+ * Learning rate, set as an exponential decay rate.
+ * This should be between (0.5, 1.0] to guarantee asymptotic convergence.
+ * Default: 0.51, based on the Online LDA paper (Hoffman et al., 2010).
+ * @group expertParam
+ */
+ @Since("1.6.0")
+ final val kappa = new DoubleParam(this, "kappa", "Learning rate, set as
an exponential decay" +
+ " rate. This should be between (0.5, 1.0] to guarantee asymptotic
convergence.",
+ ParamValidators.gt(0))
+
+ /** @group expertGetParam */
+ @Since("1.6.0")
+ def getKappa: Double = $(kappa)
+
+ /**
+ * Fraction of the corpus to be sampled and used in each iteration of
mini-batch gradient descent,
+ * in range (0, 1].
+ *
+ * Note that this should be adjusted in synch with [[LDA.maxIter]]
+ * so the entire corpus is used. Specifically, set both so that
+ * maxIterations * miniBatchFraction >= 1.
+ *
+ * Note: This is the same as the `miniBatchFraction` parameter in
+ * [[org.apache.spark.mllib.clustering.OnlineLDAOptimizer]].
+ *
+ * Default: 0.05, i.e., 5% of total documents.
+ * @group param
+ */
+ @Since("1.6.0")
+ final val subsamplingRate = new DoubleParam(this, "subsamplingRate",
"Fraction of the corpus" +
+ " to be sampled and used in each iteration of mini-batch gradient
descent, in range (0, 1].",
+ ParamValidators.inRange(0.0, 1.0, lowerInclusive = false,
upperInclusive = true))
+
+ /** @group getParam */
+ @Since("1.6.0")
+ def getSubsamplingRate: Double = $(subsamplingRate)
+
+ /**
+ * Indicates whether the docConcentration (Dirichlet parameter for
+ * document-topic distribution) will be optimized during training.
+ * Setting this to true will make the model more expressive and fit the
training data better.
+ * Default: false
+ * @group expertParam
+ */
+ @Since("1.6.0")
+ final val optimizeDocConcentration = new BooleanParam(this,
"optimizeDocConcentration",
+ "Indicates whether the docConcentration (Dirichlet parameter for
document-topic" +
+ " distribution) will be optimized during training.")
+
+ /** @group expertGetParam */
+ @Since("1.6.0")
+ def getOptimizeDocConcentration: Boolean = $(optimizeDocConcentration)
+
+ /**
+ * Validates and transforms the input schema.
+ * @param schema input schema
+ * @return output schema
+ */
+ protected def validateAndTransformSchema(schema: StructType): StructType
= {
+ SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+ SchemaUtils.appendColumn(schema, $(topicDistributionCol), new
VectorUDT)
+ }
+
+ override def validateParams(): Unit = {
+ if (getDocConcentration.length != 1) {
+ require(getDocConcentration.length == getK, s"LDA docConcentration
was of length" +
+ s" ${getDocConcentration.length}, but k = $getK. docConcentration
must be either" +
+ s" length 1 (scalar) or an array of length k.")
--- End diff --
Oops, I forgot to make this update. I'll fix it now.
---
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]