我刚刚回答了一个类似的问题使用 Tensorflow Probability 的 RandomWalkMetropolis 函数执行 RandomWalk 步骤
RandomWalkMetropolis
接受一个构造函数参数new_state_fn
,这是一个自定义提案函数,它使用先前的状态并返回一个提案。
# TF/TFP Imports
!pip install --quiet tfp-nightly tf-nightly
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
import matplotlib.pyplot as plt
def log_prob(x):
return tfd.Normal(0, 1).log_prob(x)
def custom_proposal(state, extra):
return state + tfd.Uniform(-.5, .75).sample()
kernel = tfp.mcmc.RandomWalkMetropolis(log_prob, new_state_fn=custom_proposal)
state = tfd.Normal(0, 1).sample()
extra = kernel.bootstrap_results(state)
samples = []
for _ in range(1000):
state, extra = kernel.one_step(state, extra)
samples.append(state)
plt.hist(samples, bins=20)