# Question about DensityDist, again

**URL:** <https://discourse.pymc.io/t/question-about-densitydist-again/3994>\
**Category:** Questions\
**Created:** [October 21, 2019, 8:04am UTC](https://discourse.pymc.io/t/question-about-densitydist-again/3994 "2019-10-21T08:04:09Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![tboutelier](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/tboutelier/32/1222_2.png) [@tboutelier](https://discourse.pymc.io/u/tboutelier)\
**Post date:** [October 21, 2019, 8:04am UTC](https://discourse.pymc.io/t/question-about-densitydist-again/3994/1 "2019-10-21T08:04:09Z")

</div>

Hi,  
I have a model which is a monoexponential decay as a function of some _b-values_ b for which I want to estimate the decay constant ADC. The model as a function of the _b\_values_ is like:  
y\_i=s\_0\exp\{-b\_i\times ADC\} + \epsilon\_i  
where \epsilon is a i.i.d Gaussian noise with standard deviation \sigma:\epsilon \sim \mathcal{N}(0,\sigma^2). I give more detail about this model here: [How can I speed up the execution of my model?](https://discourse.pymc.io/t/how-can-i-speed-up-the-execution-of-my-model/3984)  
Assuming a [g-priror](https://en.wikipedia.org/wiki/G-prior) for \sigma and s\_0, we can marginalize those two parameters and we obtain the marginalized likelihood:

p(\mathbf{y}|ADC)\propto \left[\mathbf{y}^t\mathbf{y} - \frac{\left(\mathbf{y}^t\mathbf{f}\right)^2}{\mathbf{f}^t\mathbf{f}}\right]^{-N/2}

where \mathbf{y} is the vector containing the observation y\_i, N is the number of observations, and \mathbf{f}=\exp(-b\times ADC) is the vector of the model sampled at the observed b-values, with size N.

I tried to implement this in PyMC3 with `DensityDist`, but I get an error. Here is the code:

# Imports

```python
%matplotlib inline
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
import theano.tensor as tt
import theano
plt.style.use('seaborn-darkgrid')

```

# Data generation

```python
bvalues=np.array([0,10,20,50,100,200,500,1000],dtype=np.float) # vector of b-values
N=bvalues.size # number of bvalues

ADC=2e-3 
S0=1
Sb=S0*np.exp(-bvalues*ADC) # noise free signal
sigma=0.1

data = np.random.normal(loc=Sb, scale=sigma) # add noise to the signal

```

# PyMC3 model

```python
    with pm.Model() as marginal_likelihood_model:
        adc = pm.Lognormal('adc', np.log(4e-3), sigma=1)

        # loglikelihood function with theano
        def my_loglike_tt(adc, data):
            f = tt.exp(-bvalues * adc)
            yty = tt.sum(data**2,)
            ftf = tt.sum(f**2)
            fty = tt.sum(data*f)
            logp = -N / 2 * tt.log(yty - fty * fty / ftf)
            return logp

        # loglikelihood function with numpy
        def my_loglike_np(adc, data):
            f = np.exp(-bvalues * adc)
            yty = (data ** 2).sum() # y.T @ y
            fty = (data* f).sum() # y.T @ f
            ftf = (data** 2).sum() # f.T @ f
            logp = -N / 2 * tt.log(yty - fty * fty / ftf)

            return logp

        likelihood = pm.DensityDist('likelihood', my_loglike_tt, observed={'adc': adc, 'data': data})

    with marginal_likelihood_model:
        marginal_likelihood_trace = pm.sample(2000,tune=1000)

    pm.traceplot(marginal_likelihood_trace, var_names=['adc'],coords={'adc_dim_0':0})

```

When I execute this code, the model compiles correctly but I get an error at the inference step.

Any idea an how to make it work?

Thanks!

---

<div class="post-metadata">

**Author:** ![tboutelier](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/tboutelier/32/1222_2.png) [@tboutelier](https://discourse.pymc.io/u/tboutelier)\
**Post date:** [October 22, 2019, 8:13am UTC](https://discourse.pymc.io/t/question-about-densitydist-again/3994/2 "2019-10-22T08:13:59Z")

</div>

Hi,  
I could find a way for my code to work. Setting the number of cores to 1 `cores=1` seems to solve the problem. I don’t know why but I found that most of my models fail if I don’t set the number of cores to 1. Anyone got an idea on the reason why I have such a behaviour? I am on windows and I run my code in PyCharm.

---

<div class="post-metadata">

**Author:** ![junpenglao](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/junpenglao/32/8_2.png) [@junpenglao](https://discourse.pymc.io/u/junpenglao)\
**Post date:** [October 22, 2019, 9:37am UTC](https://discourse.pymc.io/t/question-about-densitydist-again/3994/3 "2019-10-22T09:37:24Z")

</div>

Try moving the custom log\_prob function outside of the `pm.Model` block “Lambdas defined in local namespace are not picklable (see issue [#1995](https://github.com/pymc-devs/pymc3/issues/1995))”  
ref:

> <https://github.com/pymc-devs/pymc3/blob/a01d015763f82b590a8355fec018ce2706982607/pymc3/examples/custom_dists.py#L27-L32>

---

<div class="post-metadata">

**Author:** ![tboutelier](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/tboutelier/32/1222_2.png) [@tboutelier](https://discourse.pymc.io/u/tboutelier)\
**Post date:** [October 22, 2019, 10:35am UTC](https://discourse.pymc.io/t/question-about-densitydist-again/3994/4 "2019-10-22T10:35:02Z")

</div>

Thanks, it works! Your help is much appreciated!🙂

---

<div class="post-metadata">

**Author:** ![tboutelier](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/tboutelier/32/1222_2.png) [@tboutelier](https://discourse.pymc.io/u/tboutelier)\
**Post date:** [October 23, 2019, 10:22am UTC](https://discourse.pymc.io/t/question-about-densitydist-again/3994/5 "2019-10-23T10:22:55Z")

</div>

I have one more question though:  
How can I pass other parameters that are not random variables or observed data to my function?  
Thanks!

---

<div class="post-metadata">

**Author:** ![junpenglao](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/junpenglao/32/8_2.png) [@junpenglao](https://discourse.pymc.io/u/junpenglao)\
**Post date:** [October 23, 2019, 11:41am UTC](https://discourse.pymc.io/t/question-about-densitydist-again/3994/6 "2019-10-23T11:41:17Z")

</div>

You can take a look at this post first: [How to set up a custom likelihood function for two variables](https://discourse.pymc.io/t/how-to-set-up-a-custom-likelihood-function-for-two-variables/906)
