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

Categorical distribution #148

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
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
40 changes: 40 additions & 0 deletions src/parameterized/categorical.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Categorical distribution

# REFERENCES
# https://juliastats.org/Distributions.jl/stable/univariate/#Distributions.Categorical
# https://juliastats.org/Distributions.jl/stable/univariate/#Distributions.DiscreteNonParametric

export Categorical

@parameterized Categorical(p) ≪ CountingMeasure(ℤ[0:∞])

ncategories(d::Categorical) = length(d.p)

(d::Categorical ≪ ::CountingMeasure{IntegerRange{a,b}}) where {a,b} = a ≤ 1 && b ≥ ncategories(d)

(::CountingMeasure{IntegerRange{a,b}} ≪ ::Categorical) where {a,b} = a ≥ 1 && b ≤ ncategories(d)

###############################################################################
@kwstruct Categorical(p)

logdensity(d::Categorical{(:p)}, y) = log(d.p[y])

# The implementation of Dists.DiscreteNonParametric has heavy argument checks
# But I think since the values of Categorical are 1:n the sortperm has no effect
# So it might be OK
distproxy(d::Categorical{(:p)}) = Dists.Categorical(d.p)

Base.rand(rng::AbstractRNG, T::Type, d::Categorical{(:p)}) = rand(rng, distproxy(d))

asparams(::Type{<:Categorical}, ::Val{:p}) = as𝕀

###############################################################################
@kwstruct Categorical(logp)

logdensity(d::Categorical{(:logp)}, y) = d.logp[y]

distproxy(d::Categorical{(:logp)}) = Dists.Categorical(exp.(d.logp)) # inefficient

Base.rand(rng::AbstractRNG, T::Type, d::Categorical{(:logp)}) = rand(rng, distproxy(d))

asparams(::Type{<:Categorical}, ::Val{:logp}) = asℝ