Skip to content

Instantly share code, notes, and snippets.

@twolodzko
Last active July 12, 2019 16:35
Show Gist options
  • Select an option

  • Save twolodzko/feb1786e3f19dc7a652cd0bbbf0f60fa to your computer and use it in GitHub Desktop.

Select an option

Save twolodzko/feb1786e3f19dc7a652cd0bbbf0f60fa to your computer and use it in GitHub Desktop.
Partial correlation
import numpy as np
def pcor(X, rowvar=False):
"""
Partial correlation
Implemented as in pcor::pcor function in R.
Kim, S. (2015) ppcor: An R Package for a Fast Calculation to Semi-partial Correlation Coefficients.
Communications for Statistical Applications and Methods, 22(6), 665-674.
"""
V = np.linalg.inv(np.cov(X, rowvar=rowvar))
# cov2cor
Is = np.diag(np.sqrt(1/np.diag(V)))
rho = -(Is @ V @ Is)
np.fill_diagonal(rho, 1)
return rho
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment