|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.spark.mllib.stat |
| 19 | + |
| 20 | +import org.apache.spark.rdd.RDD |
| 21 | + |
| 22 | +private[stat] object KernelDensity { |
| 23 | + /** |
| 24 | + * Given a set of samples from a distribution, estimates its density at the set of given points. |
| 25 | + * Uses a Gaussian kernel with the given standard deviation. |
| 26 | + */ |
| 27 | + def estimate(samples: RDD[Double], standardDeviation: Double, |
| 28 | + evaluationPoints: Array[Double]): Array[Double] = { |
| 29 | + if (standardDeviation <= 0.0) { |
| 30 | + throw new IllegalArgumentException("Standard deviation must be positive") |
| 31 | + } |
| 32 | + |
| 33 | + // This gets used in each Gaussian PDF computation, so compute it up front |
| 34 | + val logStandardDeviationPlusHalfLog2Pi = |
| 35 | + Math.log(standardDeviation) + 0.5 * Math.log(2 * Math.PI) |
| 36 | + |
| 37 | + val (points, count) = samples.aggregate((new Array[Double](evaluationPoints.length), 0))( |
| 38 | + (x, y) => { |
| 39 | + var i = 0 |
| 40 | + while (i < evaluationPoints.length) { |
| 41 | + x._1(i) += normPdf(y, standardDeviation, logStandardDeviationPlusHalfLog2Pi, |
| 42 | + evaluationPoints(i)) |
| 43 | + i += 1 |
| 44 | + } |
| 45 | + (x._1, i) |
| 46 | + }, |
| 47 | + (x, y) => { |
| 48 | + var i = 0 |
| 49 | + while (i < evaluationPoints.length) { |
| 50 | + x._1(i) += y._1(i) |
| 51 | + i += 1 |
| 52 | + } |
| 53 | + (x._1, x._2 + y._2) |
| 54 | + }) |
| 55 | + |
| 56 | + var i = 0 |
| 57 | + while (i < points.length) { |
| 58 | + points(i) /= count |
| 59 | + i += 1 |
| 60 | + } |
| 61 | + points |
| 62 | + } |
| 63 | + |
| 64 | + private def normPdf(mean: Double, standardDeviation: Double, |
| 65 | + logStandardDeviationPlusHalfLog2Pi: Double, x: Double): Double = { |
| 66 | + val x0 = x - mean |
| 67 | + val x1 = x0 / standardDeviation |
| 68 | + val logDensity = -0.5 * x1 * x1 - logStandardDeviationPlusHalfLog2Pi |
| 69 | + Math.exp(logDensity) |
| 70 | + } |
| 71 | +} |
0 commit comments