gpt4 book ai didi

python - 这些功能是等价的吗?

转载 作者:行者123 更新时间:2023-12-03 18:51:20 31 4
gpt4 key购买 nike

我正在构建一个利用 T-distribution noise 的神经网络.我正在使用 numpy 库中定义的函数 np.random.standard_t和 tensorflow 中定义的一个 tf.distributions.StudentT .第一个函数的文档链接是 here第二个函数是 here .我正在使用上述功能,如下所示:

a = np.random.standard_t(df=3, size=10000)  # numpy's function

t_dist = tf.distributions.StudentT(df=3.0, loc=0.0, scale=1.0)
sess = tf.Session()
b = sess.run(t_dist.sample(10000))

在为 Tensorflow 实现提供的文档中,有一个名为 scale 的参数。其描述为

The scaling factor(s) for the distribution(s). Note that scale is not technically the standard deviation of this distribution but has semantics more similar to standard deviation than variance.



我已经设置了 scale成为 1.0但我无法确定这些是否指同一分布。

有人可以帮我验证一下吗?谢谢

最佳答案

我会说它们是,因为在这两种情况下,它们的抽样定义几乎完全相同。这就是 tf.distributions.StudentT 的采样方式被定义为:

def _sample_n(self, n, seed=None):
# The sampling method comes from the fact that if:
# X ~ Normal(0, 1)
# Z ~ Chi2(df)
# Y = X / sqrt(Z / df)
# then:
# Y ~ StudentT(df).
seed = seed_stream.SeedStream(seed, "student_t")
shape = tf.concat([[n], self.batch_shape_tensor()], 0)
normal_sample = tf.random.normal(shape, dtype=self.dtype, seed=seed())
df = self.df * tf.ones(self.batch_shape_tensor(), dtype=self.dtype)
gamma_sample = tf.random.gamma([n],
0.5 * df,
beta=0.5,
dtype=self.dtype,
seed=seed())
samples = normal_sample * tf.math.rsqrt(gamma_sample / df)
return samples * self.scale + self.loc # Abs(scale) not wanted.

所以它是一个标准正态样本除以参数 df的卡方样本的平方根。除以 df .卡方样本作为 Gamma 样本,参数 0.5 * df并评价 0.5 ,这是等价的(卡方是 Gamma 的特例)。 scale值,如 loc ,仅在最后一行起作用,作为在某个点和规模“重新定位”分布样本的一种方式。当 scale是一和 loc为零,他们什么都不做。

这是 np.random.standard_t 的实现:

double legacy_standard_t(aug_bitgen_t *aug_state, double df) {
double num, denom;

num = legacy_gauss(aug_state);
denom = legacy_standard_gamma(aug_state, df / 2);
return sqrt(df / 2) * num / sqrt(denom);
})

所以本质上是一样的,稍微改写一下。这里我们还有一个形状为 df / 2 的 Gamma 但它是标准的(等级一)。然而,失踪的 0.5现在由分子为 / 2sqrt .所以它只是移动数字。这里没有 scaleloc , 尽管。

事实上,不同之处在于,在 TensorFlow 的情况下,分布确实是 noncentral t-distribution .一个简单的经验证明,它们对于 loc=0.0 是相同的和 scale=1.0是绘制两个分布的直方图,看看它们看起来有多接近。

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
np.random.seed(0)
t_np = np.random.standard_t(df=3, size=10000)
with tf.Graph().as_default(), tf.Session() as sess:
tf.random.set_random_seed(0)
t_dist = tf.distributions.StudentT(df=3.0, loc=0.0, scale=1.0)
t_tf = sess.run(t_dist.sample(10000))
plt.hist((t_np, t_tf), np.linspace(-10, 10, 20), label=['NumPy', 'TensorFlow'])
plt.legend()
plt.tight_layout()
plt.show()

输出:

Distribution histograms

那看起来很接近。显然,从统计样本的角度来看,这不是任何一种证明。如果您仍然不相信,可以使用一些统计工具来测试一个样本是来自某个分布还是两个样本来自同一分布。

关于python - 这些功能是等价的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59032933/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com