2016-08-25 36 views
1

我认为这个问题归结为我对Theano作品缺乏了解。我处于这种情况,我想创建一个变量,该变量是分布和numpy数组之间相减的结果。当我指定的形状参数为1与PYMC3广播数学运算/ Theano

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使它broadcastable

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) 

回答

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) 

在这种情况下n1和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 
+0

谢谢!我将不得不再次检查这是否产生了我想要的pymc3中的行为,但我很乐观认为这是一个很好的解决方案! –