python - 使用张量流概率解决掷骰子和掷硬币问题,方差是错误的
问题描述
我对统计学不是很精通,我正在努力学习。所以请多多包涵。我在 Quora 中看到了这个问题 - 基本上说明了以下内容 -
如果结果是奇数,则掷一个公平的骰子,然后投掷一个公平的硬币 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]
解决方案
您正在计算错误分布的方差。我们正在寻找的方差适用于您将一遍又一遍地掷骰子的实验,每次计算正面的数量,并计算正面数量的方差。您正在代码中执行此操作,但是您将所有骰子掷出的正面总数相加,然后对骰子的每个可能结果取这些总和的方差。
这将给出正确的结果。我添加了一些评论,希望能澄清它:
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
推荐阅读
- python - 使用 Mock 时出现 ModuleNotFoundError
- python - 我想在一个值中使用 get_attribute 但没有“data_value”只是数字,如何使用 selenium python 获取信息?
- r - Ggiraph 不适用于圆形堆叠条形图
- java - 接口的实现/扩展何时不应返回比接口上声明的类型更具体的类型?
- google-chrome-extension - 带有 Manifest v3 的 Sandbox 中的 Chrome 扩展中的 WebAssembly
- java - 如何在 JavaFX 中使用 HBox 将某些元素放置在画布上的特定位置?
- android - Moshi 使用动态内部数据类创建 json
- ruby - 为什么在这个问题中需要 uniq?(红宝石)
- python - 根据某些值对字典进行排序
- json - 如何使用 vertx routingcontext 返回 Json 数组