-
Notifications
You must be signed in to change notification settings - Fork 29k
[SPARK-5565] [ML] LDA wrapper for Pipelines API #9513
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
Closed
Changes from 1 commit
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
c053d0a
partly done adding LDA
jkbradley 23d40c4
done adding LDA. need to add tests
jkbradley 583e173
fix indentation
jkbradley ffb68c5
Added test suite for spark.ml LDA
jkbradley 9589e01
scala style fix
jkbradley 3acc9e0
updates per code review, mostly minor
jkbradley 631d407
fixed unit tests
jkbradley 16a061c
removed optimizers and changed optimizer param to be a String
jkbradley be67704
changed concentration Params not to use -1 as special value, and to b…
jkbradley a55de6d
tiny fix
jkbradley 8eaa596
Renamed kappa, tau0 to learningDecay, learningOffset
jkbradley File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Added test suite for spark.ml LDA
- Loading branch information
commit ffb68c5af18e7755fe2e834fc16ce2cd413786d3
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
228 changes: 228 additions & 0 deletions
228
mllib/src/test/scala/org/apache/spark/ml/clustering/LDASuite.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,228 @@ | ||
| /* | ||
| * 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.SparkFunSuite | ||
| import org.apache.spark.ml.util.MLTestingUtils | ||
| import org.apache.spark.mllib.linalg.{Vector, Vectors} | ||
| import org.apache.spark.mllib.util.MLlibTestSparkContext | ||
| import org.apache.spark.sql.{DataFrame, Row, SQLContext} | ||
|
|
||
|
|
||
| object LDASuite { | ||
| def generateLDAData( | ||
| sql: SQLContext, | ||
| rows: Int, | ||
| dim: Int, | ||
| k: Int, | ||
| vocabSize: Int): DataFrame = { | ||
| val sc = sql.sparkContext | ||
| val rng = new java.util.Random() | ||
| rng.setSeed(1) | ||
| val rdd = sc.parallelize(1 to rows).map { i => | ||
| Vectors.dense(Array.fill(dim)(rng.nextInt(vocabSize).toDouble)) | ||
| }.map(v => new TestRow(v)) | ||
| sql.createDataFrame(rdd) | ||
| } | ||
| } | ||
|
|
||
|
|
||
| class LDASuite extends SparkFunSuite with MLlibTestSparkContext { | ||
|
|
||
| val k = 5 | ||
| @transient var dataset: DataFrame = _ | ||
| @transient var vocabSize: Int = _ | ||
|
|
||
| override def beforeAll(): Unit = { | ||
| super.beforeAll() | ||
|
|
||
| dataset = LDASuite.generateLDAData(sqlContext, 50, 3, k, 30) | ||
| vocabSize = dataset.flatMap(_.getAs[Vector](0).toArray.map(_.toInt).toSet) | ||
| .distinct().count().toInt | ||
| } | ||
|
|
||
| test("default parameters") { | ||
| val lda = new LDA() | ||
|
|
||
| assert(lda.getFeaturesCol === "features") | ||
| assert(lda.getMaxIter === 20) | ||
| assert(lda.isDefined(lda.seed)) | ||
| assert(!lda.isDefined(lda.checkpointInterval)) | ||
| assert(lda.getK === 10) | ||
| assert(lda.getDocConcentration === Array(-1.0)) | ||
| assert(lda.getTopicConcentration === -1.0) | ||
| assert(lda.getOptimizer.isInstanceOf[OnlineLDAOptimizer]) | ||
| val optimizer = lda.getOptimizer.asInstanceOf[OnlineLDAOptimizer] | ||
| assert(optimizer.getKappa === 0.51) | ||
| assert(optimizer.getTau0 === 1024) | ||
| assert(optimizer.getSubsamplingRate === 0.05) | ||
| assert(optimizer.getOptimizeDocConcentration) | ||
| assert(lda.getTopicDistributionCol === "topicDistribution") | ||
| } | ||
|
|
||
| test("set parameters") { | ||
| val lda = new LDA() | ||
| .setFeaturesCol("test_feature") | ||
| .setMaxIter(33) | ||
| .setSeed(123) | ||
| .setCheckpointInterval(7) | ||
| .setK(9) | ||
| .setTopicConcentration(0.56) | ||
| .setTopicDistributionCol("myOutput") | ||
|
|
||
| assert(lda.getFeaturesCol === "test_feature") | ||
| assert(lda.getMaxIter === 33) | ||
| assert(lda.getSeed === 123) | ||
| assert(lda.getCheckpointInterval === 7) | ||
| assert(lda.getK === 9) | ||
| assert(lda.getTopicConcentration === 0.56) | ||
| assert(lda.getTopicDistributionCol === "myOutput") | ||
|
|
||
|
|
||
| // setOptimizer | ||
| lda.setOptimizer("em") | ||
| assert(lda.getOptimizer.isInstanceOf[EMLDAOptimizer]) | ||
| lda.setOptimizer("online") | ||
| assert(lda.getOptimizer.isInstanceOf[OnlineLDAOptimizer]) | ||
| val optimizer = lda.getOptimizer.asInstanceOf[OnlineLDAOptimizer] | ||
| optimizer.setKappa(0.53) | ||
| assert(optimizer.getKappa === 0.53) | ||
| optimizer.setTau0(1027) | ||
| assert(optimizer.getTau0 === 1027) | ||
| optimizer.setSubsamplingRate(0.06) | ||
| assert(optimizer.getSubsamplingRate === 0.06) | ||
| optimizer.setOptimizeDocConcentration(false) | ||
| assert(!optimizer.getOptimizeDocConcentration) | ||
| } | ||
|
|
||
| test("parameters validation") { | ||
| val lda = new LDA() | ||
|
|
||
| // misc Params | ||
| intercept[IllegalArgumentException] { | ||
| new LDA().setK(1) | ||
| } | ||
| intercept[IllegalArgumentException] { | ||
| new LDA().setOptimizer("no_such_optimizer") | ||
| } | ||
| intercept[IllegalArgumentException] { | ||
| new LDA().setDocConcentration(-1.1) | ||
| } | ||
| intercept[IllegalArgumentException] { | ||
| new LDA().setTopicConcentration(-1.1) | ||
| } | ||
|
|
||
| // validateParams() | ||
| lda.setDocConcentration(-1) | ||
| assert(lda.getDocConcentration === -1) | ||
| lda.validateParams() | ||
| lda.setDocConcentration(0.1) | ||
| lda.validateParams() | ||
| lda.setDocConcentration(Range(0, lda.getK).map(_ + 2.0).toArray) | ||
| lda.validateParams() | ||
| lda.setDocConcentration(Range(0, lda.getK - 1).map(_ + 2.0).toArray) | ||
| withClue("LDA docConcentration validity check failed for bad array length") { | ||
| intercept[IllegalArgumentException] { | ||
| lda.validateParams() | ||
| } | ||
| } | ||
|
|
||
| // OnlineLDAOptimizer | ||
| intercept[IllegalArgumentException] { | ||
| new OnlineLDAOptimizer().setTau0(0) | ||
| } | ||
| intercept[IllegalArgumentException] { | ||
| new OnlineLDAOptimizer().setKappa(0) | ||
| } | ||
| intercept[IllegalArgumentException] { | ||
| new OnlineLDAOptimizer().setSubsamplingRate(0) | ||
| } | ||
| intercept[IllegalArgumentException] { | ||
| new OnlineLDAOptimizer().setSubsamplingRate(1.1) | ||
| } | ||
| } | ||
|
|
||
| test("fit & transform with Online LDA") { | ||
| val lda = new LDA().setK(k).setSeed(1).setOptimizer("online").setMaxIter(2) | ||
| val model = lda.fit(dataset) | ||
|
|
||
| MLTestingUtils.checkCopy(model) | ||
|
|
||
| assert(!model.isInstanceOf[DistributedLDAModel]) | ||
| assert(model.vocabSize === vocabSize) | ||
| assert(model.estimatedDocConcentration.size === k) | ||
| assert(model.topicsMatrix.numRows === vocabSize) | ||
| assert(model.topicsMatrix.numCols === k) | ||
| assert(!model.isDistributed) | ||
|
|
||
| // transform() | ||
| val transformed = model.transform(dataset) | ||
| val expectedColumns = Array("features", lda.getTopicDistributionCol) | ||
| expectedColumns.foreach { column => | ||
| assert(transformed.columns.contains(column)) | ||
| } | ||
| transformed.select(lda.getTopicDistributionCol).collect().foreach { r => | ||
| val topicDistribution = r.getAs[Vector](0) | ||
| assert(topicDistribution.size === vocabSize) | ||
| assert(topicDistribution.toArray.forall(w => w >= 0.0 && w <= 1.0)) | ||
| } | ||
|
|
||
| // logLikelihood, logPerplexity | ||
| val ll = model.logLikelihood(dataset) | ||
| assert(ll <= 0.0 && ll != Double.NegativeInfinity) | ||
| val lp = model.logPerplexity(dataset) | ||
| assert(lp >= 0.0 && lp != Double.PositiveInfinity) | ||
|
|
||
| // describeTopics | ||
| val topics = model.describeTopics(3) | ||
| assert(topics.count() === k) | ||
| assert(topics.select("topic").map(_.getInt(0)).collect().toSet === Range(0, k).toSet) | ||
| assert(topics.select("termIndices").collect().forall { case r: Row => | ||
| val termIndices = r.getAs[Array[Int]](0) | ||
| termIndices.length === 3 && termIndices.toSet.size === 3 | ||
| }) | ||
| assert(topics.select("termWeights").collect().forall { case r: Row => | ||
| val termWeights = r.getAs[Array[Double]](0) | ||
| termWeights.length === 3 && termWeights.forall(w => w >= 0.0 && w <= 1.0) | ||
| }) | ||
| } | ||
|
|
||
| test("fit & transform with EM LDA") { | ||
| val lda = new LDA().setK(k).setSeed(1).setOptimizer("em").setMaxIter(2) | ||
| val model_ = lda.fit(dataset) | ||
|
|
||
| MLTestingUtils.checkCopy(model_) | ||
|
|
||
| assert(model_.isInstanceOf[DistributedLDAModel]) | ||
| val model = model_.asInstanceOf[DistributedLDAModel] | ||
| assert(model.vocabSize === vocabSize) | ||
| assert(model.estimatedDocConcentration.size === k) | ||
| assert(model.topicsMatrix.numRows === vocabSize) | ||
| assert(model.topicsMatrix.numCols === k) | ||
| assert(model.isDistributed) | ||
|
|
||
| val localModel = model.toLocal | ||
| assert(!localModel.isInstanceOf[DistributedLDAModel]) | ||
|
|
||
| // training logLikelihood, logPrior | ||
| val ll = model.trainingLogLikelihood | ||
| assert(ll <= 0.0 && ll != Double.NegativeInfinity) | ||
| val lp = model.logPrior | ||
| assert(lp >= 0.0 && lp != Double.PositiveInfinity) | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
alphaand especiallyetaare confusing in this context where the implementation is in a whole different fileThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ok