2016-12-16 125 views
4

假定需要通過查找表訪問非可連接對象的列表。所以列表索引將是一個張量對象,但這是不可能的。如何用TensorFlow張量索引列表?

tf_look_up = tf.constant(np.array([3, 2, 1, 0, 4])) 
index = tf.constant(2) 
list = [0,1,2,3,4] 

target = list[tf_look_up[index]] 

這將帶出以下錯誤信息。

TypeError: list indices must be integers or slices, not Tensor 

索引與張量列表的方法/解決方法?

+0

使用sess.run首先將張量轉換爲numpy –

+0

@YaroslavBulatov如果列表是動態生成的,例如RNN產生的狀態。任何方式列表動態索引將工作? – chentingpc

+0

也許'tf.gather'就像在@ soloice的答案? –

回答

0

我認爲這將有助於: How can I convert a tensor into a numpy array in TensorFlow?

「從張量轉換回numpy的數組,你可以簡單地在變換張量運行.eval()。」

+0

這可以起作用,但它大大增加了「編譯時間」。你知道一種預編譯TensorFlow圖形部分的方法嗎? – spreisel

+0

@spreisel,不幸的是,我沒有。我可以想象,由於缺少錯誤,時間會增加嗎?我不確定tbh,我不太瞭解TF。 – Kelvin

1

Tensorflow實際上支持HashTable。有關更多詳細信息,請參閱documentation

在這裏,你可以做的是:

table = tf.contrib.lookup.HashTable(
    tf.contrib.lookup.KeyValueTensorInitializer(tf_look_up, list), -1) 

然後只需運行

target = table.lookup(index) 

注意-1是默認值,如果關鍵是沒有找到得到期望的輸入。您可能必須將key_dtypevalue_dtype添加到構造函數,具體取決於張量的配置。

3

tf.gather是爲此目的而設計的。

只需運行tf.gather(list, tf_look_up[index]),你會得到你想要的。