【问题标题】:Solving dice throwing and coin tossing problem using tensorflow probability, variance is wrong使用张量流概率解决掷骰子和掷硬币问题,方差是错误的
【发布时间】:2019-02-07 20:02:43
【问题描述】:

我对统计学不是很精通,我正在努力学习。所以请多多包涵。我在 Quora 看到了this 的问题——基本上是这样的——

如果结果是奇数则掷出公平的骰子,然后掷出公平的硬币 被扔了 3 次。否则,如果结果是偶数,则公平 硬币将被抛 2 次。在这两种情况下,都会计算正面数。 获得的#个正面的方差是多少?

我想使用 Python 和 tf-probability 来解决它。这就是我所做的 -

import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
tf.enable_eager_execution()
probs = [1/6.] * 6

dices = tfp.distributions.Multinomial(total_count=1000, probs=probs)

n = dices.sample()

HEAD = 1
TAIL = 0
l = list(n.numpy())
heads_even = []
heads_odd = []
for i, nums in enumerate(l):
    mul_by = 3 if (i + 1) % 2 != 0 else 2
    tosses = tfp.distributions.Bernoulli(probs=0.5)
    coin_flip_data = tosses.sample(nums * mul_by)
    l2 = coin_flip_data.numpy()
    unique, counts = np.unique(l2, return_counts=True)
    head_tails = dict(zip(unique, counts))
    if (i + 1) % 2 != 0:
        heads_odd.append(head_tails[HEAD])
    else:
        heads_even.append(head_tails[HEAD])

total_heads = heads_odd + heads_even
final_nd_arr = np.array(total_heads)
print(final_nd_arr.var())

但是,final_nd_arr.var() 当然与实际答案相去甚远(它是 2089.805555555556),0.68(正如人们在 Quora 答案中提到的那样)。

我无法找出我做错了什么。我该如何纠正我的错误?

任何指针都会有所帮助。提前非常感谢。

--------- 编辑

为了提供更多数据,

dices.sample() => array([169., 173., 149., 171., 175., 163.], dtype=float32)
heads_odd => [266, 210, 259]
heads_even => [176, 167, 145]
total_heads => [266, 210, 259, 176, 167, 145]

【问题讨论】:

  • 你得到什么答案?
  • 我已经编辑了问题并添加了我得到的价值。 @EdekiOkoh
  • 另外,请记住,如果您正在运行此代码,由于代码的随机性,您最后可能会得到不同的 final_nd_arr.var() 值。
  • 是的,但如果你运行足够多的时间,答案应该会收敛到相同的结果(此处为统计专业)
  • 我现在已经在问题中添加了运行中的数据。

标签: python tensorflow statistics tensorflow-probability


【解决方案1】:

您正在计算错误分布的方差。我们正在寻找的方差适用于您将一遍又一遍地掷骰子的实验,每次计算正面数量,并计算正面数量的方差。您正在代码中执行此操作,但您汇总所有掷骰子的正面总数,然后为每个可能的骰子结果计算这些总和的方差。

这将给出正确的结果。我添加了一些希望澄清它的 cmets:

import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np

tf.enable_eager_execution()

# Simulate the outcome of 1000 dice rolls
probs = [1/6.] * 6
dices = tfp.distributions.Multinomial(total_count=1000, probs=probs)
n = dices.sample()
l = list(n.numpy().astype(int))

L = []
# Loop over 6 possible dice outcomes
for i in range(len(l)):
    # Loop over the rolls for this dice outcome
    for _ in range(l[i]):
        # For each of the dice rolls,
        # Flip a coin 2 or three times
        num_tosses = 3 if (i + 1) % 2 != 0 else 2
        tosses = tfp.distributions.Bernoulli(probs=0.5)
        coin_flip_data = tosses.sample(num_tosses)

        # And count the number of heads
        num_heads = np.sum(coin_flip_data.numpy())
        L += [num_heads]

np.var(L)
> 0.668999

【讨论】:

  • 非常感谢!现在完全有道理了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多