无法在分层 pymc3 模型中创建 lambda 函数 [英] Unable to create lambda function in hierarchical pymc3 model

查看:33
本文介绍了无法在分层 pymc3 模型中创建 lambda 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PyMC 3 创建如下所示的模型,但无法弄清楚如何使用 lambda 函数将概率正确映射到观察到的数据.

I'm trying to create the model shown below with PyMC 3 but can't figure out how to properly map probabilities to the observed data with a lambda function.

import numpy as np
import pymc as pm

data = np.array([[0, 0, 1, 1, 2],
                 [0, 1, 2, 2, 2],
                 [2, 2, 1, 1, 0],
                 [1, 1, 2, 0, 1]])
(D, W) = data.shape
V = len(set(data.ravel()))
T = 3
a = np.ones(T)
b = np.ones(V)

with pm.Model() as model:
    theta = [pm.Dirichlet('theta_%s' % i, a, shape=T) for i in range(D)]
    z = [pm.Categorical('z_%i' % i, theta[i], shape=W) for i in range(D)]
    phi = [pm.Dirichlet('phi_%i' % i, b, shape=V) for i in range(T)]
    w = [pm.Categorical('w_%i_%i' % (i, j),
                        p=lambda z=z[i][j], phi_=phi: phi_[z], # Error is here
                        observed=data[i, j])
            for i in range(D) for j in range(W)]

我得到的错误是

AttributeError: 'function' object has no attribute 'shape'

在我尝试构建的模型中,z 的元素表示 phi 中的哪个元素给出了 data<中相应观测值的概率/code>(放置在 RV w 中).换句话说,

In the model I'm attempting to build, the elements of z indicate which element in phi gives the probability of the corresponding observed value in data (placed in RV w). In other words,

P(data[i,j]) <- phi[z[i,j]][data[i,j]]

我猜我需要用 Theano 表达式或使用 Theano as_op 来定义概率,但我不知道如何为这个模型做到这一点.

I'm guessing I need to define the probability with a Theano expression or use Theano as_op but I don't see how it can be done for this model.

推荐答案

您应该将您的分类 p 值指定为 Deterministic 对象,然后再将它们传递给 w.否则,as_op 实现将如下所示:

You should specify your categorical p values as Deterministic objects before passing them on to w. Otherwise, the as_op implementation would look something like this:

@theano.compile.ops.as_op(itypes=[t.lscalar, t.dscalar, t.dscalar],otypes=[t.dvector])
def p(z=z, phi=phi):
    return [phi[z[i,j]] for i in range(D) for j in range(W)]

这篇关于无法在分层 pymc3 模型中创建 lambda 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