├── README.md
├── src
├── main
│ ├── TTest
│ │ ├── TTestUtil.scala
│ │ ├── OneSampleTTest.scala
│ │ ├── PairTwoSampleTTest.scala
│ │ └── TwoSampleIndependentTTest.scala
│ ├── KolmogorovSmirnovTest
│ │ └── KolmogorovSmirnovTest.scala
│ ├── ANOVA
│ │ └── OneWayANOVA.scala
│ └── MannWhitneyUTest
│ │ └── MannWhitneyUTest.scala
└── test
│ ├── ANOVASuite.scala
│ ├── MannWhitneyUTestSuite.scala
│ └── TTestSuite.scala
└── LICENSE
/README.md:
--------------------------------------------------------------------------------
1 | # Spark.statistics
2 |
3 | Assembly of fundamental statistics implemented based on Apache Spark
4 |
5 | ## Requirements
6 |
7 | This documentation is for Spark 1.3+. Other version will probably work yet not tested.
8 |
9 | ## Features
10 |
11 | `Spark.statistics` intends to provide fundamental statistics functions.
12 |
13 | Currently we support:
14 | * One Sample T Test,
15 | * Independent Samples T Test
16 | * Paired Samples T Test
17 | * One way ANOVA
18 |
19 | Hopefully more features will come in quickly, next on the list:
20 | * Post Hoc comparison
21 | * Log likelihood
22 | * Kolmogorov-Smirnov
23 |
24 |
25 | ## Example
26 |
27 | ### Scala API
28 |
29 | ```scala
30 | val sample1 = Array(100d, 200d, 300d, 400d)
31 | val sample2 = Array(101d, 205d, 300d, 400d)
32 |
33 | val rdd1 = sc.parallelize(sample1)
34 | val rdd2 = sc.parallelize(sample2)
35 |
36 | new TwoSampleIndependentTTest().tTest(rdd1, rdd2, 0.05))
37 | new TwoSampleIndependentTTest().tTest(rdd1, rdd2)
38 | ```
39 |
--------------------------------------------------------------------------------
/src/main/TTest/TTestUtil.scala:
--------------------------------------------------------------------------------
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 | package org.apache.spark.mllib.stat
18 |
19 | import org.apache.commons.math3.distribution.TDistribution
20 | import org.apache.spark.rdd.RDD
21 |
22 | /**
23 | * Created by yuhao on 12/31/15.
24 | */
25 | trait TTestBasic {
26 |
27 | private[stat] def t(m: Double, mu: Double, v: Double, n: Long): Double = {
28 | val t = math.abs((m - mu) / math.sqrt(v / n))
29 | val TDistribution = new TDistribution(null, n - 1.0D)
30 | return 2.0D * TDistribution.cumulativeProbability(-t)
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/test/ANOVASuite.scala:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import java.util
4 |
5 | import main.ANOVA.OneWayANOVA
6 | import org.apache.commons.math3.stat.inference.TestUtils
7 | import org.apache.log4j.{Level, Logger}
8 | import org.apache.spark.mllib.stat.OneSampleTTest
9 | import org.apache.spark.{SparkContext, SparkConf}
10 |
11 | /**
12 | * Created by yuhao on 1/4/16.
13 | */
14 | object ANOVASuite {
15 |
16 | Logger.getLogger("org").setLevel(Level.WARN)
17 | Logger.getLogger("akka").setLevel(Level.WARN)
18 | val conf = new SparkConf().setAppName("TallSkinnySVD").setMaster("local")
19 | val sc = new SparkContext(conf)
20 |
21 | def main(args: Array[String]) {
22 | OneWayANOVA
23 | }
24 |
25 | def OneWayANOVA(): Unit ={
26 | val sample1 = Array(100d, 200d, 300d, 400d)
27 | val sample2 = Array(101d, 200d, 300d, 400d)
28 | val sample3 = Array(102d, 200d, 300d, 400d)
29 | val data = new util.ArrayList[Array[Double]]()
30 | data.add(sample1)
31 | data.add(sample2)
32 | data.add(sample3)
33 |
34 | val rdd1 = sc.parallelize(sample1)
35 | val rdd2 = sc.parallelize(sample2)
36 | val rdd3 = sc.parallelize(sample3)
37 | val rddData = Seq(rdd1, rdd2, rdd3)
38 |
39 | assert(TestUtils.oneWayAnovaFValue(data) == new OneWayANOVA().anovaFValue(rddData))
40 | assert(TestUtils.oneWayAnovaPValue(data) == new OneWayANOVA().anovaPValue(rddData))
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/src/test/MannWhitneyUTestSuite.scala:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import org.apache.commons.math3.stat.inference.MannWhitneyUTest
4 | import org.apache.log4j.{Level, Logger}
5 | import org.apache.spark.{SparkContext, SparkConf}
6 |
7 | /**
8 | * Created by yuhao on 2/8/16.
9 | */
10 | object MannWhitneyUTestSuite {
11 |
12 | Logger.getLogger("org").setLevel(Level.WARN)
13 | Logger.getLogger("akka").setLevel(Level.WARN)
14 | val conf = new SparkConf().setAppName("TallSkinnySVD").setMaster("local")
15 | val sc = new SparkContext(conf)
16 |
17 | def main(args: Array[String]) {
18 | testMannWhitneyU
19 | testMannWhitneyUTest
20 | }
21 |
22 | private def testMannWhitneyU(): Unit ={
23 | val sample1 = Array(1d, 3d, 5, 7)
24 | val sample2 = Array(2, 4, 6, 8d)
25 |
26 | val rdd1 = sc.parallelize(sample1)
27 | val rdd2 = sc.parallelize(sample2)
28 |
29 | val result = new MannWhitneyUTest()
30 | .mannWhitneyU(sample1, sample2)
31 | val result2 = org.apache.spark.mllib.stat.test.MannWhitneyUTest.mannWhitneyU(rdd1, rdd2)
32 | assert(result == result2)
33 | }
34 |
35 | private def testMannWhitneyUTest(): Unit ={
36 | val sample1 = Array(1d, 3d, 5, 7)
37 | val sample2 = Array(2, 4, 6, 8d)
38 |
39 | val rdd1 = sc.parallelize(sample1)
40 | val rdd2 = sc.parallelize(sample2)
41 |
42 | val result = new MannWhitneyUTest()
43 | .mannWhitneyUTest(sample1, sample2)
44 | val result2 = org.apache.spark.mllib.stat.test.MannWhitneyUTest.mannWhitneyUTest(rdd1, rdd2)
45 | println(result)
46 | println(result2)
47 | assert(result == result2)
48 | }
49 |
50 |
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/KolmogorovSmirnovTest/KolmogorovSmirnovTest.scala:
--------------------------------------------------------------------------------
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 | package org.apache.spark.mllib.stat.test
18 |
19 | import org.apache.commons.math3.util.FastMath
20 |
21 | /**
22 | * We just found out KolmogorovSmirnovTest was included in Spark 1.6.
23 | * Instead of providing a new implementation, it better aligns with
24 | * users' interests if we can provide improvement or new functions based
25 | * on the Spark version. If you find something potentially useful yet missing
26 | * from Spark, please go ahead and create an issue in the project.
27 | *
28 | */
29 | object KolmogorovSmirnovTest {
30 |
31 | def ksSum (t: Double, tolerance: Double, maxIterations: Int): Double = {
32 | if (t == 0.0) {
33 | return 0.0
34 | }
35 | val x: Double = -2 * t * t
36 | var sign: Int = -1
37 | var i: Long = 1
38 | var partialSum: Double = 0.5d
39 | var delta: Double = 1
40 | while (delta > tolerance && i < maxIterations) {
41 | delta = FastMath.exp(x * i * i)
42 | partialSum += sign * delta
43 | sign *= -1
44 | i += 1
45 | }
46 | partialSum * 2
47 | }
48 | }
49 |
50 |
--------------------------------------------------------------------------------
/src/test/TTestSuite.scala:
--------------------------------------------------------------------------------
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.commons.math3.stat.inference.TestUtils
21 | import org.apache.log4j.{Level, Logger}
22 | import org.apache.spark.{SparkConf, SparkContext}
23 |
24 |
25 | /**
26 | * Created by yuhao on 12/31/15.
27 | */
28 | object TTestSuite {
29 |
30 | Logger.getLogger("org").setLevel(Level.WARN)
31 | Logger.getLogger("akka").setLevel(Level.WARN)
32 | val conf = new SparkConf().setAppName("TallSkinnySVD").setMaster("local")
33 | val sc = new SparkContext(conf)
34 |
35 | def main(args: Array[String]) {
36 | OneSampleTTest
37 | twoIndependentSampleTTest
38 | pairedTwoSampleTTest
39 | }
40 |
41 | def OneSampleTTest(): Unit ={
42 | val observed = Array(100d, 200d, 300d, 400d)
43 | val mu = 2.5d
44 |
45 | assert(TestUtils.tTest(mu, observed, 0.05) == new OneSampleTTest().tTest(mu, sc.parallelize(observed), 0.05))
46 | assert(TestUtils.tTest(mu, observed) == new OneSampleTTest().tTest(mu, sc.parallelize(observed)))
47 | }
48 |
49 | def twoIndependentSampleTTest(): Unit ={
50 | val sample1 = Array(100d, 200d, 300d, 400d)
51 | val sample2 = Array(101d, 205d, 300d, 400d)
52 |
53 | val rdd1 = sc.parallelize(sample1)
54 | val rdd2 = sc.parallelize(sample2)
55 |
56 | assert(TestUtils.tTest(sample1, sample2, 0.05) == new TwoSampleIndependentTTest().tTest(rdd1, rdd2, 0.05))
57 | assert(TestUtils.tTest(sample1, sample2) == new TwoSampleIndependentTTest().tTest(rdd1, rdd2))
58 | }
59 |
60 | def pairedTwoSampleTTest(): Unit ={
61 | val sample1 = Array(100d, 200d, 300d, 400d)
62 | val sample2 = Array(101d, 202d, 300d, 400d)
63 |
64 | val rdd1 = sc.parallelize(sample1)
65 | val rdd2 = sc.parallelize(sample2)
66 |
67 | assert(TestUtils.pairedTTest(sample1, sample2, 0.05) == new PairTwoSampleTTest().tTest(rdd1, rdd2, 0.05))
68 | assert(TestUtils.pairedTTest(sample1, sample2) == new PairTwoSampleTTest().tTest(rdd1, rdd2))
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/ANOVA/OneWayANOVA.scala:
--------------------------------------------------------------------------------
1 | package main.ANOVA
2 |
3 | import org.apache.commons.math3.distribution.FDistribution
4 | import org.apache.spark.rdd.RDD
5 |
6 |
7 | /**
8 | * Created by yuhao on 1/1/16.
9 | */
10 | class OneWayANOVA {
11 |
12 | /**
13 | * Performs an ANOVA test, evaluating the null hypothesis that there
14 | * is no difference among the means of the data categories.
15 | *
16 | * @param categoryData Collection of RDD[Double], each containing data for one category
17 | * @param alpha significance level of the test
18 | * @return true if the null hypothesis can be rejected with
19 | * confidence 1 - alpha
20 | */
21 | def anovaTest(categoryData: Iterable[RDD[Double]], alpha: Double): Boolean = {
22 | anovaPValue(categoryData) < alpha
23 | }
24 |
25 | /**
26 | * Computes the ANOVA F-value for a collection of RDD[double].
27 | *
28 | * This implementation computes the F statistic using the definitional
29 | * formula
30 | * F = msbg/mswg
31 | * where
32 | * msbg = between group mean square
33 | * mswg = within group mean square
34 | *
35 | * @param categoryData Collection of RDD[Double], each containing data for one category
36 | * @return Fvalue
37 | */
38 | def anovaFValue(categoryData: Iterable[RDD[Double]]): Double = {
39 | getAnovaStats(categoryData).F
40 | }
41 |
42 |
43 |
44 | /**
45 | * Computes the ANOVA P-value for a collection of double[]
46 | * arrays.
47 | *
48 | * @param categoryData Collection of RDD[Double], each containing data for one category
49 | * @return Pvalue
50 | */
51 | def anovaPValue(categoryData: Iterable[RDD[Double]]): Double = {
52 | val anovaStats = getAnovaStats(categoryData)
53 |
54 | val fdist: FDistribution = new FDistribution(null, anovaStats.dfbg, anovaStats.dfwg)
55 | return 1.0 - fdist.cumulativeProbability(anovaStats.F)
56 | }
57 |
58 | private case class ANOVAStats(dfbg: Double, dfwg: Double, F: Double)
59 |
60 | private def getAnovaStats(categoryData: Iterable[RDD[Double]]): ANOVAStats = {
61 | var dfwg: Long = 0
62 | var sswg: Double = 0
63 | var totsum: Double = 0
64 | var totsumsq: Double = 0
65 | var totnum: Long = 0
66 |
67 | for (data <- categoryData) {
68 | val sum: Double = data.sum()
69 | val sumsq: Double = data.map(i => i * i).sum()
70 | val num = data.count()
71 | totnum += num
72 | totsum += sum
73 | totsumsq += sumsq
74 | dfwg += num - 1
75 | val ss: Double = sumsq - ((sum * sum) / num)
76 | sswg += ss
77 | }
78 |
79 | val sst: Double = totsumsq - ((totsum * totsum) / totnum)
80 | val ssbg: Double = sst - sswg
81 | val dfbg: Int = categoryData.size - 1
82 | val msbg: Double = ssbg / dfbg
83 | val mswg: Double = sswg / dfwg
84 | val F: Double = msbg / mswg
85 | ANOVAStats(dfbg, dfwg, F)
86 | }
87 |
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/src/main/TTest/OneSampleTTest.scala:
--------------------------------------------------------------------------------
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.commons.math3.distribution.TDistribution
21 | import org.apache.spark.rdd.RDD
22 |
23 | /**
24 | * Created by yuhao on 12/31/15.
25 | */
26 | class OneSampleTTest extends TTestBasic {
27 | /**
28 | * Performs a two-sided t-test evaluating the null hypothesis that the mean of the population from
29 | * which sample is drawn equals mu
30 | * Returns true iff the null hypothesis can be
31 | * rejected with confidence 1 - alpha. To
32 | * perform a 1-sided test, use alpha * 2
33 |
34 | * To test the (2-sided) hypothesis sample mean = mu at
35 | * the 95% level, use tTest(mu, sample, 0.05)
36 | *
37 | * To test the (one-sided) hypothesis sample mean < mu
38 | * at the 99% level, first verify that the measured sample mean is less
39 | * than mu and then use
40 | * tTest(mu, sample, 0.02)
41 | *
42 | * @param mu constant value to compare sample mean against
43 | * @param sample array of sample data values
44 | * @param alpha significance level of the test
45 | * @return p-value
46 | */
47 | def tTest(mu: Double, sample: RDD[Double], alpha:Double): Boolean = {
48 | tTest(mu, sample) < alpha
49 | }
50 |
51 | /**
52 | * Returns the observed significance level, or
53 | * p-value, associated with a one-sample, two-tailed t-test
54 | * comparing the mean of the input array with the constant mu.
55 | *
56 | * The number returned is the smallest significance level
57 | * at which one can reject the null hypothesis that the mean equals
58 | * mu in favor of the two-sided alternative that the mean
59 | * is different from mu. For a one-sided test, divide the
60 | * returned value by 2.
61 | *
62 | * @param mu constant value to compare sample mean against
63 | * @param sample array of sample data values
64 | * @return p-value
65 | */
66 | def tTest(mu: Double, sample: RDD[Double]): Double = {
67 | val n = sample.count()
68 | val mean = sample.sum() / n
69 | val variance = sample.map(d => (d - mean) * (d - mean)).sum() / (n - 1)
70 | t(mean, mu, variance, n)
71 | }
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/TTest/PairTwoSampleTTest.scala:
--------------------------------------------------------------------------------
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 | package org.apache.spark.mllib.stat
18 |
19 |
20 | import org.apache.spark.rdd.RDD
21 |
22 | /**
23 | * Created by yuhao on 12/31/15.
24 | */
25 | class PairTwoSampleTTest extends TTestBasic {
26 | /**
27 | * Returns the observed significance level, or
28 | * p-value, associated with a paired, two-sample, two-tailed t-test
29 | * based on the data in the input arrays.
30 | *
31 | * The number returned is the smallest significance level
32 | * at which one can reject the null hypothesis that the mean of the paired
33 | * differences is 0 in favor of the two-sided alternative that the mean paired
34 | * difference is not equal to 0. For a one-sided test, divide the returned
35 | * value by 2.
36 | *
37 | * This test is equivalent to a one-sample t-test computed using
38 | * {@link #tTest(double, double[])} with mu = 0 and the sample
39 | * array consisting of the signed differences between corresponding elements of
40 | * sample1 and sample2.
41 | *
42 | * @param sample1 array of sample data values
43 | * @param sample2 array of sample data values
44 | * @return p-value for t-test
45 | */
46 | def tTest(sample1: RDD[Double], sample2: RDD[Double]): Double = {
47 | val n = sample1.count()
48 | require(n == sample2.count())
49 |
50 | val meanDifference = sample1.zip(sample2).map(p => p._1 - p._2).sum() / n
51 |
52 | val sum1 = sample1.zip(sample2).map(p => (p._1 - p._2 - meanDifference) * (p._1 - p._2 - meanDifference)).sum()
53 | val sum2 = sample1.zip(sample2).map(p => p._1 - p._2 - meanDifference).sum()
54 | val varianceDifference = (sum1 - sum2 * sum2 / n) / (n - 1)
55 |
56 | t(meanDifference, 0, varianceDifference, n)
57 | }
58 |
59 | /**
60 | * Performs a paired t-test evaluating the null hypothesis that the
61 | * mean of the paired differences between sample1 and
62 | * sample2 is 0 in favor of the two-sided alternative that the
63 | * mean paired difference is not equal to 0, with significance level
64 | * alpha.
65 | * Returns true iff the null hypothesis can be rejected with
66 | * confidence 1 - alpha. To perform a 1-sided test, use
67 | * alpha * 2
68 | *
69 | * @param sample1 array of sample data values
70 | * @param sample2 array of sample data values
71 | * @param alpha significance level of the test
72 | * @return true if the null hypothesis can be rejected with
73 | * confidence 1 - alpha
74 | */
75 | def tTest(sample1: RDD[Double], sample2: RDD[Double], alpha: Double): Boolean = {
76 | tTest(sample1, sample2) < alpha
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/TTest/TwoSampleIndependentTTest.scala:
--------------------------------------------------------------------------------
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 | package org.apache.spark.mllib.stat
18 |
19 | import org.apache.commons.math3.distribution.TDistribution
20 | import org.apache.commons.math3.util.FastMath
21 | import org.apache.spark.rdd.RDD
22 |
23 | /**
24 | * Created by yuhao on 12/31/15.
25 | */
26 | class TwoSampleIndependentTTest {
27 | /**
28 | * Performs a two-sided t-test evaluating the null hypothesis that sample1
29 | * and sample2 are drawn from populations with the same mean,
30 | * with significance level alpha. This test does not assume
31 | * that the subpopulation variances are equal.
32 | * Returns true iff the null hypothesis that the means are
33 | * equal can be rejected with confidence 1 - alpha. To
34 | * perform a 1-sided test, use alpha * 2
35 | * To test the (2-sided) hypothesis mean 1 = mean 2 at
36 | * the 95% level, use
37 | * tTest(sample1, sample2, 0.05).
38 | * To test the (one-sided) hypothesis mean 1 < mean 2,
39 | * at the 99% level, first verify that the measured mean of sample 1
40 | * is less than the mean of sample 2 and then use
41 | * tTest(sample1, sample2, 0.02)
42 | * @param sample1 array of sample data values
43 | * @param sample2 array of sample data values
44 | * @param alpha significance level of the test
45 | * @return true if the null hypothesis can be rejected with
46 | * confidence 1 - alpha
47 | */
48 | def tTest(sample1: RDD[Double], sample2: RDD[Double], alpha: Double): Boolean = {
49 | tTest(sample1, sample2) < alpha
50 | }
51 |
52 | /**
53 | * Returns the observed significance level, or
54 | * p-value, associated with a two-sample, two-tailed t-test
55 | * comparing the means of the input arrays.
56 | *
57 | * The number returned is the smallest significance level
58 | * at which one can reject the null hypothesis that the two means are
59 | * equal in favor of the two-sided alternative that they are different.
60 | * For a one-sided test, divide the returned value by 2.
61 | *
62 | * @param sample1 array of sample data values
63 | * @param sample2 array of sample data values
64 | * @return p-value for t-test
65 | */
66 | def tTest(sample1: RDD[Double], sample2: RDD[Double]): Double = {
67 | val n1 = sample1.count()
68 | val n2 = sample2.count()
69 | val m1 = sample1.sum() / n1
70 | val m2 = sample2.sum() / n2
71 | val v1 = sample1.map(d => (d - m1) * (d - m1)).sum() / (n1 - 1)
72 | val v2 = sample2.map(d => (d - m2) * (d - m2)).sum() / (n2 - 1)
73 | val t: Double = math.abs((m1 - m2) / FastMath.sqrt((v1 / n1) + (v2 / n2)))
74 | val degreesOfFreedom: Double = (((v1 / n1) + (v2 / n2)) * ((v1 / n1) + (v2 / n2))) /
75 | ((v1 * v1) / (n1 * n1 * (n1 - 1d)) + (v2 * v2) / (n2 * n2 * (n2 - 1d)))
76 |
77 | // pass a null rng to avoid unneeded overhead as we will not sample from this distribution
78 | val distribution: TDistribution = new TDistribution(null, degreesOfFreedom)
79 | 2.0 * distribution.cumulativeProbability(-t)
80 | }
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/MannWhitneyUTest/MannWhitneyUTest.scala:
--------------------------------------------------------------------------------
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 | package org.apache.spark.mllib.stat.test
18 |
19 | import breeze.linalg.max
20 | import org.apache.commons.math3.distribution.NormalDistribution
21 | import org.apache.commons.math3.exception.{ConvergenceException, MaxCountExceededException, NoDataException, NullArgumentException}
22 | import org.apache.commons.math3.stat.ranking.{NaNStrategy, NaturalRanking, TiesStrategy}
23 | import org.apache.commons.math3.util.FastMath
24 | import org.apache.spark.rdd.RDD
25 |
26 | /**
27 | * An implementation of the Mann-Whitney U test (also called Wilcoxon rank-sum test).
28 | *
29 | */
30 | object MannWhitneyUTest {
31 |
32 |
33 | /**
34 | * Computes the Mann-Whitney
36 | * U statistic comparing mean for two independent samples possibly of
37 | * different length.
38 | * This statistic can be used to perform a Mann-Whitney U test evaluating
39 | * the null hypothesis that the two independent samples has equal mean.
40 | *
41 | * @param x the first sample
42 | * @param y the second sample
43 | * @return Mann-Whitney U statistic (maximum of Ux and Uy)
44 | */
45 | def mannWhitneyU(x: RDD[Double], y: RDD[Double]): Double = {
46 | val zz = x.union(y)
47 | val originalPositions = zz.zipWithIndex().sortByKey().map(_._2) // original positions sorted
48 | val rank = originalPositions.zipWithIndex() // original position and rank
49 | val xLength = x.count()
50 | val yLength = y.count()
51 | val sumRankX = rank.filter( p => p._1 < xLength).map(_._2).sum() + xLength
52 |
53 | val U1: Double = sumRankX - (xLength * (xLength + 1)) / 2
54 | val U2: Double = xLength.toLong * yLength - U1
55 | return math.max(U1, U2)
56 | }
57 |
58 | /**
59 | * @param Umin smallest Mann-Whitney U value
60 | * @param n1 number of subjects in first sample
61 | * @param n2 number of subjects in second sample
62 | * @return two-sided asymptotic p-value
63 | */
64 | private def calculateAsymptoticPValue(Umin: Double, n1: Long, n2: Long): Double = {
65 | val n1n2prod: Long = n1.toLong * n2
66 | val EU: Double = n1n2prod / 2.0
67 | val VarU: Double = n1n2prod * (n1 + n2 + 1) / 12.0
68 | val z: Double = (Umin - EU) / FastMath.sqrt(VarU)
69 | val standardNormal: NormalDistribution = new NormalDistribution(null, 0, 1)
70 | return 2 * standardNormal.cumulativeProbability(z)
71 | }
72 |
73 | /**
74 | * Returns the asymptotic observed significance level, or
76 | * p-value, associated with a Mann-Whitney
78 | * U statistic comparing mean for two independent samples.
79 | *
80 | * @param x the first sample
81 | * @param y the second sample
82 | * @return asymptotic p-value
83 | */
84 |
85 | def mannWhitneyUTest(x: RDD[Double], y: RDD[Double]): Double = {
86 | val Umax: Double = mannWhitneyU(x, y)
87 | val Umin: Double = x.count() * y.count() - Umax
88 | return calculateAsymptoticPValue(Umin, x.count(), y.count())
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------