Skip to content

Instantly share code, notes, and snippets.

@wizzeh
Created October 13, 2016 19:15
Show Gist options
  • Save wizzeh/68bdf956e713c18fcf33de167967f58d to your computer and use it in GitHub Desktop.
Save wizzeh/68bdf956e713c18fcf33de167967f58d to your computer and use it in GitHub Desktop.
Partial Correlation in Python
"""
Partial Correlation in Python
Based on Fabian Pedregosa-Izquierdo's implementation at:
https://gist.github.com/fabianp/9396204419c7b638d38f
This version of the algorithm calculates the partial correlation coefficient controlling for Z.
I use row vectors here, for whatever reason.
"""
import numpy as np
def partial_corr(X,Z):
"""
Returns the partial correlation coefficients between elements of X controlling for the elements in Z.
"""
X = np.asarray(X).transpose()
Z = np.asarray(Z).transpose()
n = X.shape[1]
partial_corr = np.zeros((n,n), dtype=np.float)
for i in range(n):
partial_corr[i,i] = 1
for j in range(i+1,n):
beta_i = np.linalg.lstsq(Z, X[:,j])[0]
beta_j = np.linalg.lstsq(Z, X[:,i])[0]
res_j = X[:,j] - Z.dot(beta_i)
res_i = X[:,i] - Z.dot(beta_j)
corr = np.corrcoef(res_i,res_j)
partial_corr[i,j] = corr.item(0,1)
partial_corr[j,i] = corr.item(0,1)
return partial_corr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment