使用 tfp.mcmc.MetropolisHastings 作为物理模型

Using tfp.mcmc.MetropolisHastings for physical model

我是 Tensorflow 的新手,想使用 Tensorflow 概率库来模拟物理问题。 Tensorflow 自带 tfp.mcmc.MetropolisHastings 函数,这是我想使用的算法。

我提供了我的初始分布。在我的例子中,这是一个二维网格,每个网格点上都有一个 'spin'(物理学并不重要,正确知道),可以是 +1 或 -1。 新状态 x' 的提议应该是其中一个自旋被翻转的旧网格,因此在一个点上 +1 变为 -1,反之亦然。我可以传递步长参数,但我的 x 不是我可以简单增加的标量。我该如何建模?有没有一种方法可以传递更新规则,而不仅仅是将值增加一定的步长?

我刚刚回答了一个类似的问题

RandomWalkMetropolis 接受构造函数参数 new_state_fn,这是一个自定义提议函数,它使用先前的状态和 returns 一个提议。

# 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)