Skip to content

Instantly share code, notes, and snippets.

@rpryzant
Last active March 18, 2020 20:16
Show Gist options
  • Save rpryzant/2e0d5fec5915ba0e27edf6b644e291a0 to your computer and use it in GitHub Desktop.
Save rpryzant/2e0d5fec5915ba0e27edf6b644e291a0 to your computer and use it in GitHub Desktop.
Util functions for computing and removing principal components
from sklearn.decomposition import TruncatedSVD
def compute_pc(X,npc=1):
"""
Compute the principal components.
X: numpy array [data, features]
npc: num principal components
"""
svd = TruncatedSVD(n_components=npc, n_iter=7, random_state=0)
svd.fit(X)
return svd.components_
def remove_pc(X, npc=1, pc=None):
"""
Remove the projection on the principal components
X: numpy array [data, features]
npc: num principal components
pc (optional): direction to project and flatten on
returns: out[i, :] is the data point after removing its projection
"""
if pc is None:
pc = compute_pc(X, npc)
if npc==1:
out = X - X.dot(pc.transpose()) * pc
else:
out = X - X.dot(pc.transpose()).dot(pc)
return out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment