Skip to content

SPARK-2149. [MLLIB] Univariate kernel density estimation #1093

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 3 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
@@ -0,0 +1,71 @@
/*
* 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.stat

import org.apache.spark.rdd.RDD

private[stat] object KernelDensity {
/**
* Given a set of samples from a distribution, estimates its density at the set of given points.
* Uses a Gaussian kernel with the given standard deviation.
*/
def estimate(samples: RDD[Double], standardDeviation: Double,
evaluationPoints: Array[Double]): Array[Double] = {
if (standardDeviation <= 0.0) {
throw new IllegalArgumentException("Standard deviation must be positive")
}

// This gets used in each Gaussian PDF computation, so compute it up front
val logStandardDeviationPlusHalfLog2Pi =
Copy link
Member

Choose a reason for hiding this comment

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

If some of this is copied from Commons Math I'd suggest a note about its origin. I like FastMath; I think they show it is faster than Java's version. For consistency in the past I either used all FastMath or all Math. I don't know how much it matters here, using FastMath vs Java Math vs Scala Math from a consistency standpoint?

Math.log(standardDeviation) + 0.5 * Math.log(2 * Math.PI)
Copy link
Contributor

Choose a reason for hiding this comment

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

Math is being deprecated. Please replace it with math instead.

Copy link
Member

Choose a reason for hiding this comment

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

Ah, yeah I thought of that before I merged, but saw a load of usages of Math in the code. Shall I make a PR to change all of them in one go?


val (points, count) = samples.aggregate((new Array[Double](evaluationPoints.length), 0))(
(x, y) => {
var i = 0
while (i < evaluationPoints.length) {
Copy link
Member

Choose a reason for hiding this comment

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

Traversing arrays this way is to avoid copying?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Right. There might be a prettier way to do this that still avoids copying, but I've been advised against using Scala fanciness in performance-critical loops, because it has non-negligible overhead.

x._1(i) += normPdf(y, standardDeviation, logStandardDeviationPlusHalfLog2Pi,
evaluationPoints(i))
i += 1
}
(x._1, i)
},
(x, y) => {
var i = 0
while (i < evaluationPoints.length) {
x._1(i) += y._1(i)
i += 1
}
(x._1, x._2 + y._2)
})

var i = 0
while (i < points.length) {
points(i) /= count
i += 1
}
points
}

private def normPdf(mean: Double, standardDeviation: Double,
logStandardDeviationPlusHalfLog2Pi: Double, x: Double): Double = {
val x0 = x - mean
val x1 = x0 / standardDeviation
val logDensity = -0.5 * x1 * x1 - logStandardDeviationPlusHalfLog2Pi
Math.exp(logDensity)
}
}
14 changes: 14 additions & 0 deletions mllib/src/main/scala/org/apache/spark/mllib/stat/Statistics.scala
Original file line number Diff line number Diff line change
Expand Up @@ -149,4 +149,18 @@ object Statistics {
def chiSqTest(data: RDD[LabeledPoint]): Array[ChiSqTestResult] = {
ChiSqTest.chiSquaredFeatures(data)
}

/**
* Given an empirical distribution defined by the input RDD of samples, estimate its density at
* each of the given evaluation points using a Gaussian kernel.
*
* @param samples The samples RDD used to define the empirical distribution.
* @param standardDeviation The standard deviation of the kernel Gaussians.
* @param evaluationPoints The points at which to estimate densities.
* @return An array the same size as evaluationPoints with the density at each point.
*/
def kernelDensity(samples: RDD[Double], standardDeviation: Double,
evaluationPoints: Iterable[Double]): Array[Double] = {
KernelDensity.estimate(samples, standardDeviation, evaluationPoints.toArray)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* 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.stat

import org.scalatest.FunSuite

import org.apache.commons.math3.distribution.NormalDistribution

import org.apache.spark.mllib.util.LocalClusterSparkContext

class KernelDensitySuite extends FunSuite with LocalClusterSparkContext {
test("kernel density single sample") {
val rdd = sc.parallelize(Array(5.0))
val evaluationPoints = Array(5.0, 6.0)
val densities = KernelDensity.estimate(rdd, 3.0, evaluationPoints)
val normal = new NormalDistribution(5.0, 3.0)
val acceptableErr = 1e-6
assert(densities(0) - normal.density(5.0) < acceptableErr)
assert(densities(0) - normal.density(6.0) < acceptableErr)
}

test("kernel density multiple samples") {
val rdd = sc.parallelize(Array(5.0, 10.0))
val evaluationPoints = Array(5.0, 6.0)
val densities = KernelDensity.estimate(rdd, 3.0, evaluationPoints)
val normal1 = new NormalDistribution(5.0, 3.0)
val normal2 = new NormalDistribution(10.0, 3.0)
val acceptableErr = 1e-6
assert(densities(0) - (normal1.density(5.0) + normal2.density(5.0)) / 2 < acceptableErr)
assert(densities(0) - (normal1.density(6.0) + normal2.density(6.0)) / 2 < acceptableErr)
}
}