Skip to content

Instantly share code, notes, and snippets.

@kailaix
Last active December 29, 2018 20:07
Show Gist options
  • Select an option

  • Save kailaix/c79a44ede5a2e128e198b5d701100cba to your computer and use it in GitHub Desktop.

Select an option

Save kailaix/c79a44ede5a2e128e198b5d701100cba to your computer and use it in GitHub Desktop.
A working example of Probabilistic Programming using Edward
# modified version from http://edwardlib.org/tutorials/
from tensorflow_probability import edward2 as ed
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
def logistic_regression(features):
coeffs = ed.Normal(loc=0., scale=1.,
sample_shape=features.shape[1], name="coeffs")
outcomes = ed.Bernoulli(logits=tf.tensordot(features, coeffs, [[1], [0]]),
name="outcomes")
return outcomes
log_joint = ed.make_log_joint_fn(logistic_regression)
features_value = np.random.random([3, 2]).astype(np.float32)
outcomes_value = np.random.random([3]).astype(np.float32)
def target_log_prob_fn(coeffs_value):
return log_joint(features_value,coeffs=coeffs_value, outcomes=outcomes_value)
num_results = 5000
num_burnin_steps = 3000
states, kernel_results = tfp.mcmc.sample_chain(
num_results=num_results,
num_burnin_steps=num_burnin_steps,
current_state=[
tf.zeros([2])
],
kernel=tfp.mcmc.HamiltonianMonteCarlo(
target_log_prob_fn=target_log_prob_fn,
step_size=0.4,
num_leapfrog_steps=3))
sess = tf.Session()
sess.run(states)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment