Skip to content

Commit 9646018

Browse files
brkyvzrxin
authored andcommitted
[SPARK-7241] Pearson correlation for DataFrames
submitting this PR from a phone, excuse the brevity. adds Pearson correlation to Dataframes, reusing the covariance calculation code cc mengxr rxin Author: Burak Yavuz <[email protected]> Closes apache#5858 from brkyvz/df-corr and squashes the following commits: 285b838 [Burak Yavuz] addressed comments v2.0 d10babb [Burak Yavuz] addressed comments v0.2 4b74b24 [Burak Yavuz] Merge branch 'master' of github.com:apache/spark into df-corr 4fe693b [Burak Yavuz] addressed comments v0.1 a682d06 [Burak Yavuz] ready for PR
1 parent 1ffa8cb commit 9646018

File tree

6 files changed

+130
-26
lines changed

6 files changed

+130
-26
lines changed

python/pyspark/sql/dataframe.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -875,6 +875,27 @@ def fillna(self, value, subset=None):
875875

876876
return DataFrame(self._jdf.na().fill(value, self._jseq(subset)), self.sql_ctx)
877877

878+
def corr(self, col1, col2, method=None):
879+
"""
880+
Calculates the correlation of two columns of a DataFrame as a double value. Currently only
881+
supports the Pearson Correlation Coefficient.
882+
:func:`DataFrame.corr` and :func:`DataFrameStatFunctions.corr` are aliases.
883+
884+
:param col1: The name of the first column
885+
:param col2: The name of the second column
886+
:param method: The correlation method. Currently only supports "pearson"
887+
"""
888+
if not isinstance(col1, str):
889+
raise ValueError("col1 should be a string.")
890+
if not isinstance(col2, str):
891+
raise ValueError("col2 should be a string.")
892+
if not method:
893+
method = "pearson"
894+
if not method == "pearson":
895+
raise ValueError("Currently only the calculation of the Pearson Correlation " +
896+
"coefficient is supported.")
897+
return self._jdf.stat().corr(col1, col2, method)
898+
878899
def cov(self, col1, col2):
879900
"""
880901
Calculate the sample covariance for the given columns, specified by their names, as a
@@ -1359,6 +1380,11 @@ class DataFrameStatFunctions(object):
13591380
def __init__(self, df):
13601381
self.df = df
13611382

1383+
def corr(self, col1, col2, method=None):
1384+
return self.df.corr(col1, col2, method)
1385+
1386+
corr.__doc__ = DataFrame.corr.__doc__
1387+
13621388
def cov(self, col1, col2):
13631389
return self.df.cov(col1, col2)
13641390

python/pyspark/sql/tests.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,12 @@ def test_aggregator(self):
394394
self.assertTrue(95 < g.agg(functions.approxCountDistinct(df.key)).first()[0])
395395
self.assertEqual(100, g.agg(functions.countDistinct(df.value)).first()[0])
396396

397+
def test_corr(self):
398+
import math
399+
df = self.sc.parallelize([Row(a=i, b=math.sqrt(i)) for i in range(10)]).toDF()
400+
corr = df.stat.corr("a", "b")
401+
self.assertTrue(abs(corr - 0.95734012) < 1e-6)
402+
397403
def test_cov(self):
398404
df = self.sc.parallelize([Row(a=i, b=2 * i) for i in range(10)]).toDF()
399405
cov = df.stat.cov("a", "b")

sql/core/src/main/scala/org/apache/spark/sql/DataFrameStatFunctions.scala

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,32 @@ import org.apache.spark.sql.execution.stat._
2727
@Experimental
2828
final class DataFrameStatFunctions private[sql](df: DataFrame) {
2929

30+
/**
31+
* Calculates the correlation of two columns of a DataFrame. Currently only supports the Pearson
32+
* Correlation Coefficient. For Spearman Correlation, consider using RDD methods found in
33+
* MLlib's Statistics.
34+
*
35+
* @param col1 the name of the column
36+
* @param col2 the name of the column to calculate the correlation against
37+
* @return The Pearson Correlation Coefficient as a Double.
38+
*/
39+
def corr(col1: String, col2: String, method: String): Double = {
40+
require(method == "pearson", "Currently only the calculation of the Pearson Correlation " +
41+
"coefficient is supported.")
42+
StatFunctions.pearsonCorrelation(df, Seq(col1, col2))
43+
}
44+
45+
/**
46+
* Calculates the Pearson Correlation Coefficient of two columns of a DataFrame.
47+
*
48+
* @param col1 the name of the column
49+
* @param col2 the name of the column to calculate the correlation against
50+
* @return The Pearson Correlation Coefficient as a Double.
51+
*/
52+
def corr(col1: String, col2: String): Double = {
53+
corr(col1, col2, "pearson")
54+
}
55+
3056
/**
3157
* Finding frequent items for columns, possibly with false positives. Using the
3258
* frequent element count algorithm described in

sql/core/src/main/scala/org/apache/spark/sql/execution/stat/StatFunctions.scala

Lines changed: 38 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -23,43 +23,51 @@ import org.apache.spark.sql.types.{DoubleType, NumericType}
2323

2424
private[sql] object StatFunctions {
2525

26+
/** Calculate the Pearson Correlation Coefficient for the given columns */
27+
private[sql] def pearsonCorrelation(df: DataFrame, cols: Seq[String]): Double = {
28+
val counts = collectStatisticalData(df, cols)
29+
counts.Ck / math.sqrt(counts.MkX * counts.MkY)
30+
}
31+
2632
/** Helper class to simplify tracking and merging counts. */
2733
private class CovarianceCounter extends Serializable {
28-
var xAvg = 0.0
29-
var yAvg = 0.0
30-
var Ck = 0.0
31-
var count = 0L
34+
var xAvg = 0.0 // the mean of all examples seen so far in col1
35+
var yAvg = 0.0 // the mean of all examples seen so far in col2
36+
var Ck = 0.0 // the co-moment after k examples
37+
var MkX = 0.0 // sum of squares of differences from the (current) mean for col1
38+
var MkY = 0.0 // sum of squares of differences from the (current) mean for col1
39+
var count = 0L // count of observed examples
3240
// add an example to the calculation
3341
def add(x: Double, y: Double): this.type = {
34-
val oldX = xAvg
42+
val deltaX = x - xAvg
43+
val deltaY = y - yAvg
3544
count += 1
36-
xAvg += (x - xAvg) / count
37-
yAvg += (y - yAvg) / count
38-
Ck += (y - yAvg) * (x - oldX)
45+
xAvg += deltaX / count
46+
yAvg += deltaY / count
47+
Ck += deltaX * (y - yAvg)
48+
MkX += deltaX * (x - xAvg)
49+
MkY += deltaY * (y - yAvg)
3950
this
4051
}
4152
// merge counters from other partitions. Formula can be found at:
42-
// http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Covariance
53+
// http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
4354
def merge(other: CovarianceCounter): this.type = {
4455
val totalCount = count + other.count
45-
Ck += other.Ck +
46-
(xAvg - other.xAvg) * (yAvg - other.yAvg) * count / totalCount * other.count
56+
val deltaX = xAvg - other.xAvg
57+
val deltaY = yAvg - other.yAvg
58+
Ck += other.Ck + deltaX * deltaY * count / totalCount * other.count
4759
xAvg = (xAvg * count + other.xAvg * other.count) / totalCount
4860
yAvg = (yAvg * count + other.yAvg * other.count) / totalCount
61+
MkX += other.MkX + deltaX * deltaX * count / totalCount * other.count
62+
MkY += other.MkY + deltaY * deltaY * count / totalCount * other.count
4963
count = totalCount
5064
this
5165
}
5266
// return the sample covariance for the observed examples
5367
def cov: Double = Ck / (count - 1)
5468
}
5569

56-
/**
57-
* Calculate the covariance of two numerical columns of a DataFrame.
58-
* @param df The DataFrame
59-
* @param cols the column names
60-
* @return the covariance of the two columns.
61-
*/
62-
private[sql] def calculateCov(df: DataFrame, cols: Seq[String]): Double = {
70+
private def collectStatisticalData(df: DataFrame, cols: Seq[String]): CovarianceCounter = {
6371
require(cols.length == 2, "Currently cov supports calculating the covariance " +
6472
"between two columns.")
6573
cols.map(name => (name, df.schema.fields.find(_.name == name))).foreach { case (name, data) =>
@@ -68,13 +76,23 @@ private[sql] object StatFunctions {
6876
s"with dataType ${data.get.dataType} not supported.")
6977
}
7078
val columns = cols.map(n => Column(Cast(Column(n).expr, DoubleType)))
71-
val counts = df.select(columns:_*).rdd.aggregate(new CovarianceCounter)(
79+
df.select(columns: _*).rdd.aggregate(new CovarianceCounter)(
7280
seqOp = (counter, row) => {
7381
counter.add(row.getDouble(0), row.getDouble(1))
7482
},
7583
combOp = (baseCounter, other) => {
7684
baseCounter.merge(other)
77-
})
85+
})
86+
}
87+
88+
/**
89+
* Calculate the covariance of two numerical columns of a DataFrame.
90+
* @param df The DataFrame
91+
* @param cols the column names
92+
* @return the covariance of the two columns.
93+
*/
94+
private[sql] def calculateCov(df: DataFrame, cols: Seq[String]): Double = {
95+
val counts = collectStatisticalData(df, cols)
7896
counts.cov
7997
}
8098
}

sql/core/src/test/java/test/org/apache/spark/sql/JavaDataFrameSuite.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,13 @@ public void testFrequentItems() {
187187
Assert.assertTrue(results.collect()[0].getSeq(0).contains(1));
188188
}
189189

190+
@Test
191+
public void testCorrelation() {
192+
DataFrame df = context.table("testData2");
193+
Double pearsonCorr = df.stat().corr("a", "b", "pearson");
194+
Assert.assertTrue(Math.abs(pearsonCorr) < 1e-6);
195+
}
196+
190197
@Test
191198
public void testCovariance() {
192199
DataFrame df = context.table("testData2");

sql/core/src/test/scala/org/apache/spark/sql/DataFrameStatSuite.scala

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,10 @@ class DataFrameStatSuite extends FunSuite {
3030
def toLetter(i: Int): String = (i + 97).toChar.toString
3131

3232
test("Frequent Items") {
33-
val rows = Array.tabulate(1000) { i =>
33+
val rows = Seq.tabulate(1000) { i =>
3434
if (i % 3 == 0) (1, toLetter(1), -1.0) else (i, toLetter(i), i * -1.0)
3535
}
36-
val df = sqlCtx.sparkContext.parallelize(rows).toDF("numbers", "letters", "negDoubles")
36+
val df = rows.toDF("numbers", "letters", "negDoubles")
3737

3838
val results = df.stat.freqItems(Array("numbers", "letters"), 0.1)
3939
val items = results.collect().head
@@ -43,19 +43,40 @@ class DataFrameStatSuite extends FunSuite {
4343
val singleColResults = df.stat.freqItems(Array("negDoubles"), 0.1)
4444
val items2 = singleColResults.collect().head
4545
items2.getSeq[Double](0) should contain (-1.0)
46+
}
4647

48+
test("pearson correlation") {
49+
val df = Seq.tabulate(10)(i => (i, 2 * i, i * -1.0)).toDF("a", "b", "c")
50+
val corr1 = df.stat.corr("a", "b", "pearson")
51+
assert(math.abs(corr1 - 1.0) < 1e-12)
52+
val corr2 = df.stat.corr("a", "c", "pearson")
53+
assert(math.abs(corr2 + 1.0) < 1e-12)
54+
// non-trivial example. To reproduce in python, use:
55+
// >>> from scipy.stats import pearsonr
56+
// >>> import numpy as np
57+
// >>> a = np.array(range(20))
58+
// >>> b = np.array([x * x - 2 * x + 3.5 for x in range(20)])
59+
// >>> pearsonr(a, b)
60+
// (0.95723391394758572, 3.8902121417802199e-11)
61+
// In R, use:
62+
// > a <- 0:19
63+
// > b <- mapply(function(x) x * x - 2 * x + 3.5, a)
64+
// > cor(a, b)
65+
// [1] 0.957233913947585835
66+
val df2 = Seq.tabulate(20)(x => (x, x * x - 2 * x + 3.5)).toDF("a", "b")
67+
val corr3 = df2.stat.corr("a", "b", "pearson")
68+
assert(math.abs(corr3 - 0.95723391394758572) < 1e-12)
4769
}
4870

4971
test("covariance") {
50-
val rows = Array.tabulate(10)(i => (i, 2.0 * i, toLetter(i)))
51-
val df = sqlCtx.sparkContext.parallelize(rows).toDF("singles", "doubles", "letters")
72+
val df = Seq.tabulate(10)(i => (i, 2.0 * i, toLetter(i))).toDF("singles", "doubles", "letters")
5273

5374
val results = df.stat.cov("singles", "doubles")
54-
assert(math.abs(results - 55.0 / 3) < 1e-6)
75+
assert(math.abs(results - 55.0 / 3) < 1e-12)
5576
intercept[IllegalArgumentException] {
5677
df.stat.cov("singles", "letters") // doesn't accept non-numerical dataTypes
5778
}
5879
val decimalRes = decimalData.stat.cov("a", "b")
59-
assert(math.abs(decimalRes) < 1e-6)
80+
assert(math.abs(decimalRes) < 1e-12)
6081
}
6182
}

0 commit comments

Comments
 (0)