Created
June 2, 2017 08:53
-
-
Save lucananni93/d7992168bb50a6f97c5a6f7f0fe7c536 to your computer and use it in GitHub Desktop.
Calculate a Pearson Correlation Matrix
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 numpy as np | |
def pearson_correlation_matrix(m1, m2): | |
""" This function takes as input two numpy matrices m1, m2 | |
such that dim(m1) = (n,m) and dim(m2) = (r,m) and gives as a result | |
a numpy matrix such that dim(result) = (n,r) where each cell c_ij is | |
the result of the pearson correlation of the i-th row of m1 with the | |
r-th row of m2. | |
""" | |
# subtract the means | |
m1 = m1 - m1.mean(1)[:,None] | |
m2 = m2 - m2.mean(1)[:,None] | |
num = m1.dot(m2.T) | |
norms1 = np.linalg.norm(m1, axis=1) | |
norms2 = np.linalg.norm(m2, axis=1) | |
den = norms1[:, None] * norms2[None, :] | |
return num / den |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment