Last active
October 4, 2016 14:25
-
-
Save kaja47/6722683 to your computer and use it in GitHub Desktop.
Pearson correlation coefficient in scalanlp/breeze
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import breeze.linalg._ | |
def corr(a: DenseVector[Double], b: DenseVector[Double]): Double = { | |
if (a.length != b.length) | |
sys.error("you fucked up") | |
val n = a.length | |
val (amean, avar) = meanAndVariance(a) | |
val (bmean, bvar) = meanAndVariance(b) | |
val astddev = math.sqrt(avar) | |
val bstddev = math.sqrt(bvar) | |
1.0 / (n - 1.0) * sum( ((a - amean) / astddev) :* ((b - bmean) / bstddev) ) | |
} |
is it worked? I could not complie on scala shell ..
so, I modified it
import breeze.linalg._
def corr(a: DenseVector[Double], b: DenseVector[Double]): Double = {
if (a.length != b.length)
sys.error("you fucked up")
val n = a.length
val ameanavar = meanAndVariance(a)
val amean = ameanavar.mean
val avar = ameanavar.variance
val bmeanbvar = meanAndVariance(b)
val bmean = bmeanbvar.mean
val bvar = bmeanbvar.variance
val astddev = math.sqrt(avar)
val bstddev = math.sqrt(bvar)
1.0 / (n - 1.0) * sum( ((a - amean) / astddev) :* ((b - bmean) / bstddev) )
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This method is really inefficient if used on SparseVectors. I have created a fork, with a version that runs a 1000 times faster on huge, sparse vectors.
Quick benchmark for two vectors with approximately 1000 non-zero elements.