forked from weilinear/PyRPCA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
robustpca.py
290 lines (247 loc) · 7.76 KB
/
robustpca.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
from sklearn.base import TransformerMixin, BaseEstimator
import numpy as np
import scipy.sparse as sp
try:
from pypropack import svdp
raise ValueError
svd = lambda X, k: svdp(X, k, 'L', kmax=max(100, 10 * k))
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
except:
from scipy.linalg import svd as svd_
def svd(X, k=-1):
U, S, V = svd_(X, full_matrices=False)
if k < 0:
return U, S, V
else:
return U[:, :k], S[:k], V[:k, :]
# The problem solved is
# min : tau * (|A|_* + \lmbda |E|_1) + .5 * |(A,E)|_F^2
# subject to: A + E = D
def _monitor(A, E, D, lmbda=0.1):
diags = svd(A, min(A.shape))[1]
print "|A|_*", np.abs(diags).sum()
print "|A|_0", (np.abs(diags) > 1e-6).sum()
print "|E|_1", np.abs(D - A).sum()
print "|D-A-E|_F", _fro(D - A - E)
return np.abs(diags).sum() + lmbda * np.abs(D - A).sum()
def _pos(A):
return A * (A > 0)
def _fro(A):
return np.sqrt((A * A).sum())
def singular_value_thresholding(D, maxiter=25000, lmbda=1.0, tau=1e4, delta=.9, verbose=2):
"""
Singular Value Thresholding
"""
# initialization
_matshape = D.shape
primal_tol = 1e-5
Y = np.zeros(shape=_matshape)
A = np.zeros(shape=_matshape)
E = np.zeros(shape=_matshape)
rankA = 0
obj = []
for iter in range(maxiter):
U, S, V = svd(Y, rankA+1)
A = np.dot(np.dot(U, np.diag(_pos(S - tau))), V)
E = np.sign(Y) * _pos(np.abs(Y) - lmbda * tau)
M = D - A - E
rankA = (S > tau).sum()
Y = Y + delta * M
if verbose >= 2:
obj.append(_monitor(A, E, D))
if _fro(D-A-E)/_fro(D) < primal_tol:
if verbose >= 2:
print "Converged at iter %d"%iter
break
if verbose >= 2:
return A, E, obj
else:
return A, E
def accelerate_proximal_gradient(D, lmbda, maxiter=25000, tol=1e-7,
continuation=True,
eta=.9, mu=1e-3, verbose=2):
"""
Accelerated Proximal Gradient (Partial SVD Version)
"""
obj = []
m, n = D.shape
t_k = 1.
tk_old = 1.
tau_0 = 2.
A_old = np.zeros(D.shape)
E_old = np.zeros(D.shape)
A = np.zeros(D.shape)
E = np.zeros(D.shape)
# This comes from the code
if continuation:
mu_0 = svd(D, 1)[1]
mu_k = mu_0;
mu_bar = 1e-9 * mu_0
else:
mu_k = mu;
tau_k = tau_0;
converged = False;
sv = 5.;
for iter in range(maxiter):
YA = A + ((tk_old - 1)/t_k)*(A-A_old);
YE = E + ((tk_old - 1)/t_k)*(E-E_old);
A_old = YA - (1/tau_k)*(YA+YE-D);
E_old = YE - (1/tau_k)*(YA+YE-D);
U, S, V = svd(A_old);
svp = (S > mu_k/tau_k).sum();
# this line to update the number of singular values comes from the code
if svp < sv:
sv = min(svp + 1, n);
else:
sv = min(svp + round(0.05*n), n);
A_new = np.dot(
np.dot(U[:, :svp], np.diag(S[:svp] - mu_k/tau_k)), V[:svp, :])
E_new = np.sign(E_old) * _pos(np.abs(E_old) - lmbda * mu_k / tau_k);
t_kp1 = 0.5*(1+np.sqrt(1+4*t_k*t_k));
A_old = A_new + E_new - YA - YE;
YA = tau_k*(YA-A_new) + A_old;
YE = tau_k*(YE-E_new) + A_old;
s1 = np.sqrt((YA**2).sum()+(YE**2).sum())
s2 = np.sqrt((A_new**2).sum()+(E_new**2).sum());
if s1 / (tau_k*max(1, s2)) <= tol and iter > 10:
break;
if continuation:
mu_k = max(0.9*mu_k, mu_bar);
tk_old = t_k;
t_k = t_kp1;
A_old = A;
E_old = E;
A = A_new;
E = E_new;
if verbose >= 2:
obj.append(_monitor(A, E, D))
if (not converged) and iter >= maxiter:
print 'Maximum iterations reached'
converged = True;
if verbose >= 2:
return A, E, obj
else:
return A, E
def dual_method():
"""
Dual Method
"""
pass
def augmented_largrange_multiplier(D, lmbda, tol=1e-7, maxiter=25000, verbose=2, inexact=True):
"""
Augmented Lagrange Multiplier
"""
obj = []
Y = np.sign(D)
norm_two = svd(Y, 1)[1]
norm_inf = np.abs(Y).max() / lmbda
dual_norm = np.max([norm_two, norm_inf])
Y = Y / dual_norm
A = np.zeros(Y.shape)
E = np.zeros(Y.shape)
dnorm = _fro(D)
tol_primal = 1e-6 * dnorm
total_svd = 0
mu = .5/norm_two
rho = 6
sv = 5
svp = sv
n = Y.shape[0]
for iter in range(maxiter):
primal_converged = False
sv = sv + np.round(n * 0.1)
primal_iter = 0
while not primal_converged:
Eraw = D - A + (1/mu) * Y
Eupdate = np.maximum(
Eraw - lmbda/mu, 0) + np.minimum(Eraw + lmbda / mu, 0)
U, S, V = svd(D - Eupdate + (1 / mu) * Y, sv)
svp = (S > 1/mu).sum()
if svp < sv:
sv = np.min([svp + 1, n])
else:
sv = np.min([svp + round(.05 * n), n])
Aupdate = np.dot(
np.dot(U[:, :svp], np.diag(S[:svp] - 1/mu)), V[:svp, :])
if primal_iter % 10 == 0 and verbose >= 2:
print _fro(A - Aupdate)
if (_fro(A - Aupdate) < tol_primal and _fro(E - Eupdate) < tol_primal) or (inexact and primal_iter > 5):
primal_converged = True
if verbose >= 2:
print "Primal Converged at Iter %d"%(primal_iter)
A = Aupdate
E = Eupdate
primal_iter = primal_iter + 1
total_svd = total_svd + 1
Z = D - A - E
Y = Y + mu * Z
mu = rho * mu
if np.sqrt((Z**2).sum()) / dnorm < tol:
if verbose >= 2:
print "Converged at Iter %d" % (iter)
break
else:
if verbose >= 2:
obj.append(_monitor(A, E, D))
if verbose >= 2:
return A, E, obj
else:
return A, E
def alternating_direction_method_of_multipliers(D, lmbda, rho=1., maxiter=25000, verbose=2, tol=1e-2):
def soft_thresh(X, sigma):
return np.maximum(X - sigma, 0) - np.maximum(-X - sigma, 0);
obj = []
m, n = D.shape
A = D;
E = D - A;
W = np.ones(D.shape)/rho;
rhoupdate = rho;
for k in range(maxiter):
U, S, V = svd(D-E-W);
Aupdate = np.dot(np.dot(U, np.diag(soft_thresh(S, 1/rho))), V);
Eupdate = soft_thresh(D-Aupdate-W, lmbda/rho);
Wupdate = W + (Aupdate + Eupdate - D);
primal_resid = _fro(Aupdate + Eupdate - D)
dual_resid = rho*_fro(Eupdate - E)
# this is from the stanford slide
if primal_resid > 10*dual_resid:
rhoupdate = 2*rho;
Wupdate = Wupdate/2;
elif dual_resid > 10*primal_resid:
rhoupdate = rho/2;
Wupdate = 2*Wupdate;
else:
rhoupdate = rho
A = Aupdate;
E = Eupdate;
W = Wupdate;
rho = rhoupdate;
if primal_resid <= tol and dual_resid <= tol:
if verbose >= 2:
print 'Converged to tol=%e in %d iterations\n'%(tol, k)
break;
if verbose >= 2:
obj.append(_monitor(A, E, D))
if verbose >= 2:
return A, E, obj
else:
return A, E
method = {"SVT": singular_value_thresholding,
"ALM": augmented_largrange_multiplier,
"ADMM": alternating_direction_method_of_multipliers,
"APG": accelerate_proximal_gradient}
class RobustPCA(BaseEstimator, TransformerMixin):
"""
Robust PCA
"""
def __init__(self, alpha=.1, copy=True, method='svt'):
"""
"""
pass
def tranform():
"""
Tranform
"""
pass