[英]How to index a list with a TensorFlow tensor?
假設需要通過查找表訪問的具有不可連接對象的列表。 因此列表索引將是張量對象,但這是不可能的。
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
是使用張量索引列表的方法/解決方法嗎?
tf.gather
就是為此目的而設計的。
只需運行tf.gather(list, tf_look_up[index])
,您就可以獲得所需內容。
Tensorflow實際上支持HashTable
。 有關詳細信息,請參閱文檔 。
在這里,您可以做的是以下內容:
table = tf.contrib.lookup.HashTable(
tf.contrib.lookup.KeyValueTensorInitializer(tf_look_up, list), -1)
然后通過運行獲得所需的輸入
target = table.lookup(index)
請注意,如果找不到密鑰,則-1
是默認值。 您可能必須根據張量的配置將key_dtype
和value_dtype
添加到構造函數中。
我認為這會有所幫助: 如何在TensorFlow中將張量轉換為numpy數組?
“要從張量轉換回numpy數組,你可以簡單地在變換張量上運行.eval()。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.