Skip to content

Instantly share code, notes, and snippets.

@jhaberstro
Created January 25, 2019 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhaberstro/74b99b817f1b87d02bb55d6a0077599b to your computer and use it in GitHub Desktop.
Save jhaberstro/74b99b817f1b87d02bb55d6a0077599b to your computer and use it in GitHub Desktop.
WebPPL Hidden Markov Model Inference
/*
Dealer repeatedly flips a coin. Sometimes the coin is fair, with P(heads) = 0.5,
sometimes it’s loaded, with P(heads) = 0.8. Dealer occasionally switches coins,
invisibly to you. Given an list of observed coin flips, infer if the coin was
fair for each individual flip.
*/
var hmm = function(n, initial, transitionf, observef) {
var impl = function(N) {
if (N > 1) {
var state = impl(N - 1)
var next_hidden = transitionf(state.hidden[state.hidden.length - 1])
var next_observed = observef(next_hidden)
return { hidden: state.hidden.concat([next_hidden]), observed: state.observed.concat([next_observed]) }
}
else return { hidden: [initial], observed: [observef(initial)] }
}
return impl(n)
}
var sometimes_change_coin = function(previous_fair_state) {
return flip(0.9) ? previous_fair_state : !previous_fair_state
}
var do_flip = function(is_fair) {
var is_head = is_fair ? flip(0.5) : flip(0.8)
return is_head ? "H" : "T"
}
var post = Infer({method: 'MCMC', samples: 1000, lag: 100, burn: 50,
model: function() {
var data = ["H", "H", "H", "H", "H", "H", "T", "H", "T", "H", "T", "H", "T"]
var model = hmm(data.length, flip(0.5), sometimes_change_coin, do_flip)
condition(sum(map2(function(a, b) { return a == b}, data, model.observed)) == data.length)
return model.hidden
}})
viz.marginals(post)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment