How to input variables into some functions in the model

Hi all, I am new to pymc3 and trying to migrate some code from Turing in Julia to pymc3. Here is a toy model of my work.

import numpy as np
import scipy
import pymc3 as pm
mu_z, Sigma_z = np.zeros(2), np.eye(2)
r = scipy.stats.multivariate_normal.rvs(np.ones(2), np.eye(2), size=5)
with pm.Model() as model:
  z = pm.MvNormal("z", mu=mu_z, cov=Sigma_z, shape=len(mu_z))
  f = lambda x : scipy.special.erf(x)
  r = pm.MvNormal("r", f(z), np.eye(2), observed=r)

What I want to do here is that setting a prior for the variable z, and implement some nonlinear transform on it (erf), and use the transformed value as the mean of the likelihood r.
The error message says that the ufunc erf not supported for the input types. Therefore, can anybody help me solve this problem? Thank you very much!

If that’s exactly what you need, you can use pm.math.erf

Thanks! This function works for me. Meanwhile, it leads to one other problem. I want to construct a matrix whose diagonal is the result of pm.math.erf(x) . For example, just like what we can do in numpy np.diag(scipy.special.erf(x)) . How can we implement this in pymc?

In general you can use theano.tensor (pymc3) or aesara.tensor (pymc 4) which implements most of numpy and scipy functions, but for the type of objects that are used by PyMC.

pm.math is just a helper to access some of the most common ones.

https://aesara.readthedocs.io/en/latest/library/tensor/basic.html#aesara.tensor.var._tensor_py_operators.diagonal

1 Like