英文:
Tensorflow distributions do not integrate/sum to 1
问题
以下是您要翻译的内容:
"I was experimenting with tensorflow-probability (tfp). I wanted to check, if the density of a Normal-distribution in tfp does integrate (sum) to one. I thought the following calculation inside the print should give me rougly 1, but instead I got 714.2143.
import tensorflow_probability as tfp
tfd = tfp.distributions
x = np.linspace(-7., 7., int(1e4), dtype=np.float64)
print(tf.reduce_sum( np.array( [tfd.Normal(loc=0, scale=1).prob(y) for y in x] )))
Output: tf.Tensor(714.2143, shape=(), dtype=float32)
What am I missing here?"
英文:
I was experimenting with tensorflow-probability (tfp). I wanted to check, if the density of a Normal-distribution in tfp does integrate (sum) to one. I thought the following calculation inside the print should give me rougly 1, but instead I got 714.2143.
import tensorflow_probability as tfp
tfd = tfp.distributions
x = np.linspace(-7., 7., int(1e4), dtype=np.float64)
print(tf.reduce_sum( np.array( [tfd.Normal(loc=0, scale=1).prob(y) for y in x] )))
Output: tf.Tensor(714.2143, shape=(), dtype=float32)
What am I missing here?
答案1
得分: 1
如果您想计算曲线下面积,即在此处对概率密度函数进行积分,您需要除以样本数量并乘以支持范围的长度:
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
tfd = tfp.distributions
num_samples = 1000
min_val = -7
max_val = 7
x = np.linspace(min_val, max_val,
num_samples,
dtype=np.float64)
dist = tfd.Normal(loc=0, scale=1)
normalized_vals = np.array([dist.prob(y) for y in x]) / num_samples * (max_val - min_val)
print(tf.reduce_sum(normalized_vals)) # 0.99899995
英文:
If you want to calculate to area under the curve, which is integrating the pdf here, you need to divide by number of samples and multiply the length of support:
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
tfd = tfp.distributions
num_samples = 1000
min_val = -7
max_val = 7
x = np.linspace(min_val, max_val,
num_samples,
dtype=np.float64)
dist = tfd.Normal(loc=0, scale=1)
normalized_vals = np.array([dist.prob(y) for y in x])/ num_samples * (max_val-(min_val))
print(tf.reduce_sum(normalized_vals)) # 0.99899995
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论