{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Stochastic Variational Bayes - example nonlinear model\n",
"==============================================\n",
"\n",
"This notebook implements stochastic variational Bayes for a nonlinear model. The model we will use is a bi-exponential model, i.e. we will assume our data reflects a time-dependent signal of the following form:\n",
"\n",
"$$S_{true}(t) = A_1 e^{-R_1t} + A_2 e^{-R_2t}$$\n",
"\n",
"However the actual time dependent signal $S(t)$ will be affected by additive Gaussian noise, so will have the distribution:\n",
"\n",
"$$P(S(t)) = \\frac{\\sqrt{\\beta}}{\\sqrt{2\\pi}} \\exp{\\bigg(-\\frac{\\beta}{2} (S(t) - S_{true}(t))^2}\\bigg)$$\n",
"\n",
"Given $S(t)$ our aim will be to infer the values of $A_1$, $A_2$, $R_1$, $R_2$ and $\\beta$.\n",
"\n",
"Here's how we can generate some sample data from this model in Python:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"# Ground truth parameters\n",
"# We infer the precision, BETA, but it is useful to\n",
"# derive the variance and standard deviation from it\n",
"A1_TRUTH = 10.0\n",
"A2_TRUTH = 10.0\n",
"R1_TRUTH = 10.0\n",
"R2_TRUTH = 1.0\n",
"BETA_TRUTH = 1.0\n",
"VAR_TRUTH = 1/BETA_TRUTH\n",
"STD_TRUTH = np.sqrt(VAR_TRUTH)\n",
"\n",
"# Observed data samples are generated by Numpy from the ground truth\n",
"# Gaussian distribution. Reducing the number of samples should make\n",
"# the inference less 'confident' - i.e. the output variances for\n",
"# MU and BETA will increase\n",
"N = 200\n",
"T = np.linspace(0, 5, N)\n",
"\n",
"DATA_CLEAN = A1_TRUTH * np.exp(-R1_TRUTH * T) + A2_TRUTH * np.exp(-R2_TRUTH*T)\n",
"DATA = DATA_CLEAN + np.random.normal(0, STD_TRUTH, [N])\n",
"print(\"Data samples are:\")\n",
"print(DATA)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can plot this data to illustrate the true signal (green line) and the measured data (red crosses):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from matplotlib import pyplot as plt\n",
"plt.figure()\n",
"plt.plot(DATA, \"rx\")\n",
"plt.plot(DATA_CLEAN, \"g\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As with the single Gaussian example we will use a multivariate normal distribution as our prior and approximate posterior distributions. \n",
"\n",
"One difference here is that we will choose to infer the log of the decay rate parameters $R_1$ and $R_2$. This is because if these parameters are allowed to become negative the model prediction will become an exponential growth and can easily lead to numerical errors.\n",
"\n",
"We will still choose our priors to be relatively uninformative as follows:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a0 = 1.0\n",
"v0 = 100000.0\n",
"r0 = 0.0\n",
"u0 = 10.0\n",
"b0 = 0.0\n",
"w0 = 10.0\n",
"print(\"Priors: Amplitude mean=%f, variance=%f\" % (a0, v0))\n",
"print(\" Log decay rate mean=%f, variance=%f\" % (r0, u0))\n",
"print(\" Log noise variance mean=%f, variance=%f\" % (b0, w0))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The posterior will be defined in the same way as for the single Gaussian example, however we need to account for the increased number of parameters we are inferring. We will initialize the posterior with the prior values but with reduced initial variance to prevent problems with generating a representative posterior sample. Remember that the decay rates (and the noise) are being inferred as their log-values so the prior mean of 0 translates into a value of 1."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" import tensorflow.compat.v1 as tf\n",
"except ImportError:\n",
" import tensorflow as tf\n",
"\n",
"# Number of parameters - 4 for the biexponential + noise\n",
"NUM_PARAMS = 4 + 1\n",
"\n",
"data = tf.constant(DATA, dtype=tf.float32)\n",
"prior_means = tf.constant([a0, r0, a0, r0, b0], dtype=tf.float32)\n",
"prior_covariance = tf.diag(tf.constant([v0, u0, v0, u0, w0], dtype=tf.float32))\n",
"\n",
"post_means_init = prior_means\n",
"post_covariance_init = np.identity(NUM_PARAMS, dtype=np.float32)\n",
"\n",
"chol_off_diag = tf.Variable(np.zeros(post_covariance_init.shape), dtype=tf.float32)\n",
"# Comment in this line if you do NOT want to infer parameter covariances\n",
"#chol_off_diag = tf.constant([[0, 0], [0, 0]], dtype=tf.float32)\n",
"chol_log_diag = tf.Variable(tf.log(tf.diag_part(post_covariance_init)), dtype=tf.float32)\n",
"chol_diag = tf.diag(tf.sqrt(tf.exp(chol_log_diag)))\n",
"post_covariance_chol = tf.add(chol_diag, tf.matrix_band_part(chol_off_diag, -1, 0))\n",
"\n",
"post_covariance = tf.matmul(tf.transpose(post_covariance_chol), post_covariance_chol)\n",
"post_means = tf.Variable(post_means_init, dtype=tf.float32)\n",
"\n",
"sess = tf.Session()\n",
"sess.run(tf.initialize_all_variables())\n",
"print(\"Initial posterior mean: %s\" % sess.run(post_means))\n",
"print(\"Initial posterior covariance:\\n%s\" % sess.run(post_covariance))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The code to generate a posterior sample is unchanged except for the number of parameters:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Number of samples from the posterior\n",
"S=5\n",
"\n",
"# eps is a sample from a Gaussian with mean 0 and variance 1\n",
"eps = tf.random_normal((NUM_PARAMS, S), 0, 1, dtype=tf.float32)\n",
"\n",
"# Start off each sample with the current posterior mean\n",
"# post_samples is now a tensor of shape [NUM_PARAMS, n_samples]\n",
"samples = tf.tile(tf.reshape(post_means, [NUM_PARAMS, 1]), [1, S])\n",
"\n",
"# Now add the random sample scaled by the covariance\n",
"post_samples = tf.add(samples, tf.matmul(post_covariance_chol, eps))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In calculating the reconstruction cost we need to calculate the log likelihood of the data given a set of model parameters. We do this by observing that any difference between the biexponential model prediction (given these parameters) and the actual noisy data must be a result of the Gaussian noise - hence the likelihood is simply the likelihood of drawing these differences from the Gaussian noise distribution:\n",
"\n",
"$$\\log P(\\textbf{y} | A_1; A_2; r_1; r_2; \\beta) = \\frac{1}{2} \\bigg( N \\log \\beta - \\sum{\\frac{(y_n - M_n)^2}{\\beta}}\\bigg)$$\n",
"\n",
"Here $M_n$ is the model prediction for the nth data point which is calculated by evaluating the biexponential model for the given parameters $A_1$, $A_2$, $r_1$ and $r_2$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# These are our sample of values for the model parameters\n",
"a1 = tf.reshape(post_samples[0], [-1, 1])\n",
"r1 = tf.exp(tf.reshape(post_samples[1], [-1, 1]))\n",
"a2 = tf.reshape(post_samples[2], [-1, 1])\n",
"r2 = tf.exp(tf.reshape(post_samples[3], [-1, 1]))\n",
"\n",
"# Get the current estimate of the noise variance remembering that\n",
"# we are inferring the log of the noise precision, beta\n",
"log_noise_var = -post_samples[4]\n",
"noise_var = tf.exp(log_noise_var)\n",
"\n",
"# Each sample value predicts the full set of values in the data sample.\n",
"# For our constant-signal model, the prediction is simply a set of \n",
"# constant values. The prediction tensor will have shape [S, N]\n",
"# where S is the sample size and N is the number of data values\n",
"t = tf.reshape(tf.constant(T, dtype=tf.float32), [1, -1])\n",
"prediction = a1*tf.exp(-r1*t) + a2*tf.exp(-r2*t)\n",
"diff = tf.reshape(data, [1, -1]) - prediction\n",
"\n",
"# To calculate the likelihood we need the sum of the squared difference between the data \n",
"# and the prediction. This gives a value for each posterior sample so has shape [S]\n",
"sum_square_diff = tf.reduce_sum(tf.square(diff), axis=1)\n",
"\n",
"# Now we calculate the likelihood for each posterior sample (shape [S])\n",
"# Note that we are ignoring constant factors such as 2*PI here as they \n",
"# are just an fixed offset and do not affect the optimization \n",
"log_likelihood = 0.5 * (-log_noise_var * tf.to_float(N) - sum_square_diff / noise_var)\n",
"\n",
"# Finally to evaluate the expectation value we take the mean across all the posterior\n",
"# samples. The negative of this is the reconstruction loss\n",
"reconstr_loss = -tf.reduce_mean(log_likelihood)\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For the latent loss we will again use the analytic expression for the K-L divergence of two MVN distributions with a slight modification to the previous code to account for the different number of parameters (5 vs 2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"C = post_covariance\n",
"C0 = prior_covariance\n",
"C0_inv = tf.matrix_inverse(C0)\n",
"\n",
"# m - m0 as row and column vectors\n",
"m_minus_m0 = tf.reshape(tf.subtract(post_means, prior_means), [-1, 1])\n",
"m_minus_m0_T = tf.reshape(tf.subtract(post_means, prior_means), [1, -1])\n",
"\n",
"term1 = tf.trace(tf.matmul(C0_inv, C))\n",
"term2 = -tf.log(tf.matrix_determinant(C) / tf.matrix_determinant(C0))\n",
"\n",
"# Size of the MVN distribution\n",
"term3 = -NUM_PARAMS\n",
"term4 = tf.matmul(tf.matmul(m_minus_m0_T, C0_inv), m_minus_m0)\n",
" \n",
"latent_loss = 0.5 * (term1 + term2 + term3 + term4)\n",
"\n",
"cost = reconstr_loss + latent_loss\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally we ask TensorFlow to minimise the total cost iteratively:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"optimizer = tf.train.AdamOptimizer(learning_rate=0.02)\n",
"minimizer = optimizer.minimize(cost)\n",
"sess.run(tf.global_variables_initializer())\n",
"\n",
"cost_history = []\n",
"for epoch in range(5000):\n",
" sess.run(minimizer)\n",
" cost_history.append(float(sess.run(cost)))\n",
" print(\"Epoch %i: cost=%f, posterior means=%s\" % (epoch+1, sess.run(cost), sess.run(post_means)))\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"final_means = sess.run(post_means)\n",
"final_covariance = sess.run(post_covariance)\n",
"print(\"Estimate for amp1: %f (variance: %f)\" % (final_means[0], final_covariance[0, 0]))\n",
"print(\"Estimate for amp2: %f (variance: %f)\" % (final_means[2], final_covariance[0, 0]))\n",
"print(\"Estimate for r1: %f\" % (np.exp(final_means[1]),))\n",
"print(\"Estimate for r2: %f\" % (np.exp(final_means[3]),))\n",
"print(\"Estimate for beta (noise): %f\" % np.exp(-final_means[4]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can plot the evolution of the total cost and compare the final model prediction against the data and the ground truth signal:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure()\n",
"plt.plot(cost_history)\n",
"plt.ylim(0, 500)\n",
"\n",
"plt.figure()\n",
"plt.plot(DATA_CLEAN, 'g')\n",
"plt.plot(DATA, 'rx')\n",
"plt.plot(sess.run(prediction[0]), 'b')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You should get a fairly smooth convergence of the cost and an inferred signal which matches the ground truth fairly closely.\n",
"\n",
"The biexponential model, despite its simplicity, is quite challenging to infer. The exponential with the higher decay rate only really affects the first few data points and with a small number of samples it is difficult to separate out this contribution from that of a single exponential. You might like to reduce the number of data samples and see at what point the optimization struggles to find the second exponential accurately. This is not really a limitation of the stochastic method - it is simply that we do not have enough information in the data to infer these values accurately.\n",
"\n",
"Other things you might want to try could include:\n",
"\n",
" - Do not infer covariance between the parameters - this should make the inference more robust as we have significantly fewer parameters to estimate\n",
" - Try inferring the decay rates directly rather than via their log values. It may not end well!\n",
" - Try modifying the learning rate and sample size to see how this affects the inference\n",
" - Maybe try implementing mini-batch processing as described in the tutorial (you will need to implement the scaling factor in the reconstruction loss definition)\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.7"
}
},
"nbformat": 4,
"nbformat_minor": 2
}