Question about calling log_prob in stan model

Hi, I am trying to compute log density manually using pystan 3.5, but keep getting error message . Can anyone check where my test codes in python go wrong or offer any example codes about it? I really appreciate your help!


def my_log_prob(x, data, seed, modelDir, modelName):
        with open(os.path.join(modelDir, modelName + ".stan")) as f:
            modelCode = f.read()
        posterior = stan.build(program_code = modelCode, data = data[modelName], random_seed = seed)
        unconstrained_parms = posterior.unconstrain_pars(constrained_parameters = x)

The parameter x here is a list of dictionary of fixed parameters. And the error message is the following:
Object of type ndarray is not JSON serializable

The error message is:

Object of type ndarray is not JSON serializable

I don’t use PyStan, but I assume what’s going on is that you’re supplying data in the form of an ndarray, but PyStan is using a default JSON serializer which doesn’t accept ndarrays. The solution would be to convert back to a regular Python array or list, for example with .tolist().

I would generally recommend cmdstanpy these days if you only need to fit models. It keeps up with Stan releases and is much easier to install and also faster. It’s missing some of the features of PyStan, but many of those are made up in the BridgeStan package.

Thank you Bob!