-
Notifications
You must be signed in to change notification settings - Fork 1
/
stochastic_em.jl
318 lines (255 loc) · 10.1 KB
/
stochastic_em.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
"""
Base.@kwdef struct StochasticEM<:AbstractEM
rng::AbstractRNG = Random.GLOBAL_RNG
end
The Stochastic EM algorithm was introduced by G. Celeux, and J. Diebolt. in 1985 in [*The SEM Algorithm: A probabilistic teacher algorithm derived from the EM algorithm for the mixture problem*](https://cir.nii.ac.jp/crid/1574231874553755008).
The default random seed is `Random.GLOBAL_RNG` but it can be changed via `StochasticEM(seed)`.
"""
Base.@kwdef struct StochasticEM <: AbstractEM
rng::AbstractRNG = Random.GLOBAL_RNG
end
#TODO: One could probably avoid repeating code for univariate/multivariate: the only change is in `fit_mle(dist, y[cat[k]])` vs `fit_mle(dist, y[:, cat[k]])`.
"""
fit_mle!(α::AbstractVector, dists::AbstractVector{F} where {F<:Distribution}, y::AbstractVecOrMat, method::StochasticEM; display=:none, maxiter=1000, atol=1e-3, robust=false)
Use the stochastic EM algorithm to update the Distribution `dists` and weights `α` composing a mixture distribution.
- `robust = true` will prevent the (log)likelihood to overflow to `-∞` or `∞`.
- `atol` criteria determining the convergence of the algorithm. If the Loglikelihood difference between two iteration `i` and `i+1` is smaller than `atol` i.e. `|ℓ⁽ⁱ⁺¹⁾ - ℓ⁽ⁱ⁾|<atol`, the algorithm stops.
- `rtol` relative tolerance for convergence, `|ℓ⁽ⁱ⁺¹⁾ - ℓ⁽ⁱ⁾|<rtol*(|ℓ⁽ⁱ⁺¹⁾| + |ℓ⁽ⁱ⁾|)/2` (does not check if `rtol` is `nothing`)
- `display` value can be `:none`, `:iter`, `:final` to display Loglikelihood evolution at each iterations `:iter` or just the final one `:final`
"""
function fit_mle!(
α::AbstractVector,
dists::AbstractVector{F} where {F<:Distribution},
y::AbstractVector,
method::StochasticEM;
display = :none,
maxiter = 1000,
atol = 1e-3,
rtol = nothing,
robust = false,
)
@argcheck display in [:none, :iter, :final]
@argcheck maxiter >= 0
N, K = size_sample(y), length(dists)
history = Dict("converged" => false, "iterations" => 0, "logtots" => zeros(0))
# Allocate memory for in-place updates
LL = zeros(N, K)
γ = similar(LL)
c = zeros(N)
ẑ = zeros(Int, N)
# E-step
E_step!(LL, c, γ, dists, α, y; robust = robust)
# Loglikelihood
logtot = sum(c)
(display == :iter) && println("Method = $(method)\nIteration 0: loglikelihood = ", logtot)
for it = 1:maxiter
# S-step
ẑ[:] .= [rand(method.rng, Categorical(ℙ...)) for ℙ in eachrow(γ)]
cat = [findall(ẑ .== k) for k = 1:K]
# M-step
# using ẑ, maximize (update) the parameters
α[:] = length.(cat)/N
dists[:] = [fit_mle(dists[k], y[cat[k]]) for k = 1:K]
# E-step
# evaluate likelihood for each type k
E_step!(LL, c, γ, dists, α, y; robust = robust)
# Loglikelihood
logtotp = sum(c)
(display == :iter) && println("Iteration $(it): loglikelihood = ", logtotp)
push!(history["logtots"], logtotp)
history["iterations"] += 1
if abs(logtotp - logtot) < atol || (rtol !== nothing && abs(logtotp - logtot) < rtol * (abs(logtot) + abs(logtotp)) / 2)
(display in [:iter, :final]) &&
println("EM converged in ", it, " iterations, final loglikelihood = ", logtotp)
history["converged"] = true
break
end
logtot = logtotp
end
if !history["converged"]
if display in [:iter, :final]
println(
"EM has not converged after $(history["iterations"]) iterations, final loglikelihood = $logtot",
)
end
end
return history
end
# multivariate version with no weights
function fit_mle!(
α::AbstractVector,
dists::AbstractVector{F} where {F<:Distribution},
y::AbstractMatrix,
method::StochasticEM;
display = :none,
maxiter = 1000,
atol = 1e-3,
rtol = nothing,
robust = false,
)
@argcheck display in [:none, :iter, :final]
@argcheck maxiter >= 0
N, K = size_sample(y), length(dists)
history = Dict("converged" => false, "iterations" => 0, "logtots" => zeros(0))
# Allocate memory for in-place updates
LL = zeros(N, K)
γ = similar(LL)
c = zeros(N)
# E-step
E_step!(LL, c, γ, dists, α, y; robust = robust)
# Loglikelihood
logtot = sum(c)
(display == :iter) && println("Method = $(method)\nIteration 0: loglikelihood = ", logtot)
for it = 1:maxiter
# S-step
ẑ = [rand(method.rng, Categorical(ℙ...)) for ℙ in eachrow(γ)]
cat = [findall(ẑ .== k) for k = 1:K]
# M-step
# using ẑ, maximize (update) the parameters
α[:] = length.(cat)/N
dists[:] = [fit_mle(dists[k], y[:, cat[k]]) for k = 1:K]
# E-step
# evaluate likelihood for each type k
E_step!(LL, c, γ, dists, α, y; robust = robust)
# Loglikelihood
logtotp = sum(c)
(display == :iter) && println("Iteration $(it): loglikelihood = ", logtotp)
push!(history["logtots"], logtotp)
history["iterations"] += 1
if abs(logtotp - logtot) < atol || (rtol !== nothing && abs(logtotp - logtot) < rtol * (abs(logtot) + abs(logtotp)) / 2)
(display in [:iter, :final]) &&
println("EM converged in ", it, " iterations, final loglikelihood = ", logtotp)
history["converged"] = true
break
end
logtot = logtotp
end
if !history["converged"]
if display in [:iter, :final]
println(
"EM has not converged after $(history["iterations"]) iterations, final loglikelihood = $logtot",
)
end
end
return history
end
# univariate version with weights
function fit_mle!(
α::AbstractVector,
dists::AbstractVector{F} where {F<:Distribution},
y::AbstractVector,
w::AbstractVector,
method::StochasticEM;
display = :none,
maxiter = 1000,
atol = 1e-3,
rtol = nothing,
robust = false,
)
@argcheck display in [:none, :iter, :final]
@argcheck maxiter >= 0
N, K = size_sample(y), length(dists)
@argcheck length(w) == N
history = Dict("converged" => false, "iterations" => 0, "logtots" => zeros(0))
# Allocate memory for in-place updates
LL = zeros(N, K)
γ = similar(LL)
c = zeros(N)
# E-step
E_step!(LL, c, γ, dists, α, y; robust = robust)
# Loglikelihood
logtot = sum(w[n] * c[n] for n = 1:N) #dot(w, c)
(display == :iter) && println("Method = $(method)\nIteration 0: loglikelihood = ", logtot)
for it = 1:maxiter
# S-step
ẑ = [rand(method.rng, Categorical(ℙ...)) for ℙ in eachrow(γ)]
cat = [findall(ẑ .== k) for k = 1:K]
# M-step
# using ẑ, maximize (update) the parameters
α[:] = [length(cat[k])*sum(w[cat[k]]) for k in 1:K]/sum(w)
dists[:] = [fit_mle(dists[k], y[cat[k]], w[cat[k]]) for k = 1:K]
# E-step
# evaluate likelihood for each type k
E_step!(LL, c, γ, dists, α, y; robust = robust)
# Loglikelihood
logtotp = sum(w[n] * c[n] for n in eachindex(c)) #dot(w, c)
(display == :iter) && println("Iteration $(it): loglikelihood = ", logtotp)
push!(history["logtots"], logtotp)
history["iterations"] += 1
if abs(logtotp - logtot) < atol || (rtol !== nothing && abs(logtotp - logtot) < rtol * (abs(logtot) + abs(logtotp)) / 2)
(display in [:iter, :final]) &&
println("EM converged in ", it, " iterations, final loglikelihood = ", logtotp)
history["converged"] = true
break
end
logtot = logtotp
end
if !history["converged"]
if display in [:iter, :final]
println(
"EM has not converged after $(history["iterations"]) iterations, final loglikelihood = $logtot",
)
end
end
return history
end
# multivariate version with weights
function fit_mle!(
α::AbstractVector,
dists::AbstractVector{F} where {F<:Distribution},
y::AbstractMatrix,
w::AbstractVector,
method::StochasticEM;
display = :none,
maxiter = 1000,
atol = 1e-3,
rtol = nothing,
robust = false,
)
@argcheck display in [:none, :iter, :final]
@argcheck maxiter >= 0
N, K = size_sample(y), length(dists)
@argcheck length(w) == N
history = Dict("converged" => false, "iterations" => 0, "logtots" => zeros(0))
# Allocate memory for in-place updates
LL = zeros(N, K)
γ = similar(LL)
c = zeros(N)
# E-step
E_step!(LL, c, γ, dists, α, y; robust = robust)
# Loglikelihood
logtot = sum(w[n] * c[n] for n = 1:N) #dot(w, c)
(display == :iter) && println("Method = $(method)\nIteration 0: loglikelihood = ", logtot)
for it = 1:maxiter
# S-step
ẑ = [rand(method.rng, Categorical(ℙ...)) for ℙ in eachrow(γ)]
cat = [findall(ẑ .== k) for k = 1:K]
# M-step
# using ẑ, maximize (update) the parameters
α[:] = [sum(w[cat[k]]) for k in 1:K]/sum(w)
dists[:] = [fit_mle(dists[k], y[:, cat[k]], w[cat[k]]) for k = 1:K]
# E-step
# evaluate likelihood for each type k
E_step!(LL, c, γ, dists, α, y; robust = robust)
# Loglikelihood
logtotp = sum(w[n] * c[n] for n in eachindex(c)) #dot(w, c)
(display == :iter) && println("Iteration $(it): loglikelihood = ", logtotp)
push!(history["logtots"], logtotp)
history["iterations"] += 1
if abs(logtotp - logtot) < atol || (rtol !== nothing && abs(logtotp - logtot) < rtol * (abs(logtot) + abs(logtotp)) / 2)
(display in [:iter, :final]) &&
println("EM converged in ", it, " iterations, final loglikelihood = ", logtotp)
history["converged"] = true
break
end
logtot = logtotp
end
if !history["converged"]
if display in [:iter, :final]
println(
"EM has not converged after $(history["iterations"]) iterations, final loglikelihood = $logtot",
)
end
end
return history
end