Worked Example: Simulate from a Multivariate Gaussian

Jack Baker

In this example we use the package to infer the mean of a 2d Gaussian using stochastic gradient Langevin dynamics. So we assume we have independent and identically distributed data \(x_1, \dots, x_N\) with \(X_i | \theta \sim N( \theta, I_2 )\), and we want to infer \(\theta\).

First, let’s simulate the data with the following code, we set \(N\) to be \(10^4\)

library(sgmcmc)
library(MASS)
# Declare number of observations
N = 10^4
# Set theta to be 0 and simulate the data
theta = c( 0, 0 )
Sigma = diag(2)
X = mvrnorm( N, theta, Sigma )
dataset = list("X" = X)

In the last line we defined the dataset as it will be input to the relevant sgmcmc function. A lot of the inputs to functions in sgmcmc are defined as lists. This improves flexibility by enabling models to be specified with multiple parameters, datasets and allows separate tuning constants to be set for each parameter. We assume that observations are always accessed on the first dimension of each object, i.e. the point \(x_i\) is located at X[i,] rather than X[,i]. Similarly the observation \(i\) from a 3d object Y would be located at Y[i,,].

The parameters are declared very similarly, but this time the value associated with each entry is its starting point. We have one parameter theta, which we’ll just start at 0.

params = list( "theta" = c( 0, 0 ) )

Now we’ll define the functions logLik and logPrior. It should now become clear why the list names come in handy. The function logLik should take two parameters as input: params and dataset. These parameters will be lists with the same names as those you defined for params and dataset earlier. There is one difference though, the objects in the lists will have automatically been converted to TensorFlow objects for you. The params list will contain TensorFlow tensor variables; the dataset list will contain TensorFlow placeholders. The logLik function should take these lists as input and return the value of the log-likelihood function as a tensor at point params given data dataset. The function should do this using TensorFlow operations, as this allows the gradient to be automatically calculated; it also allows the wide range of distribution objects as well as matrix operations that TensorFlow provides to be taken advantage of. A tutorial of TensorFlow for R is beyond the scope of this article, for more details we refer the reader to the website of TensorFlow for R. With this in place we can define the logLik function as follows

logLik = function( params, dataset ) {
    # Declare distribution of each observation
    SigmaDiag = c( 1, 1 )
    baseDist = tf$contrib$distributions$MultivariateNormalDiag( params$theta, SigmaDiag )
    # Declare log-likelihood function and return
    logLik = tf$reduce_sum( baseDist$log_prob( dataset$X ) )
    return( logLik )
}

So this function basically states that our likelihood is \(\sum_{i=1}^N \log \mathcal N( x_i | \theta, I_2 )\), where \(\mathcal N( x | \mu, \Sigma )\) is a Gaussian density at \(x\) with mean \(\mu\) and variance \(\Sigma\). Most of the time just specifying the constants in these functions, such as SigmaDiag as R objects will be fine. But there are sometimes issues when these constants get automatically converted to tf$float64 objects by TensorFlow rather than tf$float32. If you run into errors involving tf$float64 then force the constants to be input as tf$float32 by using SigmaDiag = tf$constant( c( 1, 1 ), dtype = tf$float32 ).

Next we want to define our log-prior density, which we assume is \(\log p( \theta_j ) = \log \mathcal N(\theta_j | 0,10)\), for each dimension \(j\) of \(\theta\). Similar to logLik, logPrior is defined as a function with input params. In our case the definition is

logPrior = function( params ) {
    baseDist = tf$contrib$distributions$Normal( 0, 10 )
    logPrior = tf$reduce_sum( baseDist$log_prob( params$theta ) )
    return( logPrior )
}

Before we begin running our SGLD algorithm, we need to specify the stepsize and minibatch size. A stepsize is required for each parameter, so this must be a list of numbers with names that are exactly the same as each of the parameters. The minibatch size is simply a number that is less than \(N\), or a number between 0 and 1 which will be taken to be the proportion of \(N\). It specifies how many observations are used in each iteration of SGMCMC, it is a trade off between accuracy and speed. The default is minibatchSize = 0.01, we’ll set it to be 100.

