Skip to content

Instantly share code, notes, and snippets.

@anibalsolon
Last active May 7, 2019 21:27
Show Gist options
  • Save anibalsolon/cb9ca69c15d697932f7700815962e087 to your computer and use it in GitHub Desktop.
Save anibalsolon/cb9ca69c15d697932f7700815962e087 to your computer and use it in GitHub Desktop.
anicor
def anicor(matrix1, matrix2):
d1 = matrix1.shape[-1]
d2 = matrix2.shape[-1]
def zscore(data, axis):
data -= data.mean(axis=axis,keepdims=True)
data /= data.std(axis=axis,keepdims=True)
return np.nan_to_num(data, copy=False)
assert d1 == d2
assert matrix1.ndim <= 2
assert matrix2.ndim <= 2
matrix1 = zscore(matrix1.astype(float), matrix1.ndim - 1) / np.sqrt(d1)
matrix2 = zscore(matrix2.astype(float), matrix2.ndim - 1) / np.sqrt(d2)
if matrix1.ndim >= matrix2.ndim:
r = np.dot(matrix1, matrix2.T)
else:
r = np.dot(matrix2, matrix1.T)
r = np.clip(r, -1.0, 1.0)
df = d1 - 2
if abs(r) == 1.0:
p = 0.0
else:
from scipy.special import betainc
x = df / (df + (r * r * (df / ((1-.0 - r) * (1.0 + r)))))
p = betainc(0.5 * df, 0.5, np.where(x < 1.0, x, 1.0))
return r, p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment