Skip to content

Instantly share code, notes, and snippets.

@mschmidt87
Created August 4, 2022 02:27
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 mschmidt87/81ffe34aefb7ec5f80cc5d5194f7f37c to your computer and use it in GitHub Desktop.
Save mschmidt87/81ffe34aefb7ec5f80cc5d5194f7f37c to your computer and use it in GitHub Desktop.
webppl example
var g0 = 'Hello, World!'
var g1 = 'Howdy, universe!'
var g2 = 'Oh no, not again!'
var greeting = function(sunny) {
return function() {
var greetingChoice = sunny ? flip(0.6) : flip(0.2)
var altAnswer = sunny ? g1 : g2
return greetingChoice ? g0 : altAnswer
}
}
var predictGreeting = function(sunnyDist) {
return function() {
var x = sample(sunnyDist);
return greeting(x)()
}
}
var sunnyTomorrow = function(sunnyToday) {
return function() {
var pSunny = sample(sunnyToday) ? 0.8 : 0.05
return flip(pSunny)
}
}
var predictGreetingToday = function () {
var sunnyToday = flip(0.2)
return greeting(sunnyToday)()
}
var inferWeatherToday = function (observedGreeting) {
return function() {
var sunnyToday = flip(0.2);
var greet = greeting(sunnyToday)
condition(greet() == observedGreeting)
return sunnyToday
}
}
var LearnandPredict = function (observedGreeting) {
return function() {
// Infer today's weather
var sunnyToday = Infer({method: 'rejection', samples: 1000},
inferWeatherToday(observedGreeting))
// Predict tomorrow's weather
var sTomorrow = Infer({method: 'forward', samples: 1000},
sunnyTomorrow(sunnyToday))
// Predict tomorrow's greeting
var gTomorrow = Infer({method: 'forward', samples:1000},
predictGreeting(sTomorrow))
return gTomorrow
}
}
// Predict today's greeting
viz(repeat(100, predictGreetingToday))
var g_obs = g2
// Infer today's weather based on an observed greeting
viz(Infer({method: 'rejection', samples: 1000}, inferWeatherToday(g_obs)))
// Predict tomorrow's weather based on an observed greeting
viz(LearnandPredict(g_obs)())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment