Skip to content

Instantly share code, notes, and snippets.

@lucananni93
Created June 2, 2017 08:53
Show Gist options
  • Save lucananni93/d7992168bb50a6f97c5a6f7f0fe7c536 to your computer and use it in GitHub Desktop.
Save lucananni93/d7992168bb50a6f97c5a6f7f0fe7c536 to your computer and use it in GitHub Desktop.
Calculate a Pearson Correlation Matrix
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