Conditional statement within a pymc3 model

Hi all!

I was wondering if it’s possible to include a conditional statement within a pymc3 model. Let’s say I’m building a model based on 3 coefficients, that looks like the following:

with pm.Model as model:
    x = pm.Data("x", x_obs, dims="obs_id")

    a = pm.Normal("a", mu=0.0, sigma=1.0)
    b = pm.Normal("b", mu = 0.0, sigma = 1.0)
    c = pm.Normal("c", mu = 18.0, sigma = 1.0)

    mu = a + b * (x - c)

    sigma = pm.Exponential("sigma", 1.0)

    y = pm.Normal("y", mu, sigma=sigma, observed=y_obs, dims="obs_id")

I would be interested in adding a conditional statement, when evaluating the (x-c) bit, so that the value included in the model will be (x-c) if (x-c) is positive, otherwise it will be 0. In python syntax, I think it would be something like:

    np.where(x-c > 0, x-c, 0)

Would it be possible to include such a statement in my probabilistic model?

Thanks in advance for your help!

You might be looking for aesara’s ifelse() function.

1 Like

Can’t you just multiply with the boolean (x-c>0)? Otherwise tt.switch() might also work for you.


Thanks to both, I didn’t know you could include booleans in the models. Multiplying by (x-c>0) solved my issue!

Could you post the solution code? I am not sure what is meant by multiply by the boolean…

Thank you!

I assume the solution is something along the lines of this:

mu = a + b * ( ((x-c) > 0) * (x-c) )

For those still looking for other options, I will also note that you can get similar behavior out of aesara.tensor.clip().

1 Like

Ah thank you! So the boolean is taken in theano (and numpy and aesara) as zero…

I did not know that… that is nice “universal” trick

1 Like