2017-02-02 36 views
2

我正在寫一個簡單的代碼來計算索引列表的單熱編碼。 例如:[1,2,3] => [[0,1,0,0],[0,0,1,0],[0,0,0,1]]如何使用theano中的scan函數遍歷theano矩陣的行?

我寫了一個功能做同樣的一個載體:

n_val =4 
def encoding(x_t): 
    z = T.zeros((x_t.shape[0], n_val)) 
    one_hot = T.set_subtensor(z[T.arange(x_t.shape[0]), x_t], 1) 
    return one_hot 

重複同樣的功能在矩陣的行,我做以下,

x = T.imatrix() 
[m],_ = theano.scan(fn = encoding, sequences = x) 

Y = T.stacklists(m) 
f= theano.function([x],Y) 

我期待一個三維張量每片對應於矩陣行的單熱編碼。

我收到以下錯誤,而編譯功能,

/Library/Python/2.7/site-packages/theano/tensor/var.pyc in __iter__(self) 
594   except TypeError: 
595    # This prevents accidental iteration via builtin.sum(self) 
--> 596    raise TypeError(('TensorType does not support iteration. ' 
    597        'Maybe you are using builtin.sum instead of ' 
598        'theano.tensor.sum? (Maybe .max?)')) 

TypeError: TensorType does not support iteration. Maybe you are using builtin.sum instead of theano.tensor.sum? (Maybe .max?) 

是否有人可以幫助我瞭解我要去的地方錯了,我怎麼能修改代碼,即可獲得我需要什麼?

在此先感謝。

+0

'scan'的'fn'參數必須返回一個列表的代碼 – Kh40tiK

回答

1

這裏是工作

# input a matrix, expect scan to work with each row of matrix 
my_matrix = np.asarray([[1,2,3],[1,3,2],[1,1,1]]) 

x = T.imatrix() 

def encoding(idx): 
    z = theano.tensor.zeros((idx.shape[0], 4)) 
    one_hot = theano.tensor.set_subtensor(z[theano.tensor.arange(idx.shape[0]), idx], 1) 
    return one_hot 

m, update = theano.scan(fn=encoding, 
         sequences=x) 


f = theano.function([x], m) 

##########3 
result = f(my_matrix) 
print (result)