-
Notifications
You must be signed in to change notification settings - Fork 28.4k
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
SPARK-4156 [MLLIB] EM algorithm for GMMs #3022
Changes from 28 commits
c15405c
5c96c57
c1a8e16
719d8cc
86fb382
e6ea805
676e523
8aaa17d
9770261
e7d413b
dc9c742
97044cf
f407b4c
b99ecc4
2df336b
c3b8ce0
d695034
9be2534
8b633f3
42b2142
20ebca1
cff73e0
308c8ad
227ad66
578c2d1
1de73f3
b97fe00
9b2fc2a
acf1fba
709e4bf
aaa8f25
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
/* | ||
* 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.examples.mllib | ||
|
||
import org.apache.spark.{SparkConf, SparkContext} | ||
import org.apache.spark.mllib.clustering.GaussianMixtureModelEM | ||
import org.apache.spark.mllib.linalg.Vectors | ||
|
||
/** | ||
* An example Gaussian Mixture Model EM app. Run with | ||
* {{{ | ||
* ./bin/run-example org.apache.spark.examples.mllib.DenseGmmEM <input> <k> <covergenceTol> | ||
* }}} | ||
* If you use it as a template to create your own app, please use `spark-submit` to submit your app. | ||
*/ | ||
object DenseGmmEM { | ||
def main(args: Array[String]): Unit = { | ||
if (args.length != 3) { | ||
println("usage: DenseGmmEM <input file> <k> <convergenceTol>") | ||
} else { | ||
run(args(0), args(1).toInt, args(2).toDouble) | ||
} | ||
} | ||
|
||
private def run(inputFile: String, k: Int, convergenceTol: Double) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we take maxIterations as an optional input parameter? |
||
val conf = new SparkConf().setAppName("Gaussian Mixture Model EM example") | ||
val ctx = new SparkContext(conf) | ||
|
||
val data = ctx.textFile(inputFile).map { line => | ||
Vectors.dense(line.trim.split(' ').map(_.toDouble)) | ||
}.cache() | ||
|
||
val clusters = new GaussianMixtureModelEM() | ||
.setK(k) | ||
.setConvergenceTol(convergenceTol) | ||
.run(data) | ||
|
||
for (i <- 0 until clusters.k) { | ||
println("weight=%f\nmu=%s\nsigma=\n%s\n" format | ||
(clusters.weight(i), clusters.mu(i), clusters.sigma(i))) | ||
} | ||
|
||
println("Cluster labels (first <= 100):") | ||
val clusterLabels = clusters.predictLabels(data) | ||
clusterLabels.take(100).foreach { x => | ||
print(" " + x) | ||
} | ||
println() | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
/* | ||
* 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.clustering | ||
|
||
import breeze.linalg.{DenseVector => BreezeVector} | ||
|
||
import org.apache.spark.rdd.RDD | ||
import org.apache.spark.mllib.linalg.{Matrix, Vector} | ||
import org.apache.spark.mllib.stat.impl.MultivariateGaussian | ||
|
||
/** | ||
* Multivariate Gaussian Mixture Model (GMM) consisting of k Gaussians, where points | ||
* are drawn from each Gaussian i=1..k with probability w(i); mu(i) and sigma(i) are | ||
* the respective mean and covariance for each Gaussian distribution i=1..k. | ||
* | ||
* @param weight Weights for each Gaussian distribution in the mixture, where mu(i) is | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Typing mistake ,where "weight(i)" is |
||
* the weight for Gaussian i, and weight.sum == 1 | ||
* @param mu Means for each Gaussian in the mixture, where mu(i) is the mean for Gaussian i | ||
* @param sigma Covariance maxtrix for each Gaussian in the mixture, where sigma(i) is the | ||
* covariance matrix for Gaussian i | ||
*/ | ||
class GaussianMixtureModel( | ||
val weight: Array[Double], | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thinking more about this API, I now believe it would be better to have it store an array of weights + an array of MultivariateGaussian instances. That would require making the MultivariateGaussian API public. I'll check some other libraries to get a sense of what their MultivariateGaussian APIs look like. If you're interested, I can let you know what I find so we can make this API change in this PR. However, if you prefer, I'd be happy to send a follow-up PR which makes this change. What do you prefer? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I know Breeze has a MultivariateGaussian, but using it requires commons-math, which does not appear to get packaged with Spark (my first pass at this algo used it and failed at run time due to the missing dependency). It would be really cool if we could use that implementation (I'm guessing it would side-step the whole covariace matrix inversion issue, too). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We only use Breeze internally right now; we don't want to expose it as a public API. I really meant using the MultivariateGaussian class which you defined. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. +1 on @jkbradley 's suggestion, which we can do in a follow-up PR. |
||
val mu: Array[Vector], | ||
val sigma: Array[Matrix]) extends Serializable { | ||
|
||
/** Number of gaussians in mixture */ | ||
def k: Int = weight.length | ||
|
||
/** Maps given points to their cluster indices. */ | ||
def predictLabels(points: RDD[Vector]): RDD[Int] = { | ||
val responsibilityMatrix = predictMembership(points, mu, sigma, weight, k) | ||
responsibilityMatrix.map(r => r.indexOf(r.max)) | ||
} | ||
|
||
/** | ||
* Given the input vectors, return the membership value of each vector | ||
* to all mixture components. | ||
*/ | ||
def predictMembership( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should it be a private method inside There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I like the idea of being able to get back soft clustering results, not just hard predictions. I'm voting for having predictMembership() return soft clusterings (Vector of cluster membership degrees for each cluster), and predict() return hard clusterings (Int indicating cluster, as in KMeansModel). |
||
points: RDD[Vector], | ||
mu: Array[Vector], | ||
sigma: Array[Matrix], | ||
weight: Array[Double], | ||
k: Int): RDD[Array[Double]] = { | ||
val sc = points.sparkContext | ||
val dists = sc.broadcast { | ||
(0 until k).map { i => | ||
new MultivariateGaussian(mu(i).toBreeze.toDenseVector, sigma(i).toBreeze.toDenseMatrix) | ||
}.toArray | ||
} | ||
val weights = sc.broadcast(weight) | ||
points.map { x => | ||
computeSoftAssignments(x.toBreeze.toDenseVector, dists.value, weights.value, k) | ||
} | ||
} | ||
|
||
// We use "eps" as the minimum likelihood density for any given point | ||
// in every cluster; this prevents any divide by zero conditions for | ||
// outlier points. | ||
private val eps = math.pow(2.0, -52) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. EPS is defined in |
||
|
||
/** | ||
* Compute the partial assignments for each vector | ||
*/ | ||
private def computeSoftAssignments( | ||
pt: BreezeVector[Double], | ||
dists: Array[MultivariateGaussian], | ||
weights: Array[Double], | ||
k: Int): Array[Double] = { | ||
val p = weights.zip(dists).map { case (weight, dist) => eps + weight * dist.pdf(pt) } | ||
val pSum = p.sum | ||
for (i <- 0 until k) { | ||
p(i) /= pSum | ||
} | ||
p | ||
} | ||
} |
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.
Please add documentation similar to other examples (e.g., DenseKMeans.scala)