Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Mixture Models #79

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/DistributionsAD.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import Distributions: MvNormal,
BetaBinomial,
Erlang
import ZygoteRules
import Zygote

export TuringScalMvNormal,
TuringDiagMvNormal,
Expand All @@ -50,6 +51,7 @@ export TuringScalMvNormal,
include("common.jl")
include("univariate.jl")
include("multivariate.jl")
include("mixturemodels.jl")
include("mvcategorical.jl")
include("matrixvariate.jl")
include("flatten.jl")
Expand Down
46 changes: 46 additions & 0 deletions src/mixturemodels.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
function _mixlogpdf1(d::AbstractMixtureModel, x)
# using the formula below for numerical stability
#
# logpdf(d, x) = log(sum_i pri[i] * pdf(cs[i], x))
# = log(sum_i pri[i] * exp(logpdf(cs[i], x)))
# = log(sum_i exp(logpri[i] + logpdf(cs[i], x)))
# = m + log(sum_i exp(logpri[i] + logpdf(cs[i], x) - m))
#
# m is chosen to be the maximum of logpri[i] + logpdf(cs[i], x)
# such that the argument of exp is in a reasonable range
#

K = ncomponents(d)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

K is not used anywhere.

Suggested change
K = ncomponents(d)

p = probs(d)
# use Buffer to avoid mutating arrays.
# lp = Vector{eltype(p)}(undef, K)
lp = Zygote.Buffer(p, K)
m = -Inf # m <- the maximum of log(p(cs[i], x)) + log(pri[i])
@inbounds for i in eachindex(p)
sivapvarma marked this conversation as resolved.
Show resolved Hide resolved
pi = p[i]
if pi > 0.0
# lp[i] <- log(p(cs[i], x)) + log(pri[i])
lp_i = logpdf(component(d, i), x) + log(pi)
# zygote seems to have trouble here.
# Mutating arrays is not supported
lp[i] = lp_i
if lp_i > m
m = lp_i
end
end
end
v = 0.0
@inbounds for i = 1:K
if p[i] > 0.0
v += exp(lp[i] - m)
end
end
return m + log(v)
end



Distributions.logpdf(d::UnivariateMixture{Continuous}, x::Real) = _mixlogpdf1(d, x)
Distributions.logpdf(d::UnivariateMixture{Discrete}, x::Int) = _mixlogpdf1(d, x)

Distributions._logpdf(d::MultivariateMixture, x::AbstractVector) = _mixlogpdf1(d, x)