如何使用 pymc3 指定伯努利分布的大小?

How to specify size for bernoulli distribution with pymc3?

在尝试通过 pymc 中的 Bayesian Methods for Hackers 时,我遇到了这段代码:

first_coin_flips = pm.Bernoulli("first_flips", 0.5, size=N)

我试图用以下内容将其转换为 pymc3,但它只是 returns 一个 numpy 数组,而不是张量 (?):

first_coin_flips = pm.Bernoulli("first_flips", 0.5).random(size=50)

大小之所以重要是因为它稍后会在确定性变量中使用。这是我到目前为止的全部代码:

import pymc3 as pm
import matplotlib.pyplot as plt
import numpy as np
import mpld3
import theano.tensor as tt

model = pm.Model()
with model:
    N = 100
    p = pm.Uniform("cheating_freq", 0, 1)
    true_answers = pm.Bernoulli("truths", p)
    print(true_answers)
    first_coin_flips = pm.Bernoulli("first_flips", 0.5)
    second_coin_flips = pm.Bernoulli("second_flips", 0.5)
    #  print(first_coin_flips.value)

    # Create model variables
    def calc_p(true_answers, first_coin_flips, second_coin_flips):
        observed = first_coin_flips * true_answers + (1-first_coin_flips) * second_coin_flips
        # NOTE: Where I think the size param matters, since we're dividing by it
        return observed.sum() / float(N)

    calced_p = pm.Deterministic("observed", calc_p(true_answers, first_coin_flips, second_coin_flips))
    step = pm.Metropolis(model.free_RVs)
    trace = pm.sample(1000, tune=500, step=step)
    pm.traceplot(trace)

    html = mpld3.fig_to_html(plt.gcf())
    with open("output.html", 'w') as f:
        f.write(html)
        f.close()

并且输出:

硬币翻转和统一 cheating_freq 输出看起来正确,但 observed 对我来说看起来不像任何东西,我认为这是因为我没有翻译 size 参数正确。

指定伯努利分布大小的 pymc3 方法是使用 shape 参数,例如:

first_coin_flips = pm.Bernoulli("first_flips", 0.5, shape=N)