-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrack_pca.jl
291 lines (269 loc) · 9.35 KB
/
track_pca.jl
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
using ArgParse
using Arpack
using CSV, DataFrames
using LinearAlgebra, Random, Statistics
using LinearMaps
using PyPlot
include("EvolvingNetworks.jl")
include("Utils.jl")
"""
getRatio(Rs, skip)
Sort the eigenvalues in `Rs` in decreasing order of magnitude and return the
index of the minimizing ratio of successive eigenvalues, as well as the sorted
list of them.
"""
function getRatio(Rs, skip)
sort!(Rs, rev=true); ratios = Rs[2:end] ./ Rs[1:(end-1)]
sSize = first(filter(x -> x > skip, sortperm(ratios)))
return sSize, Rs
end
function genMatrix(n, d)
Q = Matrix(qr(randn(n, d)).Q); Σ = (2.0 .* randn(d)).^2;
return Q * Diagonal(Σ) * Q'
# A = randn(n, d); return (1 / sqrt(d)) * A * A'
end
#= genPert(n): create a low-rank matrix =#
function genPert(n)
v = randn(n) / sqrt(n); ϵi = (rand() <= 0.5) ? 1.0 : -1.0
return ϵi, v
end
#= genPertFull(n): create a matrix with i.i.d. entries N(0,1/n^2) =#
function genPertFull(n)
return (1 / n) * randn(n, n)
end
"""
update_eigvals(Anew, Vnew, Vold, λs, ϵ, nHi, use_bk, skip_last)
Compute `nHi` higher order eigenvalues of the deflated matrix
`(I - Vnew * Vnew') * Anew * (I - Vnew * Vnew')` starting from the previous
estimate `Vold`, up to target accuracy `ϵ`.
"""
function update_eigvals(Anew, Vnew, Vold, λs, ϵ, nHi, use_bk, skip_last)
n = size(Anew)[1]; ℓ = nHi + 5 # oversampling factor
if use_bk
Vold[:, 1:nHi], λHi, qIter = Utils.bkvals(Anew, nHi, Vold, ϵ,
getVecs=true, Vp=Vnew)
else
Vold[:, 1:nHi], λHi, qIter = Utils.sivals(Anew, ℓ, ϵ, nconv=nHi, V0=Vold,
getVecs=true, Vp=Vnew)
end
sSize, λAll = getRatio(abs.(vcat(λs, λHi)), skip_last)
return sSize, λAll, Vold, qIter
end
function track_full(n::Int, maxDim::Int, numEdits::Int;
γ::Float64, δ::Float64, ϵ::Float64,
use_bk::Bool, rnd_guess::Bool)
r = trunc(Int, sqrt(n))
A = (1 / (r * log(n))) * randn(n, r) * randn(r, n)
Amap = LinearMap(X -> A' * (A * X), n, n, issymmetric=true)
D, V, _ = eigs(Amap, nev=maxDim) # true evals, evecs
sSize, Dr = getRatio(D, 1); s1, sr, sr₊ = Dr[[1, sSize, sSize+1]];
@info("σs: $(sr), $(sr₊) - sSize: $(sSize)")
# rough eigval estimates
# (add +1 since we work with Anorm + 1.0I in the sequel)
# eigvec - keep correct dimension
V0 = V[:, 1:sSize]; nHi = 5; VHi = Utils._qrDirect(randn(n, nHi))
# steps elapsed, predicted (BK) and predicted (SI)
subSteps = []; subPredBK = []; subPredSI = []
# subspace distance (true and predicted)
subDistT = []; subDistP = []
# accumulated edits
for j = 1:numEdits
# update A
E = genPertFull(n)
(j % 10 == 0) && println("Running repeat $(j)...")
Anew = A + E;
# get new singular values
Amap = LinearMap(X -> Anew' * (Anew * X), n, n, issymmetric=true)
# norm of perturbation and perturbation of singular values
Enorm = (1.1 / sqrt(n))
σPert = (sqrt(s1) + sqrt(sr) + log(n)) / n
@info("sr: $(sr), sr₊: $(sr₊), σPert: $(σPert)")
if rnd_guess
V0 = Utils._qrDirect(randn(n, sSize))
nPredBK = nPredSI = n
Vnew, λs, endIt = begin
if use_bk
Utils.block_krylov(Amap, sSize, V0, ϵ, maxiter=nPredBK)
else
Utils.subspace_iteration(Amap, sSize, nPredSI, ϵ, V0=copy(V0))
end
end
Δ = opnorm(V0 * V0' - Vnew * Vnew')
# set correct predictions if using random guess
nPredBK, nPredSI = Utils.getIterBounds(Δ, ϵ, sr, sr₊, Enorm, γ, n)
else
# compute Δ bound
Δdenom = sr - sr₊ - 2 * σPert
Δ = ((2 / sqrt(n)) + (sqrt(sSize) / n)) / Δdenom
nPredBK, nPredSI = Utils.getIterBounds(Δ, ϵ, sr, sr₊, Enorm, γ, n)
Vnew, λs, endIt = begin
if use_bk
Utils.block_krylov(Amap, sSize, V0, ϵ, maxiter=nPredBK)
else
Utils.subspace_iteration(Amap, sSize, nPredSI, ϵ, V0=copy(V0))
end
end
end
Δex = first(svds(LinearMap(X -> V0 * (V0' * X) - Vnew * (Vnew' * X),
n, n, issymmetric=true), tol=1e-6)[1].S)
@info("Δs: $(Δ) vs. $(Δex)")
append!(subDistT, Δex)
append!(subDistP, Δ)
append!(subSteps, endIt)
append!(subPredBK, nPredBK)
append!(subPredSI, nPredSI)
V0 = copy(Vnew)
# update high-order eigenvalues for next iteration
sSize, λAll, VHi, qIter =
update_eigvals(Amap, Vnew, VHi, λs, ϵ, nHi, use_bk, 2)
s1, sr, sr₊ = λAll[[1, sSize, sSize+1]]
@info("Updated subspace size: $(sSize)")
# update A
A += E
end
# return all step statistics
return subSteps, subPredBK, subPredSI, subDistT, subDistP
end
function track_lowrank(n::Int, d::Int, maxDim::Int, numEdits::Int;
γ::Float64, δ::Float64, monitor_freq::Int,
ϵ::Float64, use_bk::Bool, rnd_guess::Bool)
Asym = genMatrix(n, d)
D, V, _ = eigs(Symmetric(Asym), nev=maxDim) # true evals, evecs
sSize, Dr = getRatio(D, 1); λ1, λr, λr₊ = Dr[[1, sSize, sSize+1]]
@info("λs: $(Dr) - sSize: $(sSize)")
# eigvec - keep correct dimension
V0 = V[:, 1:sSize]; nHi = 5; VHi = Utils._qrDirect(randn(n, nHi))
# steps elapsed, predicted (BK) and predicted (SI)
subSteps = []; subPredBK = []; subPredSI = []
# subspace distance (true and predicted)
subDistT = []; subDistP = []
# accumulated edits
for j = 1:numEdits
# update Asym
ϵi, v = genPert(n); BLAS.ger!(ϵi, v, v, Asym); E = ϵi * (v .* v')
(j % 10 == 0) && println("Running repeat $(j)...")
# norm of perturbation and perturbation of singular values
Enorm = (1.1 / sqrt(n))
Ptheo = sqrt(sSize / n) + sqrt(2 * log(n) / n)
if rnd_guess
V0 = Utils._qrDirect(randn(n, sSize))
nPredBK = nPredSI = n
Vnew, λs, endIt = begin
if use_bk
Utils.block_krylov(Asym, sSize, V0, ϵ, maxiter=nPredBK)
else
Utils.subspace_iteration(Asym, sSize, nPredSI, ϵ, V0=copy(V0))
end
end
Δ = opnorm(V0 * V0' - Vnew * Vnew')
# set correct predictions if using random guess
nPredBK, nPredSI = Utils.getIterBounds(Δ, ϵ, λr, λr₊, Enorm, γ, n,
r=sSize, δ=δ)
@info("Δ: $(Δ)")
else
# compute Δ bound
Δdenom = λr - λr₊
Δ = Ptheo / Δdenom
nPredBK, nPredSI = Utils.getIterBounds(Δ, ϵ, λr, λr₊, Enorm, γ, n,
r=sSize, δ=δ)
ρt = (λr - Enorm) / (λr₊ + Enorm)
@info("Ratio: $(ρt)")
Vnew, λs, endIt = begin
if use_bk
Utils.block_krylov(Asym, sSize, V0, ϵ, maxiter=nPredBK)
else
Utils.subspace_iteration(Asym, sSize, nPredSI, ϵ, V0=copy(V0))
end
end
end
Δex = first(svds(LinearMap(X -> V0 * (V0' * X) - Vnew * (Vnew' * X),
n, n, issymmetric=true), tol=1e-6)[1].S)
@info("Δ: $(Δ) - Δex: $(Δex)")
append!(subDistT, Δex)
append!(subDistP, Δ)
append!(subSteps, endIt)
append!(subPredBK, nPredBK)
append!(subPredSI, nPredSI)
V0 = copy(Vnew)
# update high-order eigenvalues for next iteration
sSize, λAll, VHi, qIter =
update_eigvals(Asym, Vnew, VHi, λs, ϵ, nHi, use_bk, 2)
λ1, λr, λr₊ = λAll[[1, sSize, sSize+1]]
@info("Updated subspace size: $(sSize)")
end
# return all step statistics
return subSteps, subPredBK, subPredSI, subDistT, subDistP
end
s = ArgParseSettings(description="""
Monitor the connected components of a real dataset by counting the
number of eigenvalues of the normalized laplacian which are close to 0.""")
@add_arg_table s begin
"--n"
help = "Number of data points"
arg_type = Int
default = 500
"--d"
help = "Dimension of data"
arg_type = Int
default = 100
"--max_dim"
help = "Maximum number of principal components"
arg_type = Int
default = 10
"--num_edits"
help = "The number of edits"
arg_type = Int
default = 500
"--monitor_freq"
help = "The monitoring frequency"
arg_type = Int
default = 10
"--seed"
help = "The random seed for the RNG"
arg_type = Int
default = 999
"--gamma"
help = "The eigenvalue decay parameter γ"
arg_type = Float64
default = 0.1
"--delta_fail"
help = "The probability of failure for randomized iteration"
arg_type = Float64
default = 1e-4
"--eps"
help = "The desired subspace distance to retain"
arg_type = Float64
default = 1e-3
"--random_guess"
help = "Set to report number of iterations predicted by random guess"
action = :store_true
"--use_bk"
help = "Use a block krylov method instead of randomized subspace iter."
action = :store_true
"--update_type"
help = "Choose the type of random updates - one of {full, low_rank}"
range_tester = (x -> lowercase(x) in ["full", "low_rank"])
end
parsed = parse_args(s); Random.seed!(parsed["seed"])
monitor_freq = parsed["monitor_freq"]
n, d, maxDim, nEdits = parsed["n"], parsed["d"], parsed["max_dim"], parsed["num_edits"]
γ, δ, ϵ = parsed["gamma"], parsed["delta_fail"], parsed["eps"]
use_bk, rnd_guess = parsed["use_bk"], parsed["random_guess"]
upd_type = lowercase(parsed["update_type"])
if upd_type == "low_rank"
sSteps, sPredBK, sPredSI, subT, subP = track_lowrank(
n, d, maxDim, nEdits, monitor_freq=monitor_freq, γ=γ,
δ=δ, ϵ=ϵ, use_bk=use_bk, rnd_guess=rnd_guess)
df = DataFrame(k=(1:length(sSteps)) .* monitor_freq,
sSteps=sSteps, sPredBK=sPredBK, sPredSI=sPredSI,
subT=subT, subP=subP)
CSV.write("track_pca_$(n)x$(d)_freq-$(monitor_freq)_bk_$(use_bk)_rnd_$(rnd_guess).csv", df)
else
sSteps, sPredBK, sPredSI, subT, subP = track_full(
n, maxDim, nEdits, γ=γ, δ=δ, ϵ=ϵ, use_bk=use_bk,
rnd_guess=rnd_guess)
df = DataFrame(k=(1:length(sSteps)) .* monitor_freq,
sSteps=sSteps, sPredBK=sPredBK,
sPredSI=sPredSI, subT=subT, subP=subP)
CSV.write("track_pca_full_$(n)_freq-$(monitor_freq)_bk_$(use_bk)_rnd_$(rnd_guess).csv", df)
end