如何正确使用张量流概率对随机变量函数进行抽样?

2024-10-02 08:30:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我对张量流概率中双射体的特征很感兴趣,所以我试着从一个由全要素生产率. 你知道吗

我只提供了我的测试代码blow,这里我提供了一些细节:我曾经测试过的例子是Chièu平方分布。我用两种不同的方法得到样本Chi(2)分布:(1)直接使用tensorflow中的Chi(2)api;(2)使用全要素生产率根据Chi(2)与标准正态分布(N(0,1))的关系:如果X,Y iid~N(0,1),Z=g(X,Y)=X^2+Y^2,则Z~Chi(2)。结果表明,两组样本的均值基本相等,但两个标准差相差较大,谁能告诉我错在哪里,如何正确使用tfu概率?你知道吗

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

这里是我的结果,原点是用tf中的Chi(2)api直接计算出来的,左边的图是原点的结果,右边的图是tf得到的_概率.双射体. 你知道吗

enter image description here


Tags: importtfasoriginmean概率sessstd

热门问题