-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCompoundDistributions.jl
256 lines (205 loc) · 6.68 KB
/
CompoundDistributions.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
module CompoundDistributions
using StatsFuns.RFunctions: betarand, gammarand
using SpecialFunctions: lbeta
using LogProbs
# distribution types
export BetaBern, DirMul, DirCat, UniCat, CatDist, ChineseRest
# conditional distribution type
export SimpleCond
# functions
export support, sample, logscore, add_obs!, rm_obs!
# helper function
export categorical_sample
abstract type Distribution{T} end
function categorical_sample(tokens, weights)
T = eltype(weights)
x = rand(T) * sum(weights)
cum_weights = zero(T)
for (t, w) in zip(tokens, weights)
cum_weights += w
if cum_weights > x
return t
end
end
end
categorical_sample(d::Dict) = categorical_sample(keys(d), values(d))
categorical_sample(v::Vector) = categorical_sample(1:length(v), v)
############################
### Beta Bernoulli Class ###
############################
mutable struct BetaBern{T, C} <: Distribution{T}
heads :: T
tails :: T
alpha :: C
beta :: C
end
BetaBern(a, b) = BetaBern(true, false, a, b)
BetaBern(support) = BetaBern(support..., 1, 1)
support(bb::BetaBern) = [bb.heads, bb.tails]
function sample(bb::BetaBern)
p = betarand(bb.alpha, bb.beta)
categorical_sample((bb.heads, bb.tails), (p, 1-p))
end
function logscore(bb::BetaBern, obs)
k = obs == bb.heads
LogProb(lbeta(k+bb.alpha, 1-k+bb.beta) - lbeta(bb.alpha, bb.beta), islog=true)
end
add_obs!(bb::BetaBern, obs) = obs == bb.heads ? bb.alpha += 1 : bb.beta += 1
rm_obs!(bb::BetaBern, obs) = obs == bb.heads ? bb.alpha -= 1 : bb.beta -= 1
###################################
### Dirichlet Multinomial Class ###
###################################
mutable struct DirMul{T, C} <: Distribution{T}
counts :: Dict{T, C}
end
DirMul(support) = DirMul(Dict(x => 1.0 for x in support))
support(dm::DirMul) = keys(dm.counts)
function sample(dm::DirMul, n)
weights = [gammarand(c, 1) for c in values(dm.counts)]
d = Dict(k=>0 for k in keys(dm.counts))
for i in 1:n
d[categorical_sample(keys(dm.counts), weights)] += 1
end
d
end
function logscore(dm::DirMul, obs::AbstractDict)
n = sum(values(obs))
LogProb(
log(n) + lbeta(sum(values(dm.counts)), n) -
sum(
log(obs[x]) + lbeta(dm.counts[x], obs[x])
for x in keys(dm.counts) if obs[x] > 0
),
islog=true
)
end
function add_obs!(dm::DirMul, obs::AbstractDict)
for x in keys(obs)
dm.counts[x] += obs[x]
end
end
function rm_obs!(dm::DirMul, obs::AbstractDict)
for x in keys(obs)
dm.counts[x] -= obs[x]
end
end
###################################
### Dirichlet Categorical Class ###
###################################
mutable struct DirCat{T, C} <: Distribution{T}
counts :: Dict{T, C}
end
DirCat(support) = DirCat(Dict(x => 1.0 for x in support))
support(dc::DirCat) = keys(dc.counts)
function sample(dc::DirCat)
weights = [gammarand(c, 1) for c in values(dc.counts)]
categorical_sample(keys(dc.counts), weights)
end
function logscore(dc::DirCat, obs)
LogProb(lbeta(sum(values(dc.counts)), 1) - lbeta(dc.counts[obs], 1), islog=true)
end
add_obs!(dc::DirCat, obs) = dc.counts[obs] += 1
rm_obs!(dc::DirCat, obs) = dc.counts[obs] -= 1
######################################
### Categorical Distribution Class ###
######################################
struct CatDist{T} <: Distribution{T}
probs :: Dict{T, LogProb}
end
support(cd::CatDist) = keys(cd.probs)
logscore(cd::CatDist, x) = cd.probs[x]
sample(cd::CatDist) = categorical_sample(cd.probs)
add_obs!(cd::CatDist, obs, context) = nothing
remove_obs!(cd::CatDist, obs, context) = nothing
#################################
### Uniform Categorical Class ###
#################################
struct UniCat{T} <: Distribution{T}
support :: Vector{T}
end
UniCat(support) = UniCat(collect(support))
support(uc::UniCat) = uc.support
sample(uc::UniCat) = uc.support[rand(1:length(uc.support))]
logscore(uc::UniCat, obs) = obs in uc.support ? LogProb(1 / length(uc.support)) : zero(LogProb)
add_obs!(uc::UniCat, obs, context) = nothing
rm_obs!(uc::UniCat, obs, context) = nothing
################################
### Chinese Restaurant Class ###
################################
mutable struct ChineseRest{Dish, Dist <: Distribution{Dish}} <: Distribution{Dish}
a :: Float64 # discount parameter
b :: Float64 # crp parameter
basedist :: Dist
tables :: Dict{Dish, Vector{Int}}
num_tables :: Int
num_customers :: Int
end
ChineseRest(a, b, basedist::Distribution{T}) where T =
ChineseRest(a, b, basedist, Dict{T, Vector{Int}}(), 0, 0)
ChineseRest(support) = ChineseRest(0.0, 0.1, UniCat(support))
support(r::ChineseRest) = support(r.basedist)
function sample(r::ChineseRest)
if flip((r.num_tables * r.a + r.b) / (r.num_customers + r.b))
sample(r.basedist)
else
categorical_sample(
Dict(dish => sum(r.tables[dish]) for dish in keys(r.tables))
)
end
end
function new_table_logscore(r::ChineseRest, dish)
new_table_prob = LogProb(
log(r.num_tables * r.a + r.b) - log(r.num_customers + r.b)
)
base_dist_prob = logscore(r.basedist, dish)
new_table_prob * base_dist_prob
end
function logscore(r::ChineseRest, dish)
if haskey(r.tables, dish)
numerator = sum(n - r.a for n in r.tables[dish])
LogProb(log(numerator) - log(r.num_customers + r.b), islog=true) + new_table_logscore(r, dish)
else
new_table_logscore(r, dish)
end
end
function add_obs!(r::ChineseRest, dish)
r.num_customers += 1
if !haskey(r.tables, dish)
r.num_tables += 1
r.tables[dish] = [1]
else
r.tables[dish][1] += 1
end
nothing
end
function rm_obs!(r::ChineseRest, dish)
r.num_customers -= 1
r.tables[dish][1] -= 1
if r.tables[dish][1] == 0
r.num_tables -= 1
delete!(r.tables, dish)
end
nothing
end
################################
### Simple Conditional Class ###
################################
mutable struct SimpleCond{C, D, S} # context, distribution, support
dists :: Dict{C, D}
support :: S
end
SimpleCond(dists::AbstractDict) = SimpleCond(
dists,
vcat([collect(support(dist)) for dist in values(dists)]...)
)
SimpleCond(g::Union{Base.Generator, Base.Iterators.Flatten}) = SimpleCond(Dict(g))
sample(sc::SimpleCond, context, args...) = sample(sc.dists[context], args...)
logscore(sc::SimpleCond, obs, context) = logscore(sc.dists[context], obs)
rm_obs!(sc::SimpleCond, obs, context) = rm_obs!(sc.dists[context], obs)
function add_obs!(cond::SimpleCond{C,D,S}, obs, context) where {C,D,S}
if !haskey(cond.dists, context)
cond.dists[context] = D(cond.support)
end
add_obs!(cond.dists[context], obs)
end
end # module