Skip to content

Instantly share code, notes, and snippets.

@skuschel
Last active March 4, 2019 21:26
Show Gist options
  • Save skuschel/9cd745c4b47ad579481b1ade6115250a to your computer and use it in GitHub Desktop.
Save skuschel/9cd745c4b47ad579481b1ade6115250a to your computer and use it in GitHub Desktop.
Partial Covariance
def pcov(data, I=None, corrcoef=False, rowvar=True):
'''
Partial covariance
Stephan Kuschel, 2019
https://gist.github.com/skuschel/9cd745c4b47ad579481b1ade6115250a
'''
import numpy as np
if I is None:
I = np.mean(data, axis=0 if rowvar else 1)
I = np.atleast_2d(I)
c = np.cov(data, I, rowvar=rowvar)
cov = c[:-1, :-1]
ret = cov - np.outer(c[-1, :-1], c[:-1, -1]) / c[-1,-1]
if corrcoef:
s = np.sqrt(np.diag(ret))
ret /= np.outer(s,s)
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment