How to declare a binomial distribution variable with changing parameters in pymc3

Viewed 85

I would like to declare a binomial variable that is intermediate and not observed, used to compute another deterministic variable that is observed. If I had the observations, I could declare the following and get the model pictured below:

import pymc3
with pymc3.Model() as model:
    rate = pymc3.Beta('rate', alpha=2, beta=2)
    input_var = pymc3.Data('input_var', [1, 2, 3])
    intermediate_var = pymc3.Binomial('intermediate_var', n=input_var, p=rate, observed=[1, 1, 1])
    output_var = pymc3.Deterministic('output_var', intermediate_var)
pymc3.model_to_graphviz(model)

example_model

But, I don't have observations of the intermediate variable, only of the output variable, and this does not work, giving wrong number of dimensions error:

import pymc3
with pymc3.Model() as model:
    rate = pymc3.Beta('rate', alpha=2, beta=2)
    input_var = pymc3.Data('input_var', [1, 2, 3])
    intermediate_var = pymc3.Binomial('intermediate_var', n=input_var, p=rate)
    output_var = pymc3.Deterministic('output_var', intermediate_var)

Obviously, this is an innocent example, and someone could say that how is that I have observations of the output variable and not the intermediate one in this case, but in my model, the output variable depends on several intermediate variables that depend in other input variables as well. This is a minimal example trying to explain what I want to do.

The same happens if I change the Deterministic by a Normal with observed data.

1 Answers

If the plate diagram is to be taken literally, the dimensionality of the intermediate_var needs to be declared, since it is really three random variables each with a distinct n parameterized by the entries in input_var. This is done with the shape argument:

import pymc3

with pymc3.Model() as model:
    rate = pymc3.Beta('rate', alpha=2, beta=2)
    input_var = pymc3.Data('input_var', [1, 2, 3])
    intermediate_var = pymc3.Binomial('intermediate_var', n=input_var, p=rate, shape=3)
    output_var = pymc3.Deterministic('output_var', intermediate_var)
Related