如何正确使用tensorflow_probability从随机变量函数中抽样?

问题描述 投票:1回答:1

我对tensorflow_probability中的bijectors的特性很感兴趣,所以我尝试从一个由tfp.bijectors构造的随机变量函数中进行采样。

我只是提供我的测试代码打击,在这里我提供了一些detials:我以前测试的情况是Chi_square分布。我以两种不同的方式得到了Chi(2)分布的样本:(1)直接在张量流中使用Chi(2)api; (2)使用tfp.bijectors通过Chi(2)和标准正态分布(N(0,1))之间的关系:如果X,Y iid~N(0,1),Z = g(X,Y) = X ^ 2 + Y ^ 2,然后是Z~Chi(2)。我的结果显示打击,两组样本的平均值大致相等,但两个标准偏差更加不同,任何人都可以告诉我哪里出错了以及如何正确使用tf_probability?

import os

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from scipy.stats import chi2

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

tf.reset_default_graph()   # Clear computational graph before calc again!!!

tfd = tfp.distributions
tfb = tfp.bijectors

n_samples = 2000

chi2_origin = tfd.Chi2(2)
s_chi2_origin = chi2_origin.sample([n_samples])

base_normal = tfd.Normal(loc=0., scale=1.)
n_to_chi1_bij = tfb.Square()
n_to_chi2_bij = tfb.Chain([tfb.AffineScalar(shift=0., scale=2.), tfb.Square()])

target_Chi = tfd.TransformedDistribution(
    distribution=base_normal,
    bijector=n_to_chi2_bij,
    name="Chi_x_constructed"
)
s_chi1_constru = target_Chi.sample([n_samples])

with tf.Session() as sess:
    init_op = tf.local_variables_initializer()
    sess.run(init_op)
    s_chi2_origin_ = sess.run(s_chi2_origin)
    # print("Samples by Chi2_ORIGIN", s_chi2_origin_)
    print("Origin :  mean={:.4f}, std={:.4f}".
          format(s_chi2_origin_.mean(), s_chi2_origin_.std()))

    s_chi2_constru_ = sess.run(s_chi1_constru)
    # print("Samples by Chi1_CONSTRU:", s_chi1_constru_[-5:-1])
    print("Constru:  mean={:.4f}, std={:.4f}".
          format(s_chi2_constru_.mean(), s_chi2_constru_.std()))

x = np.arange(0, 15, .5)
y = chi2(2).pdf(x)

fig, (ax0, ax1) = plt.subplots(1, 2, sharey=True, figsize=(6,4))
ax0.hist(s_chi2_origin_, bins='auto', density=True)
ax0.plot(x, y, 'r-')
ax1.hist(s_chi2_constru_, bins=200, density=True)
ax1.plot(x, y, 'r-')
plt.show()

这是我的结果,原点线是直接由Chi(2)api在tf中计算的,左图是原点结果;构造线和右图是由tf_probability.bijectors获得的。

enter image description here

python tensorflow probability probability-density tensorflow-probability
1个回答
0
投票

我认为你的链中的条目已经颠倒了。它们被称为从右到左,如函数组成的数学符号。

© www.soinside.com 2019 - 2024. All rights reserved.