stepsize = list( "theta" = 1e-5 )
n = 100

The stepsize parameters may require a bit of tuning before you get good results. The shorthand stepsize = 1e-5 can be used, which would set the stepsize of all parameters to be 1e-5.

Now we can run our SGLD algorithm using the sgmcmc function sgld, which returns a list of Markov chains for each parameter as output. Use the argument verbose = FALSE to hide the output of the function

chains = sgld( logLik, dataset, params, stepsize, logPrior = logPrior, minibatchSize = n)
## Iteration: 100       Log posterior estimate: -28626.94140625
## Iteration: 200       Log posterior estimate: -29058.177734375
## Iteration: 300       Log posterior estimate: -25777.82421875
## Iteration: 400       Log posterior estimate: -27794.470703125
## Iteration: 500       Log posterior estimate: -27067.728515625
## Iteration: 600       Log posterior estimate: -29135.638671875
## Iteration: 700       Log posterior estimate: -29178.91015625
## Iteration: 800       Log posterior estimate: -29636.662109375
## Iteration: 900       Log posterior estimate: -28085.88671875
## Iteration: 1000      Log posterior estimate: -27630.6953125
## Iteration: 1100      Log posterior estimate: -27530.51171875
## Iteration: 1200      Log posterior estimate: -29167.048828125
## Iteration: 1300      Log posterior estimate: -26678.861328125
## Iteration: 1400      Log posterior estimate: -28098.701171875
## Iteration: 1500      Log posterior estimate: -29300.859375
## Iteration: 1600      Log posterior estimate: -28057.310546875
## Iteration: 1700      Log posterior estimate: -29300.236328125
## Iteration: 1800      Log posterior estimate: -29086.16796875
## Iteration: 1900      Log posterior estimate: -28774.5703125
## Iteration: 2000      Log posterior estimate: -29348.990234375
## Iteration: 2100      Log posterior estimate: -28756.53125
## Iteration: 2200      Log posterior estimate: -27343.869140625
## Iteration: 2300      Log posterior estimate: -27234.775390625
## Iteration: 2400      Log posterior estimate: -28497.1171875
## Iteration: 2500      Log posterior estimate: -27178.208984375
## Iteration: 2600      Log posterior estimate: -29561.13671875
## Iteration: 2700      Log posterior estimate: -28246.884765625
## Iteration: 2800      Log posterior estimate: -30588.962890625
## Iteration: 2900      Log posterior estimate: -27885.46484375
## Iteration: 3000      Log posterior estimate: -28343.39453125
## Iteration: 3100      Log posterior estimate: -27218.8828125
## Iteration: 3200      Log posterior estimate: -27698.759765625
## Iteration: 3300      Log posterior estimate: -29151.634765625
## Iteration: 3400      Log posterior estimate: -28496.982421875
## Iteration: 3500      Log posterior estimate: -28626.890625
## Iteration: 3600      Log posterior estimate: -28867.75390625
## Iteration: 3700      Log posterior estimate: -28064.51171875
## Iteration: 3800      Log posterior estimate: -30781.642578125
## Iteration: 3900      Log posterior estimate: -27467.203125
## Iteration: 4000      Log posterior estimate: -27361.41796875
## Iteration: 4100      Log posterior estimate: -28546.640625
## Iteration: 4200      Log posterior estimate: -28366.576171875
## Iteration: 4300      Log posterior estimate: -28800.5234375
## Iteration: 4400      Log posterior estimate: -27709.37890625
## Iteration: 4500      Log posterior estimate: -28462.0625
## Iteration: 4600      Log posterior estimate: -27797.51953125
## Iteration: 4700      Log posterior estimate: -28235.638671875
## Iteration: 4800      Log posterior estimate: -29065.5625
## Iteration: 4900      Log posterior estimate: -27581.900390625
## Iteration: 5000      Log posterior estimate: -28418.564453125
## Iteration: 5100      Log posterior estimate: -29036.09765625
## Iteration: 5200      Log posterior estimate: -29703.447265625
## Iteration: 5300      Log posterior estimate: -29741.708984375
## Iteration: 5400      Log posterior estimate: -27618.271484375
## Iteration: 5500      Log posterior estimate: -30289.142578125
## Iteration: 5600      Log posterior estimate: -28034.564453125
## Iteration: 5700      Log posterior estimate: -26247.2421875
## Iteration: 5800      Log posterior estimate: -27731.171875
## Iteration: 5900      Log posterior estimate: -28287.90625
## Iteration: 6000      Log posterior estimate: -27946.07421875
## Iteration: 6100      Log posterior estimate: -29098.95703125
## Iteration: 6200      Log posterior estimate: -29105.373046875
## Iteration: 6300      Log posterior estimate: -28371.5859375
## Iteration: 6400      Log posterior estimate: -28565.68359375
## Iteration: 6500      Log posterior estimate: -29220.9609375
## Iteration: 6600      Log posterior estimate: -28692.478515625
## Iteration: 6700      Log posterior estimate: -27246.541015625
## Iteration: 6800      Log posterior estimate: -27782.23046875
## Iteration: 6900      Log posterior estimate: -26895.02734375
## Iteration: 7000      Log posterior estimate: -27317.0234375
## Iteration: 7100      Log posterior estimate: -29982.828125
## Iteration: 7200      Log posterior estimate: -29488.578125
## Iteration: 7300      Log posterior estimate: -28719.162109375
## Iteration: 7400      Log posterior estimate: -29152.7265625
## Iteration: 7500      Log posterior estimate: -27468.541015625
## Iteration: 7600      Log posterior estimate: -27825.431640625
## Iteration: 7700      Log posterior estimate: -28260.8984375
## Iteration: 7800      Log posterior estimate: -29331.818359375
## Iteration: 7900      Log posterior estimate: -28610.326171875
## Iteration: 8000      Log posterior estimate: -29783.662109375
## Iteration: 8100      Log posterior estimate: -29142.814453125
## Iteration: 8200      Log posterior estimate: -29466.330078125
## Iteration: 8300      Log posterior estimate: -28142.02734375
## Iteration: 8400      Log posterior estimate: -27282.572265625
## Iteration: 8500      Log posterior estimate: -30441.251953125
## Iteration: 8600      Log posterior estimate: -27446.671875
## Iteration: 8700      Log posterior estimate: -27108.12109375
## Iteration: 8800      Log posterior estimate: -27575.259765625
## Iteration: 8900      Log posterior estimate: -30440.41015625
## Iteration: 9000      Log posterior estimate: -29613.45703125
## Iteration: 9100      Log posterior estimate: -27839.2734375
## Iteration: 9200      Log posterior estimate: -29334.958984375
## Iteration: 9300      Log posterior estimate: -28982.40234375
## Iteration: 9400      Log posterior estimate: -27894.71484375
## Iteration: 9500      Log posterior estimate: -27743.41015625
## Iteration: 9600      Log posterior estimate: -27914.037109375
## Iteration: 9700      Log posterior estimate: -27123.984375
## Iteration: 9800      Log posterior estimate: -27944.638671875
## Iteration: 9900      Log posterior estimate: -29133.224609375
## Iteration: 10000     Log posterior estimate: -27034.345703125

Finally we’ll plot the results after removing burn-in

library(ggplot2)
burnIn = 10^3
thetaOut = as.data.frame( chains$theta[-c(1:burnIn),] )
ggplot( thetaOut, aes( x = V1, y = V2 ) ) +
    stat_density2d( size = 1.5 )

There are lots of other sgmcmc algorithms implemented in exactly the same way, such as sghmc and sgnht; as well as their control variate counterparts (sgldcv, sghmccv and sgnhtcv) for improved efficiency, which take the additional small numeric input optStepsize, the stepsize of the initial optimization step to find the MAP parameters.