Skip to content

Custom distribution #1812

Closed
Closed
@davidbrochart

Description

@davidbrochart

It looks like the creation of a custom Continuous distribution is broken in PyMC3. In the example below, I get the following error:

ValueError: expected an ndarray
Apply node that caused the error: Elemwise{Composite{((i0 + (i1 * i2)) - (i3 + (i4 * i5)))}}[(0, 0)](FromFunctionOp{beta_logp}.0, TensorConstant{0.5}, Sum{acc_dtype=float64}.0, FromFunctionOp{beta_logp}.0, TensorConstant{0.5}, Sum{acc_dtype=float64}.0)
Toposort index: 10
Inputs types: [TensorType(float64, scalar), TensorType(float64, scalar), TensorType(float64, scalar), TensorType(float64, scalar), TensorType(float64, scalar), TensorType(float64, scalar)]
Inputs shapes: [(), (), (), (), (), ()]
Inputs strides: [(), (), (), (), (), ()]
Inputs values: [-0.2159736732943715, array(0.5), array(-458.9112207578818), -0.0, array(0.5), array(-400.5085556528546)]
Outputs clients: [['output']]
HINT: Re-running with most Theano optimization disabled could give you a back-trace of when this node was created. This can be done with by setting the Theano flag 'optimizer=fast_compile'. If that does not work, Theano optimizations can be disabled with 'optimizer=None'.
HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.

from pymc3.distributions import Continuous, Normal
from pymc3 import Model, sample, Metropolis
from theano import as_op
import theano.tensor as T
import numpy as np

size = 100
b = 2

X = np.linspace(0, 1, size)
Y = b * X + np.random.randn(size)

class Beta(Continuous):
    def __init__(self, mu, *args, **kwargs):
        super(Beta, self).__init__(*args, **kwargs)
        self.mu = mu
        self.mode = mu
    def logp(self, value):
        mu = self.mu
        return beta_logp(value - mu)

@as_op(itypes=[T.dscalar], otypes=[T.dscalar])
def beta_logp(value):
    return -1.5 * np.log(1 + (value) ** 2)

with Model() as model:
    # Create custom densities
    beta = Beta('slope', mu=0, testval=0)
    # Create likelihood
    like = Normal('y_est', mu=beta * X, sd=1, observed=Y)
    step = Metropolis([beta])
    trace = sample(100, step)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions