Skip to content

Instantly share code, notes, and snippets.

@rpryzant
Last active Mar 18, 2020
Embed
What would you like to do?
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