2016-01-20 62 views
3

我想要實現的功能theano以下功能一個矩陣值映射到另一個,如何theano功能

a=numpy.array([ [b_row[dictx[idx]] if idx in dictx else 0 for idx in range(len(b_row))] 
       for b_row in b]) 
where a, b are narray, and dictx is a dictionary 

我得到了錯誤TensorType does not support iteration 我一定要使用掃描?或者有沒有更簡單的方法? 謝謝!

+0

我敢肯定,這是可能的使用花哨的索引巧妙。如果你可以做一個實際運行的小例子,並且準確地說明你想要什麼,那麼製作theano版本會更容易。 – eickenberg

回答

2

由於b的類型是ndarray,我們假設每個b_row具有相同的長度。

如果我理解正確,代碼將根據dictx交換b中列的順序,並用零填充未指定的列。

主要問題是Theano沒有類似字典的數據結構(請讓我知道如果有的話)。

因爲在您的示例中,字典鍵和值是range(len(b_row))內的整數,解決此問題的一種方法是構造一個使用索引作爲鍵的向量(如果某些索引不應包含在字典中,請將其值 - 1)。

同樣的想法應該適用於一般矩陣的映射元素,並且當然還有其他(更好的)方法來做到這一點。

這是代碼。
NumPy的:

dictx = {0:1,1:2} 
b = numpy.asarray([[1,2,3], 
       [4,5,6], 
       [7,8,9]]) 
a = numpy.array([[b_row[dictx[idx]] if idx in dictx else 0 for idx in range(len(b_row))] for b_row in b]) 
print a 

Theano:

dictx = theano.shared(numpy.asarray([1,2,-1])) 
b = tensor.matrix() 
a = tensor.switch(tensor.eq(dictx, -1), tensor.zeros_like(b), b[:,dictx]) 
fn = theano.function([b],a) 
print fn(numpy.asarray([[1,2,3], 
         [4,5,6], 
         [7,8,9]])) 

它們都打印:

[[2 3 0] 
[5 6 0] 
[8 9 0]] 
+0

是的,它應該是範圍(len(b_row)),我已經解決了這個問題。感謝您的解決方案! –

+0

@IreneW。不用謝 – dontloo