Skip to content

Instantly share code, notes, and snippets.

@vighneshbirodkar
Last active May 19, 2016 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vighneshbirodkar/253f2da96413c657491c6a169276d06e to your computer and use it in GitHub Desktop.
Save vighneshbirodkar/253f2da96413c657491c6a169276d06e to your computer and use it in GitHub Desktop.
import numpy as np
from sklearn.decomposition.rpca import rpca
from numpy.linalg import matrix_rank
def gen_synthetic(n, sparseness, rank):
r = rank # Rank
X = np.random.normal(0, 1/float(n), size=(n, r))
Y = np.random.normal(0, 1/float(n), size=(n, r))
L = np.dot(X, Y.T)
p = sparseness/2
S = np.random.choice([0, 1, -1], size=(n, n), p=[1 - 2*p, p, p])
return L, S
L, S = gen_synthetic(500, 0.05, 25)
X = L + S
L, S, (U, s, Vt) = rpca(X, verbose=True)
r = np.count_nonzero(s)
components = Vt[:r]
l = np.dot(X, components.T)
L_ = np.dot(l, components)
print('Components rank = %d' % matrix_rank(components))
print('L_ rank = %d' % matrix_rank(L_))
assert np.allclose(L, np.dot(np.dot(U, np.diag(s)), Vt))
assert np.allclose(L, L_)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment