當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python tf.compat.v1.lookup.StaticHashTable用法及代碼示例

一個初始化後不可變的通用哈希表。

繼承自:StaticHashTableTrackableResource

用法

tf.compat.v1.lookup.StaticHashTable(
    initializer, default_value, name=None, experimental_is_anonymous=False
)

參數

  • initializer 要使用的表初始值設定項。有關受支持的鍵和值類型,請參閱HashTable 內核。
  • default_value 表中缺少鍵時使用的值。
  • name 操作的名稱(可選)。
  • experimental_is_anonymous 是否對表使用匿名模式(默認為 False)。在匿名模式下,表資源隻能通過資源句柄訪問。它不能通過名字來查找。當所有指向該資源的資源句柄都消失時,該資源將被自動刪除。

屬性

  • default_value 表的默認值。
  • initializer
  • key_dtype 表鍵數據類型。
  • name 表的名稱。
  • resource_handle 返回與此資源關聯的資源句柄。
  • value_dtype 表值 dtype。

在圖形模式下運行時,必須先評估 tf.tables_initializer() 返回的張量,然後再評估此類的 lookup() 方法返回的張量。圖形模式下的示例用法:

keys_tensor = tf.constant([1, 2])
vals_tensor = tf.constant([3, 4])
input_tensor = tf.constant([1, 5])
table = tf.lookup.StaticHashTable(
    tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1)
out = table.lookup(input_tensor)
with tf.Session() as sess:
    sess.run(tf.tables_initializer())
    print(sess.run(out))

請注意,在圖形模式下,如果將 experimental_is_anonymous 設置為 True ,則應僅調用 Session.run 一次,否則每個 Session.run 將創建(並銷毀)一個彼此無關的新表,從而導致諸如“表未初始化”。你可以這樣做:

keys_tensor = tf.constant([1, 2])
vals_tensor = tf.constant([3, 4])
input_tensor = tf.constant([1, 5])
table = tf.lookup.StaticHashTable(
    tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1,
    experimental_is_anonymous=True)
with tf.control_dependencies([tf.tables_initializer()]):
  out = table.lookup(input_tensor)
with tf.Session() as sess:
  print(sess.run(out))

在 Eager 模式下,不需要特殊代碼來初始化表。即刻模式下的示例用法:

tf.enable_eager_execution()
keys_tensor = tf.constant([1, 2])
vals_tensor = tf.constant([3, 4])
input_tensor = tf.constant([1, 5])
table = tf.lookup.StaticHashTable(
    tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1)
print(table.lookup(input_tensor))

相關用法


注:本文由純淨天空篩選整理自tensorflow.org大神的英文原創作品 tf.compat.v1.lookup.StaticHashTable。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。