Ejemplo n.º 1
0
#         "n": np.array([1183, 1510, 1597, 1924, 1178, 1324, 2173, 845]),
#         "N": 8}
# Kobe Bryant's whole field goal record from NBA records:
data = {"y": np.array([176, 391, 362, 554, 701, 749, 868, 516, 573, 978, 813, 775, 800, 716, 740]),
        "n": np.array([422, 913, 779, 1183, 1510, 1597, 1924, 1178, 1324, 2173, 1757, 1690, 1712, 1569, 1639]),
        "N": 15}

# Create the model
model = bd.Model()

# Prior p(m)
model.add_node(bd.Node("p", bd.Uniform(0, 1)))

# Likelihood p(D|n,p) place holder.
for i in range(0, data["N"]):
    suc = "y{index}".format(index=i)
    atp = "n{index}".format(index=i)
    model.add_node(bd.Node(suc, bd.Binomial(atp, "p"), observed=True))


# Create the C++ code
bd.generate_h(model, data)
bd.generate_cpp(model, data)

# take1      log(Z) = -39.2245367341 with Ntz original data
# take2      log(Z) = -39.223614467  with Ntz original data
# Analytical log(Z) = -39.2308

# take1      log(Z) = -69.0177594483 with whole record
# Analytical log(Z) = -69.0231
Ejemplo n.º 2
0
        formula += "beta_{j}_5 * SW{i} * PL{i}"
        formula = formula.format(i=i, j=j)
        model.add_node(bd.Node(name, bd.Delta(formula)))

    # Normalising constant
    name = "Z_{i}".format(i=i)
    formula = ""
    formula += "exp(p_0_{i}) + exp(p_1_{i}) + exp(p_2_{i})"
    formula = formula.format(i=i)
    model.add_node(bd.Node(name, bd.Delta(formula)))

    # Probability of the data point.
    name = "prob_{i}".format(i=i)
    formula = "exp(p_{Species}_{i}) / Z_{i}".format(i=i,
                                                    Species=data["Species"][i])
    model.add_node(bd.Node(name, bd.Delta(formula)))

    # One Trick - this is like the "zeroes trick" in JAGS
    name = "ones{i}".format(i=i)
    distribution = bd.Binomial(1, "prob_{i}".format(i=i))
    node = bd.Node(name, distribution, observed=True)
    model.add_node(node)

# Create the C++ code
bd.generate_h(model, data)
bd.generate_cpp(model, data)

# Compile the C++ code so it's ready to go
import os
os.system("make")
# Create the model
model = bd.Model()

# Coefficients
model.add_node(bd.Node("beta_0", bd.Normal(0, 10)))
model.add_node(bd.Node("beta_1", bd.Normal(0, 10)))

# Sampling Distribution
for i in range(0, data["N"]):
    name = "CHD{i}".format(i=i)
    #prob = "exp(beta_0 + beta_1 * Age{i})/(1.0 + exp(beta_0 + beta_1 * Age{i}))"
    prob = "exp(beta_0 + beta_1 * Age{i})"
    prob += "/(1.0 + exp(beta_0 + beta_1 * Age{i}))"
    prob = prob.format(i=i)
    distribution = bd.Binomial(1, prob)
    node = bd.Node(name, distribution, observed=True)
    model.add_node(node)

# Extra node for prediction
name = "CHDnew"
prob = "exp(beta_0 + beta_1 * 35)/(1.0 + exp(beta_0 + beta_1 * 35))"
distribution = bd.Delta(prob)
node = bd.Node(name, distribution)
model.add_node(node)

# Create the C++ code
bd.generate_h(model, data)
bd.generate_cpp(model, data)

# Compile the C++ code so it's ready to go