human
Give me a code to 2 given the following:
2.4.5. Markov chain Monte Carlo
We can estimate the posterior using a Markov chain Monte Carlo (MCMC) technique, which will be explained further in Chapter 9. An outline of the algorithm follows. It is written primarily in numpy to illustrate the steps you would take.
n_samples = 1000
p = np.zeros(n_samples)
p[0] = 0.5
W = 6
L = 3
for i in range(1, n_samples):
    p_new = tfd.Normal(loc=p[i - 1], scale=0.1).sample(1)
    if p_new &lt.
0:
        p_new = -p_new
    if p_new &gt.
1:
        p_new = 2 - p_new
    q0 = tfd.Binomial(total_count=W+L, probs=p[i - 1]).prob(W)
    q1 = tfd.Binomial(total_count=W+L, probs=p_new).prob(W)
    if stats.uniform.rvs(0, 1) &lt.
q1 / q0:
        p[i] = p_new
    else:
        p[i] = p[i - 1]
But to actually use Metropolis Hastings in TFP, you can use the mcmc library. The version of the algorithm that we want is called RandomWalkMetropolis.
Code 2.8"
Please write code following the instructions in jupyter notebook style.
assistant
#Here is code to 2.

@tf.function
def do_sampling():
  def get_model_log_prob(probs):
    return tfd.Binomial(total_count=W + L, probs=probs).log_prob(W)

  sampling_kernel = tfp.mcmc.RandomWalkMetropolis(get_model_log_prob)

  return tfp.mcmc.sample_chain(
      num_results=5000,
      current_state=.5,
      kernel=sampling_kernel,
      num_burnin_steps=500,
    trace_fn=None, 
  )

samples = do_sampling()