用PYMC3 / Theano广播数学运算

时间:2016-08-25 17:21:22

标签: python theano bayesian pymc3

我认为这个问题归结为我对Theano作品缺乏理解。我想要创建一个变量,它是分布和numpy数组之间减法的结果。当我将形状参数指定为1

时,这可以正常工作
import pymc3 as pm
import numpy as np
import theano.tensor as T

X = np.random.randint(low = -10, high = 10, size = 100)

with pm.Model() as model:
    nl = pm.Normal('nl', shape = 1)
    det = pm.Deterministic('det', nl - x)

nl.dshape
(1,)

然而,当我指定形状>时,这会中断1

with pm.Model() as model:
    nl = pm.Normal('nl', shape = 2)
    det = pm.Deterministic('det', nl - X)

ValueError: Input dimension mis-match. (input[0].shape[0] = 2, input[1].shape[0] = 100)

nl.dshape
(2,)

X.shape
(100,)

我尝试调换X使其可播放

X2 = X.reshape(-1, 1).transpose()

X2.shape
(1, 100)

但现在它宣布.shape[1]而不是.shape[0]

不匹配
with pm.Model() as model:
    nl = pm.Normal('nl', shape = 2)
    det = pm.Deterministic('det', nl - X2)

ValueError: Input dimension mis-match. (input[0].shape[1] = 2, input[1].shape[1] = 100)

如果我循环遍历分发的元素

,我可以做到这一点
distShape = 2
with pm.Model() as model:
    nl = pm.Normal('nl', shape = distShape)

    det = {}
    for i in range(distShape):
        det[i] = pm.Deterministic('det' + str(i), nl[i] - X)

det
{0: det0, 1: det1}

然而,这感觉不够优雅,并且限制我为模型的其余部分使用循环。我想知道是否有办法指定此操作,以便它可以与分发一样工作。

distShape = 2
with pm.Model() as model:
    nl0 = pm.Normal('nl1', shape = distShape)
    nl1 = pm.Normal('nl2', shape = 1)

    det = pm.Deterministic('det', nl0 - nl1)

1 个答案:

答案 0 :(得分:2)

你可以做到

X = np.random.randint(low = -10, high = 10, size = 100)
X = x[:,None] # or x.reshape(-1, 1)

然后

with pm.Model() as model:
    nl = pm.Normal('nl', shape = 2)
    det = pm.Deterministic('det', nl - X)

在这种情况下,nl和X的形状将分别为((2,1),(100,)),然后可播放。

请注意,我们使用两个NumPy数组(不仅是一个Theano张量和一个NumPy数组)获得相同的行为

a0 = np.array([1,2])
b0 = np.array([1,2,3,5])
a0 = a0[:,None]  # comment/uncomment this line
print(a0.shape, b0.shape)
b0-a0