Path: blob/master/deprecated/notebooks/linreg_bayes_svi_hmc_pyro.ipynb
1192 views
Bayesian linear regression in Pyro
We compare stochastic variational inference with HMC for Bayesian linear regression. We use the example from sec 8.1 of Statistical Rethinking ed 2. The code is modified from https://pyro.ai/examples/bayesian_regression.html and https://pyro.ai/examples/bayesian_regression_ii.html.
For a NumPyro version (that uses Laplace approximation instead of SVI/ HMC), see https://fehiepsi.github.io/rethinking-numpyro/08-conditional-manatees.html.
Collecting pyro-ppl
Downloading https://files.pythonhosted.org/packages/aa/7a/fbab572fd385154a0c07b0fa138683aa52e14603bb83d37b198e5f9269b1/pyro_ppl-1.6.0-py3-none-any.whl (634kB)
|████████████████████████████████| 634kB 13.4MB/s eta 0:00:01
Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.7/dist-packages (from pyro-ppl) (3.3.0)
Collecting pyro-api>=0.1.1
Downloading https://files.pythonhosted.org/packages/fc/81/957ae78e6398460a7230b0eb9b8f1cb954c5e913e868e48d89324c68cec7/pyro_api-0.1.2-py3-none-any.whl
Requirement already satisfied: torch>=1.8.0 in /usr/local/lib/python3.7/dist-packages (from pyro-ppl) (1.8.1+cu101)
Requirement already satisfied: numpy>=1.7 in /usr/local/lib/python3.7/dist-packages (from pyro-ppl) (1.19.5)
Requirement already satisfied: tqdm>=4.36 in /usr/local/lib/python3.7/dist-packages (from pyro-ppl) (4.41.1)
Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.8.0->pyro-ppl) (3.7.4.3)
Installing collected packages: pyro-api, pyro-ppl
Successfully installed pyro-api-0.1.2 pyro-ppl-1.6.0
Data
The dataset has 3 variables: (whether a country is in Africa or not), (its terrain ruggedness), and (the log GDP per capita in 2000). We want to preict from , , and . The response variable is very skewed, so we log transform it.
Ordinary least squares
We define the linear model as a simple neural network with no hidden layers. We fit it by using maximum likelihood, optimized by (full batch) gradient descent, as is standard for DNNs.
Bayesian model
To make a Bayesian version of the linear neural network, we need to use a Pyro module instead of a torch.nn.module. This lets us replace torch tensors containg the parameters with random variables, defined by PyroSample commands. We also specify the likelihood function by using a plate over the multiple observations.
Utilities
Summarize posterior
Plot posterior predictions
HMC inference
Parameter posterior
Predictive posterior
Diagonal Gaussian variational posterior
Fit
Parameter posterior
Posterior predictive
We extract posterior predictive distribution for obs, and the return value of the model (which is the mean prediction).
Scratch
Experiments with the log(sigma) term.