/
ppca.jl
339 lines (271 loc) · 9.32 KB
/
ppca.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# Probabilistic Principal Component Analysis
"""
This type contains probabilistic PCA model parameters.
"""
struct PPCA{T<:Real} <: LatentVariableDimensionalityReduction
mean::Vector{T} # sample mean: of length d (mean can be empty, which indicates zero mean)
W::Matrix{T} # weight matrix: of size d x p
σ²::T # residual variance
end
## properties
"""
size(M::PPCA)
Returns a tuple with values of the input dimension ``d``, *i.e* the dimension of
the observation space, and the output dimension ``p``, *i.e* the dimension of
the principal subspace.
"""
size(M::PPCA) = size(M.W)
"""
mean(M::PPCA)
Get the mean vector (of length ``d``).
"""
mean(M::PPCA) = fullmean(size(M)[1], M.mean)
"""
projection(M::PPCA)
Returns the projection matrix (of size ``(d, p)``). Each column of the projection
matrix corresponds to a principal component.
The principal components are arranged in descending order of the corresponding variances.
"""
projection(M::PPCA) = svd(M.W).U # recover principle components from the weight matrix
"""
var(M::PPCA)
Returns the total residual variance of the model `M`.
"""
var(M::PPCA) = M.σ²
"""
loadings(M::PPCA)
Returns the factor loadings matrix (of size ``(d, p)``) of the model `M`.
"""
loadings(M::PPCA) = M.W
"""
cov(M::PPCA)
Returns the covariance of the model `M`.
"""
cov(M::PPCA) = M.W'*M.W + M.σ²*I
## use
"""
predict(M::PPCA, x)
Transform observations `x` into latent variables. Here, `x` can be either a vector
of length `d` or a matrix where each column is an observation.
"""
function predict(M::PPCA, x::AbstractVecOrMat{T}) where {T<:Real}
xn = centralize(x, M.mean)
n = size(M)[2]
return inv(cov(M))*M.W'*xn
end
"""
reconstruct(M::PPCA, z)
Approximately reconstruct observations from the latent variable given in `z`.
Here, `z` can be either a vector of length `p` or a matrix where each column gives
the latent variables for an observation.
"""
function reconstruct(M::PPCA, z::AbstractVecOrMat{T}) where {T<:Real}
W = M.W
WTW = W'W
n = size(M)[2]
C = WTW + var(M) * I
return W*inv(WTW)*C*z .+ mean(M)
end
## show
function Base.show(io::IO, M::PPCA)
i, o = size(M)
print(io, "Probabilistic PCA(indim = $i, outdim = $o, σ² = $(var(M)))")
end
## core algorithms
"""
ppcaml(Z, mean; ...)
Compute probabilistic PCA using on maximum likelihood formulation for a centralized
sample matrix `Z`.
*Parameters*:
- `Z`: a centralized samples matrix
- `mean`: The mean vector of the **original** samples, which can be a vector of
length `d`, or an empty vector indicating a zero mean.
Returns the resultant [`PPCA`](@ref) model.
**Note:** This function accepts two keyword arguments: `maxoutdim` and `tol`.
"""
function ppcaml(Z::AbstractMatrix{T}, mean::Vector{T};
tol::Real=1.0e-6, # convergence tolerance
maxoutdim::Int=size(Z,1)-1) where {T<:Real}
check_pcaparams(size(Z,1), mean, maxoutdim, 1.)
d, n = size(Z)
# SVD decomposition
Svd = svd(Z)
λ = Svd.S
ord = sortperm(λ; rev=true)
V = abs2.(λ[ord]) ./ (n-1)
# filter 0 eigenvalues and adjust number of latent dimensions
idxs = findall(V .< tol)
l = length(idxs)
l = l == 0 ? maxoutdim : l
# variance "loss" in the projection
σ² = sum(V[l+1:end])/(d-l)
@inbounds for i in 1:l
V[i] = sqrt(V[i] - σ²)
end
W = Svd.U[:,ord[1:l]]*diagm(0 => V[1:l])
return PPCA(mean, W, σ²)
end
"""
ppcaem(S, mean, n; ...)
Compute probabilistic PCA based on expectation-maximization algorithm for a given sample covariance matrix `S`.
*Parameters*:
- `S`: The sample covariance matrix.
- `mean`: The mean vector of original samples, which can be a vector of length `d`,
or an empty vector indicating a zero mean.
- `n`: The number of observations.
Returns the resultant [`PPCA`](@ref) model.
**Note:** This function accepts three keyword arguments: `maxoutdim`, `tol`, and `maxiter`.
"""
function ppcaem(S::AbstractMatrix{T}, mean::Vector{T}, n::Int;
maxoutdim::Int=size(S,1)-1,
tol::Real=1.0e-6, # convergence tolerance
maxiter::Integer=1000) where {T<:Real}
check_pcaparams(size(S,1), mean, maxoutdim, 1.)
d = size(S,1)
q = maxoutdim
Iq = Matrix{T}(I, q, q)
Id = Matrix{T}(I, d, d)
W = Matrix{T}(I, d, q)
σ² = zero(T)
M⁻¹ = inv(W'W .+ σ² * Iq)
i = 1
L_old = 0.
chg = NaN
converged = false
while i < maxiter
# EM-steps
SW = S*W
W⁺ = SW*inv(σ²*Iq + M⁻¹*W'*SW)
σ²⁺ = tr(S - SW*M⁻¹*(W⁺)')/d
# new parameters
W = W⁺
σ² = σ²⁺
# log likelihood
C = W*W'.+ σ²*Id
M⁻¹ = inv(W'*W .+ σ²*Iq)
C⁻¹ = (Id - W*M⁻¹*W')/σ²
L = (-n/2)*(log(det(C)) + tr(C⁻¹*S)) # (-n/2)*d*log(2π) omitted
@debug "Likelihood" iter=i L=L ΔL=abs(L_old - L)
chg = abs(L_old - L)
if chg < tol
converged = true
break
end
L_old = L
i += 1
end
converged || throw(ConvergenceException(maxiter, chg, oftype(chg, tol)))
return PPCA(mean, W, σ²)
end
"""
bayespca(S, mean, n; ...)
Compute probabilistic PCA using a Bayesian algorithm for a given sample covariance matrix `S`.
*Parameters*:
- `S`: The sample covariance matrix.
- `mean`: The mean vector of original samples, which can be a vector of length `d`,
or an empty vector indicating a zero mean.
- `n`: The number of observations.
Returns the resultant [`PPCA`](@ref) model.
**Notes:**
- This function accepts three keyword arguments: `maxoutdim`, `tol`, and `maxiter`.
- Function uses the `maxoutdim` parameter as an upper boundary when it automatically
determines the latent space dimensionality.
"""
function bayespca(S::AbstractMatrix{T}, mean::Vector{T}, n::Int;
maxoutdim::Int=size(S,1)-1,
tol::Real=1.0e-6, # convergence tolerance
maxiter::Integer=1000) where {T<:Real}
check_pcaparams(size(S,1), mean, maxoutdim, 1.)
d = size(S,1)
q = maxoutdim
Iq = Matrix{T}(I, q, q)
Id = Matrix{T}(I, d, d)
W = Matrix{T}(I, d, q)
wnorm = zeros(T, q)
σ² = zero(T)
M = W'*W .+ σ²*Iq
M⁻¹ = inv(M)
α = zeros(T, q)
i = 1
chg = NaN
L_old = 0.
converged = false
while i < maxiter
# EM-steps
SW = S*W
W⁺ = SW*inv(σ²*(Iq+diagm(0=>α)*M/n) + M⁻¹*W'*SW)
σ²⁺ = tr(S - SW*M⁻¹*(W⁺)')/d
# new parameters
W = W⁺
σ² = σ²⁺
@inbounds for j in 1:q
wnorm[j] = norm(W[:,j])^2
α[j] = wnorm[j] < eps() ? maxintfloat(Float64) : d/wnorm[j]
end
# log likelihood
C = W*W'.+ σ²*Id
M = W'*W .+ σ²*Iq
M⁻¹ = inv(M)
C⁻¹ = (Id - W*M⁻¹*W')/σ²
L = (-n/2)*(log(det(C)) + tr(C⁻¹*S)) # (-n/2)*d*log(2π) omitted
@debug "Likelihood" iter=i L=L ΔL=abs(L_old - L)
chg = abs(L_old - L)
if chg < tol
converged = true
break
end
L_old = L
i += 1
end
converged || throw(ConvergenceException(maxiter, chg, oftype(chg, tol)))
return PPCA(mean, W[:,wnorm .> 0.], σ²)
end
## interface functions
"""
fit(PPCA, X; ...)
Perform probabilistic PCA over the data given in a matrix `X`.
Each column of `X` is an observation. This method returns an instance of [`PPCA`](@ref).
**Keyword arguments:**
Let `(d, n) = size(X)` be respectively the input dimension and the number of observations:
- `method`: The choice of methods:
- `:ml`: use maximum likelihood version of probabilistic PCA (*default*)
- `:em`: use EM version of probabilistic PCA
- `:bayes`: use Bayesian PCA
- `maxoutdim`: Maximum output dimension (*default* `d-1`)
- `mean`: The mean vector, which can be either of:
- `0`: the input data has already been centralized
- `nothing`: this function will compute the mean (*default*)
- a pre-computed mean vector
- `tol`: Convergence tolerance (*default* `1.0e-6`)
- `maxiter`: Maximum number of iterations (*default* `1000`)
**Notes:** This function calls [`ppcaml`](@ref), [`ppcaem`](@ref) or
[`bayespca`](@ref) internally, depending on the choice of method.
"""
function fit(::Type{PPCA}, X::AbstractMatrix{T};
method::Symbol=:ml,
maxoutdim::Int=size(X,1)-1,
mean=nothing,
tol::Real=1.0e-6, # convergence tolerance
maxiter::Integer=1000) where {T<:Real}
@assert !SparseArrays.issparse(X) "Use Kernel PCA for sparse arrays"
d, n = size(X)
# process mean
mv = preprocess_mean(X, mean)
if !(isempty(mv) || length(mv) == d)
throw(DimensionMismatch("Dimensions of weight matrix and mean are inconsistent."))
end
if method == :ml
Z = centralize(X, mv)
M = ppcaml(Z, mv, maxoutdim=maxoutdim, tol=tol)
elseif method == :em || method == :bayes
S = covm(X, isempty(mv) ? 0 : mv, 2)
if method == :em
M = ppcaem(S, mv, n, maxoutdim=maxoutdim, tol=tol, maxiter=maxiter)
elseif method == :bayes
M = bayespca(S, mv, n, maxoutdim=maxoutdim, tol=tol, maxiter=maxiter)
end
else
throw(ArgumentError("Invalid method name $(method)"))
end
return M::PPCA
end