Github user feynmanliang commented on a diff in the pull request:
https://github.com/apache/spark/pull/7278#discussion_r34304484
--- Diff:
mllib/src/main/scala/org/apache/spark/mllib/stat/test/ADTest.scala ---
@@ -0,0 +1,264 @@
+/*
+ * 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.test
+
+import collection.immutable.ListMap
+
+import org.apache.commons.math3.distribution.{ExponentialDistribution,
GumbelDistribution,
+ LogisticDistribution, NormalDistribution, WeibullDistribution}
+
+import org.apache.spark.rdd.RDD
+
+/**
+ * The Anderson Darling (AD) test, similarly to the Kolmogorov Smirnov
(KS) test, tests whether the
+ * data follow a given theoretical distribution. It should be used with
continuous data and
+ * assumes that no ties occur (the presence of ties can affect the
validity of the test).
+ * The AD test provides an alternative to the Kolmogorov-Smirnov test.
Namely, it is better
+ * suited to identify departures from the theoretical distribution at the
tails.
+ * It is worth noting that the the AD test's critical values depend on the
+ * distribution being tested against.
+ * The AD statistic is defined as -n - s/n, where
+ * s = sum from i=1 to n of (2i + 1)(ln(z_i) + ln(1 - z_{n+1-i})
+ * where z_i is the CDF value of the ith observation in the sorted sample.
+ * For more information
@see[[https://en.wikipedia.org/wiki/Anderson%E2%80%93Darling_test]]
+ */
+private[stat] object ADTest {
+
+ object NullHypothesis extends Enumeration {
+ type NullHypothesis = Value
+ val oneSample = Value("Sample follows theoretical distribution.")
+ }
+
+ /**
+ * ADTheoreticalDist is a trait that every distribution used in an AD
test must extend.
+ * The rationale for this is that the AD test has distribution-dependent
critical values, and by
+ * requiring extension of this trait we guarantee that future additional
distributions
+ * make sure to add the appropriate critical values (CVs) (or at least
acknowledge
+ * that they should be added)
+ */
+ sealed trait ADTheoreticalDist {
+ val params: Array[Double] // parameters used to initialized the
distribution
+
+ def cdf(x: Double): Double // calculate the cdf under the given
distribution for value x
+
+ def getCVs(n: Double): Map[Double, Double] // return appropriate CVs,
adjusted for sample size
+ }
+
+ /**
+ * Sourced from
+ *
http://civil.colorado.edu/~balajir/CVEN5454/lectures/Ang-n-Tang-Chap7-Goodness-of-fit-PDFs-
+ * test.pdf
+ *
https://github.com/scipy/scipy/blob/v0.15.1/scipy/stats/morestats.py#L1017
+ */
+
+ // Exponential distribution
+ class ADExponential(val params: Array[Double]) extends ADTheoreticalDist
{
+ private val theoretical = new ExponentialDistribution(params(0))
+
+ private val rawCVs = ListMap(
+ 0.15 -> 0.922, 0.10 -> 1.078,
+ 0.05 -> 1.341, 0.025 -> 1.606, 0.01 -> 1.957
+ )
+
+ def cdf(x: Double): Double = theoretical.cumulativeProbability(x)
+
+ def getCVs(n: Double): Map[Double, Double] = {
+ rawCVs.map { case (sig, cv) => sig -> cv / (1 + 0.6 / n)}
+ }
+ }
+
+ // Normal Distribution
+ class ADNormal(val params: Array[Double]) extends ADTheoreticalDist {
+ private val theoretical = new NormalDistribution(params(0), params(1))
+
+ private val rawCVs = ListMap(
+ 0.15 -> 0.576, 0.10 -> 0.656,
+ 0.05 -> 0.787, 0.025 -> 0.918, 0.01 -> 1.092
+ )
+
+ def cdf(x: Double): Double = theoretical.cumulativeProbability(x)
+
+ def getCVs(n: Double): Map[Double, Double] = {
+ rawCVs.map { case (sig, cv) => sig -> cv / (1 + 4.0 / n - 25.0 / (n
* n)) }
+ }
+ }
+
+ // Gumbel distribution
+ class ADGumbel(val params: Array[Double]) extends ADTheoreticalDist {
+ private val theoretical = new GumbelDistribution(params(0), params(1))
+
+ private val rawCVs = ListMap(
+ 0.25 -> 0.474, 0.10 -> 0.637,
+ 0.05 -> 0.757, 0.025 -> 0.877, 0.01 -> 1.038
+ )
+
+ def cdf(x: Double): Double = theoretical.cumulativeProbability(x)
+
+ def getCVs(n: Double): Map[Double, Double] = {
+ rawCVs.map { case (sig, cv) => sig -> cv / (1 + 0.2 / math.sqrt(n))}
+ }
+ }
+
+ // Logistic distribution
+ class ADLogistic(val params: Array[Double]) extends ADTheoreticalDist {
+ private val theoretical = new LogisticDistribution(params(0),
params(1))
+
+ private val rawCVs = ListMap(
+ 0.25 -> 0.426, 0.10 -> 0.563, 0.05 -> 0.660,
+ 0.025 -> 0.769, 0.01 -> 0.906, 0.005 -> 1.010
+ )
+
+ def cdf(x: Double): Double = theoretical.cumulativeProbability(x)
+
+ def getCVs(n: Double): Map[Double, Double] = {
+ rawCVs.map { case (sig, cv) => sig -> cv / (1 + 0.25 / n)}
+ }
+ }
+
+ // Weibull distribution
+ class ADWeibull(val params: Array[Double]) extends ADTheoreticalDist {
+ private val theoretical = new WeibullDistribution(params(0), params(1))
+
+ private val rawCVs = ListMap(
+ 0.25 -> 0.474, 0.10 -> 0.637,
+ 0.05 -> 0.757, 0.025 -> 0.877, 0.01 -> 1.038
+ )
+
+ def cdf(x: Double): Double = theoretical.cumulativeProbability(x)
+
+ def getCVs(n: Double): Map[Double, Double] = {
+ rawCVs.map { case (sig, cv) => sig -> cv / (1 + 0.2 / math.sqrt(n))}
+ }
+ }
+
+ /**
+ * Perform a one sample Anderson Darling test
+ * @param data `RDD[Double]` data to test for a given distribution
+ * @param distName `String` name of theoretical distribution: currently
supports standard normal,
+ * exponential, gumbel, logistic, weibull
+ * @param params optional variable-length argument providing parameters
for given distribution,
+ * otherwise they are estimated from sample but in both
cases we adjust critical
+ * values assuming they were estimated from sample.
Providing them is simply a
+ * convenience to avoid recalculation when the values are
already available to
+ * the user
+ * @return Anderson-Darling test result
+ */
+ def testOneSample(data: RDD[Double], distName: String, params: Double*):
ADTestResult = {
+ val n = data.count()
+ val makeDist = initDist(distName, data, n, params.toArray)
+ val localData = data.sortBy(x => x).mapPartitions(calcPartAD(_,
makeDist, n)).collect()
+ val s = localData.foldLeft((0.0, 0.0)) { case ((prevStat, prevCt),
(rawStat, adj, ct)) =>
+ val adjVal = 2 * prevCt * adj
+ val adjustedStat = rawStat + adjVal
+ val cumCt = prevCt + ct
+ (prevStat + adjustedStat, cumCt)
+ }._1
+ val ADStat = -1 * n - s / n
+ val criticalVals = makeDist().getCVs(n)
+ new ADTestResult(ADStat, criticalVals,
NullHypothesis.oneSample.toString)
+ }
+
+
+ /**
+ * Calculate a partition's contribution to the Anderson Darling
statistic.
+ * In each partition we calculate 2 values, an unadjusted value that is
contributed to the AD
+ * statistic directly, a value that must be adjusted by the number of
values in the prior
+ * partition, and a count of the elements in that partition
+ * @param part `Iterator[Double]` a partition of the data sample to be
analyzed
+ * @param makeDist `() => ADTheoreticalDist` a function to create a
class that extends the
+ * ADTheoreticalDist trait, which requires various
methods, used in creating 1
+ * object per partition
+ * @param n `Double` the total size of the data sample
+ * @return `Iterator[(Double, Double, Double)]` The first element
corresponds to the
+ * position-independent contribution to the AD statistic, the
second is the value that must
+ * be scaled by the number of elements in prior partitions and
the third is the number of
+ * elements in this partition
+ */
+ def calcPartAD(part: Iterator[Double], makeDist: () =>
ADTheoreticalDist, n: Double)
+ : Iterator[(Double, Double, Double)] = {
+ val dist = makeDist()
+ val initAcc = (0.0, 0.0, 0.0)
+ val pResult = part.zipWithIndex.foldLeft(initAcc) { case ((prevS,
prevC, prevCt), (v, i)) =>
+ val y = dist.cdf(v)
+ val a = math.log(y)
+ val b = math.log(1 - y)
+ val unAdjusted = a * (2 * i + 1) + b * (2 * n - 2 * i - 1)
+ val adjConstant = a - b
+ (prevS + unAdjusted, prevC + adjConstant, prevCt + 1)
+ }
+ Array(pResult).iterator
--- End diff --
Why do you create an `Array` and convert to `iterator`? `pResult` will have
type `Double, Double, Double` here so can't we just return that?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]