2016-08-25 65 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中的行爲,但我很樂觀認爲這是一個很好的解決方案! –