Skip to content
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

Closed
wants to merge 31 commits into from
Closed
Show file tree
Hide file tree
Changes from 28 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
c15405c
SPARK-4156
Oct 30, 2014
5c96c57
Merge remote-tracking branch 'upstream/master'
Nov 11, 2014
c1a8e16
Made GaussianMixtureModel class serializable
Nov 11, 2014
719d8cc
Added scala test suite with basic test
tgaloppo Nov 13, 2014
86fb382
Merge remote-tracking branch 'upstream/master'
tgaloppo Nov 17, 2014
e6ea805
Merged with master branch; update test suite with latest context chan…
tgaloppo Nov 18, 2014
676e523
Fixed to no longer ignore delta value provided on command line
tgaloppo Dec 3, 2014
8aaa17d
Added additional train() method to companion object for cluster count…
tgaloppo Dec 3, 2014
9770261
Corrected a variety of style and naming issues.
tgaloppo Dec 12, 2014
e7d413b
Moved multivariate Gaussian utility class to mllib/stat/impl
tgaloppo Dec 12, 2014
dc9c742
Moved MultivariateGaussian utility class
tgaloppo Dec 12, 2014
97044cf
Fixed style issues
tgaloppo Dec 16, 2014
f407b4c
Added predict() to return the cluster labels and membership values
FlytxtRnD Dec 16, 2014
b99ecc4
Merge pull request #1 from FlytxtRnD/predictBranch
tgaloppo Dec 16, 2014
2df336b
Fixed style issue
tgaloppo Dec 16, 2014
c3b8ce0
Merge branch 'master' of https://github.com/tgaloppo/spark
tgaloppo Dec 16, 2014
d695034
Fixed style issues
tgaloppo Dec 16, 2014
9be2534
Style issue
tgaloppo Dec 16, 2014
8b633f3
Style issue
tgaloppo Dec 16, 2014
42b2142
Added functionality to allow setting of GMM starting point.
tgaloppo Dec 17, 2014
20ebca1
Removed unusued code
tgaloppo Dec 17, 2014
cff73e0
Replaced accumulators with RDD.aggregate
tgaloppo Dec 17, 2014
308c8ad
Numerous changes to improve code
tgaloppo Dec 18, 2014
227ad66
Moved prediction methods into model class.
tgaloppo Dec 18, 2014
578c2d1
Removed unused import
tgaloppo Dec 18, 2014
1de73f3
Removed redundant array from array creation
tgaloppo Dec 18, 2014
b97fe00
Minor fixes and tweaks.
tgaloppo Dec 19, 2014
9b2fc2a
Style improvements
tgaloppo Dec 20, 2014
acf1fba
Fixed parameter comment in GaussianMixtureModel
tgaloppo Dec 22, 2014
709e4bf
fixed usage line to include optional maxIterations parameter
tgaloppo Dec 22, 2014
aaa8f25
MLUtils: changed privacy of EPSILON from [util] to [mllib]
tgaloppo Dec 22, 2014
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
@@ -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 {
Copy link
Member

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)

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) {
Copy link
Contributor

Choose a reason for hiding this comment

The 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
Copy link
Contributor

Choose a reason for hiding this comment

The 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],
Copy link
Member

Choose a reason for hiding this comment

The 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?

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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).

Copy link
Member

Choose a reason for hiding this comment

The 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.

Copy link
Contributor

Choose a reason for hiding this comment

The 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(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should it be a private method inside object GaussianMixtureModel?

Copy link
Member

Choose a reason for hiding this comment

The 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)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

EPS is defined in MLUtils.EPSILON.


/**
* 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
}
}
Loading