Simulating and Modeling Statistical Distributions via bayes.js

2 minute read

Published:

I have been thinking about building a web app for simulating data with given parameters and recovering the parameters with Bayesian MCMC samplers in JavaScript. This web app can not only make the procedures more transparent, but also help us understand the magic of the Bayesian MCMC approach. More importantly, I have benefited from this simulation-based way of thinking, so I would like to promote it in my blog.

I looked for some off-the-shelf software online and found a JS library bayes.js developed by Rasmus Bååth. He also wrote a blog to introduce the library. I strongly recommend you first to read his blog to get some key ideas behind it. The library includes an adaptive MCMC sampler (AmwgSampler) in mcmc.js and some common probability distributions in distributions.js. There are also some examples, e.g., you can use bayes.js to fit a Normal distribution and plot the posterior distributions of parameters via plotly.js.

This blog heavily relies on Bååth’s library and his implementations. I appreciate his efforts to build a web app for Bayesian data analysis in JavaScript. Here I made some small adjustments.

  • (1) Include the data generating process by using **d3.js**; You can type console.log(data) or data in your console to check the simulated data.

  • (2) Simultaneously update the posterior distributions with the true parameters indicated by red vertical lines;

  • (3) Enable and disable buttons and textContent to make it more user-friendly;

  • (4) Add buttons to display messages and warnings.

These changes are purely based on my personal tastes since I want to simulate data with valid parameters from a probabilistic distribution and check the performance of the posterior estimates against the original parameter values. With some help from ChatGPT, I implemented the web app and deployed it inside my personal webpage powered by Jekyll. Here is the web app for Bayesian MCMC for Normal distributions. Note that the default priors for the parameters of the normal distribution are $\mu \sim N(0, 100)$ and $\sigma \sim U(0, 100)$. If you prefer a standalone version, pls check this page.

Simulating and modeling Normal distributions via bayes.js

Bayesian MCMC for Normal distributions

Useful links: