在PYMC3中使用自定义似然导致“预期的ndarray”出错

时间:2017-11-03 19:42:27

标签: theano pymc3

我正在尝试在PYMC3中使用自定义分布(广义极值或GEV分布)。我已经编写了一些代码来计算它,但是我得到了

的错误
  

ValueError:期望一个ndarray   应用导致错误的节点:MakeVector {dtype ='float64'}( logp_sigma_log ,__ logp_mu,__ logp_xi,__ logp_x)

以下是供参考的代码:

@theano.as_op(itypes=[tt.dvector, tt.dscalar, tt.dscalar, tt.dscalar],
              otypes=[tt.dscalar])
def likelihood_op(values, mu, sigma, xi):
    logp = 0.
    for val in values:
        logp += genextreme.logpdf(val,-xi,loc=mu,scale=sigma)
    return logp

def gev_ll(values):
    return likelihood_op(values, mu, sigma, xi)



with pymc3.Model() as model:
    mean_sigma = 0.0
    sd_sigma   = 5.0
    sigma      = pymc3.Lognormal('sigma',mu = mean_sigma,tau = sd_sigma)

    mean_mu = 0.0
    sd_mu   = 40.0
    mu      = pymc3.Normal('mu',mu=mean_mu,sd =sd_mu)

    mean_xi = 0.0
    sd_xi   = 2.0
    xi      = pymc3.Normal('xi',mu = mean_xi, sd = sd_xi)

    x = pymc3.DensityDist('x',gev_ll,observed = np.squeeze(maxima.values ))
    step = pymc3.Metropolis()
    trace = pymc3.sample(draws=1000,step=step,n_int = 10000,tune = 1000,n_jobs = 4)
    print 'Gelman-Rubin diagnostic: {0}'.format(pymc3.diagnostics.gelman_rubin(trace))

1 个答案:

答案 0 :(得分:1)

事实证明,这个错误是因为likelihood_op的返回值需要是一个numpy数组。一旦我改变了

def likelihood_op(values, mu, sigma, xi):
    logp = 0.
    for val in values:
        logp += genextreme.logpdf(val,-xi,loc=mu,scale=sigma)
    return logp

def likelihood_op(values, mu, sigma, xi):
    logp = 0.
    for val in values:
        logp += genextreme.logpdf(val,-xi,loc=mu,scale=sigma)
    return np.array(logp)

然后图表编译得很好,我能够进行采样。