bayes.js: A Small Library for Doing MCMC in the Browser

By Rasmus Bååth

(This article was first published on Publishable Stuff, and kindly contributed to R-bloggers)

Bayesian data analysis is cool, Markov chain Monte Carlo is the cool technique that makes Bayesian data analysis possible, and wouldn’t it be coolness if you could do all of this in the browser? That was what I thought, at least, and I’ve now made bayes.js: A small JavaScript library that implements an adaptive MCMC sampler and a couple of probability distributions, and that makes it relatively easy to implement simple Bayesian models in JavaScript.

Here is a motivating example: Say that you have the heights of the last ten American presidents…

// The heights of the last ten American presidents in cm, from Kennedy to Obama 
var heights = [183, 192, 182, 183, 177, 185, 188, 188, 182, 185];

… and that you would like to fit a Bayesian model assuming a Normal distribution to this data. Well, you can do that right now by clicking “Start sampling” below! This will run an MCMC sampler in your browser implemented in JavaScript.



function loadScript(url, callback)
{
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;

// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;

// Fire the loading
head.appendChild(script);
}

var clear_samples;
var sample_loop;
var stop_sample_loop;

loadScript("https://cdn.plot.ly/plotly-1.3.0.min.js", function(){
loadScript("/files/posts/2015-12-31-bayes-js-a-small-library-for-doing-mcmc-in-the-browser/mcmc.js", function(){
loadScript("/files/posts/2015-12-31-bayes-js-a-small-library-for-doing-mcmc-in-the-browser/distributions.js", function(){

var heights = [183, 192, 182, 183, 177, 185, 188, 188, 182, 185];

var params = {
mu: {type: "real"},
sigma: {type: "real", lower: 0}};

var log_post = function(state, heights) {
var log_post = 0;
// Priors (here sloppy and vague...)
log_post += ld.norm(state.mu, 0, 1000);
log_post += ld.unif(state.sigma, 0, 1000);
// Likelihood
for(var i = 0; i ' +
'

' +
'

' +
'

Source:: R News

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.