Define model
A model is a function whose arguments are the data (matched by name to the entries of m.data_on_model). Inside it, you declare the priors of the parameters and the likelihood of the observed data; it does not need to return anything.
def model(Y, X):
# Define the model here β the parameter name is taken from the variable name
a = m.dist.normal(0, 1)
b = m.dist.normal(1, 1)
s = m.dist.exponential(1)
# Likelihood β pass the observed data through obs
m.dist.normal(a + b * X, s, obs = Y)model <- function(Y, X){
# In R, give every parameter its name explicitly
a <- bf.dist.normal(0, 1, name = "a")
b <- bf.dist.normal(1, 1, name = "b")
s <- bf.dist.exponential(1, name = "s")
bf.dist.normal(a + b * X, s, obs = Y)
}using PyBayesForge
@BF function model(Y, X)
# Define the model here β the parameter name is taken from the variable name
a = m.dist.normal(0, 1)
b = m.dist.normal(1, 1)
s = m.dist.exponential(1)
m.dist.normal(a + b * X, s, obs = Y)
endIn Julia, prefix the model function with the @BF macro, which lets BayesForge call it and adds the parameter names.
Note the additional obs argument when declaring the likelihood function. This argument is used to specify the observed data.
The name argument is optional
Every prior needs a unique name so it can be tracked in the posterior. In Python and in Julia (@BF models) you do not have to pass it: when name is omitted, BayesForge infers it from the variable the distribution is assigned to. In R, pass name = for every parameter, as in the example above (an R function cannot see the variable its result is assigned to). In the model above, a = m.dist.normal(0, 1) registers a parameter named "a", b = ... registers "b", and so on.
You can still pass name= to override the inferred name β this is useful when the posterior name must differ from the local variable (e.g. to match an external reference such as a Stan parameter):
def model(Y, X):
alpha = m.dist.normal(0, 1, name = 'a') # variable 'alpha', but posterior name is 'a'
beta = m.dist.normal(1, 1, name = 'b')
s = m.dist.exponential(1) # inferred name: 's'
m.dist.normal(alpha + beta * X, s, obs = Y)model <- function(Y, X){
alpha <- bf.dist.normal(0, 1, name = "a") # variable 'alpha', but posterior name is 'a'
beta <- bf.dist.normal(1, 1, name = "b")
s <- bf.dist.exponential(1, name = "s") # in R, name is always given
bf.dist.normal(alpha + beta * X, s, obs = Y)
}@BF function model(Y, X)
alpha = m.dist.normal(0, 1, name = "a") # variable 'alpha', but posterior name is 'a'
beta = m.dist.normal(1, 1, name = "b")
s = m.dist.exponential(1) # inferred name: 's'
m.dist.normal(alpha + beta * X, s, obs = Y)
endName inference only works for a direct assignment (param = m.dist.<...>(...)). If the result is used without being bound to a single variable β for example built inside a list/comprehension, passed straight into another call, or unpacked from a tuple β the name cannot be inferred and you must pass name= explicitly.