Matmul on deterministic variable TypeError

Hi there

I’m trying to run a non-centered hierarchical model, and running into a type error while trying to do matrix multiplication on a pm.Deterministic variable.

I have tried various different things like using np.matmul explicitly, using np.dot and taking the beta_unit * beta_sigma + beta_mu expression out of the pm.Deterministic class, but I run into errors with everything I try. (Happy to provide more details here).

This seems like relatively simple functionality; I wonder if anyone else has run into this, or if there’s a known way to achieve this?

Thanks in advance for any advice
David

import numpy as np
import pymc3 as pm

# random data to illustrate TypeError
X = np.random.randn(104, 216)
Y = np.random.rand(104)

# model
with pm.Model() as non_centered_model:
    
    # hyperpriors
    beta_mu = pm.Normal("beta_mu", mu=1, sigma=1)
    beta_sigma = pm.Exponential("beta_sigma", 1)
    
    # priors
    beta_unit = pm.Normal("beta_unit", mu=0, sigma=1, shape=X.shape[1])
    beta = pm.Deterministic("beta", beta_unit * beta_sigma + beta_mu)
    sigma = pm.Exponential("sigma", 1)
    
    # likelihood
    pm.Normal("lik", mu=X @ beta, sigma=sigma, observed=Y)
    
    idata_non_centered = pm.sample(return_inferencedata=True)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [150], in <cell line: 9>()
     18 sigma = pm.Exponential("sigma", 1)
     20 # likelihood
---> 21 pm.Normal("lik", mu=X @ beta, sigma=sigma, observed=Y)
     23 idata_non_centered = pm.sample(return_inferencedata=True)

TypeError: unsupported operand type(s) for @: 'numpy.ndarray' and 'DeterministicWrapper'
1 Like

When performing algebraic operations on parameters, you often have the functions in pm.math (many of which mirror their numpy counterparts). Also, see here.

Thanks for that. Sorry for not properly searching the docs.

1 Like