Question about the error: Variables do not support boolean operations

I want to use boolean operations on variable. Here is the code:

with pm.Model() as hierarchical_model:
    tau = pm.Uniform('tau', lower=1, upper=100)
    for t in range(ntrials):
        if t < tau:
            ......
        else:
            ......

while I receive the error:
TypeError: Variables do not support boolean operations.

I try to use if tau.gt(t) to replace if t < tau, but receive the error:
AttributeError: ‘TensorVariable’ object has no attribute ‘gt’

I have also update NumPy to 1.22

Thanks for any help!

As you’ve discovered, you’re not allowed to use normal Python control flow operators (if, else, for, while, try, etc) inside a PyMC model. These need special implementations that allow them to be represented on a computation graph (so that we can do reverse-mode autodiff).

The special function for conditions is pm.math.switch. The API docs for it aren’t very helpful, so here’s an example model that uses a switch to find a change point on discrete data. It should give you a pattern to follow for your own model.

2 Likes