Я хочу использовать API TensorFlow_probability, чтобы выполнить выборку. Возьмем двумерное распределение Гаусса в качестве примера. Я не мог найти хороший учебник. Код, который я изменил с сайта TensorFlow, не работает.
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
tf.enable_eager_execution()
def unnormalized_log_prob(x): # Two dimensional unnormalized Gaussian
#dim x= batch size,vec size?
kernel = tf.Tensor([[1.,0.],[0.,10.]], dtype = tf.float32)
mu = tf.Tensor([1.,5.], dtype = tf.float32)
return -0.5*tf.matmul((x-mu), tf.matmul(tf.inverse(kernel), tf.transpose(x-mu)))
# Initialize the HMC transition kernel.
num_results = int(10e3)
num_burnin_steps = int(1e3)
adaptive_hmc = tfp.mcmc.SimpleStepSizeAdaptation(
tfp.mcmc.HamiltonianMonteCarlo(
target_log_prob_fn=unnormalized_log_prob,
num_leapfrog_steps=3,
step_size=1.),
num_adaptation_steps=int(num_burnin_steps * 0.8))
# Run the chain (with burn-in).
@tf.function
def run_chain():
# Run the chain (with burn-in).
samples, is_accepted = tfp.mcmc.sample_chain(
num_results=num_results,
num_burnin_steps=num_burnin_steps,
current_state=np.array([[1.,1.],[3.,3.],[5.,5.]], dtype=np.float32),
kernel=adaptive_hmc,
trace_fn=lambda _, pkr: pkr.inner_results.is_accepted)
sample_mean = tf.reduce_mean(samples)
sample_stddev = tf.math.reduce_std(samples)
is_accepted = tf.reduce_mean(tf.cast(is_accepted, dtype=tf.float32))
return samples, sample_mean, sample_stddev, is_accepted
samples, sample_mean, sample_stddev, is_accepted = run_chain()
print('mean:{:.4f} stddev:{:.4f} acceptance:{:.4f}'.format(
sample_mean.numpy(), sample_stddev.numpy(), is_accepted.numpy()))
Я ожидаю, что если я захочу взять три цепочки выборок из начального состояния [1., 1.] И [3., 3.], [5., 5.] Соответственно, он вернет тензор измерения [ 3, 10000,2]