使用字符串张量的Tensorflow字典查找

mac*_*ion 22 python lookup dictionary tensorflow

有没有办法在Tensorflow中基于字符串张量执行字典查找?

在普通的Python中,我会做类似的事情

value = dictionary[key]
Run Code Online (Sandbox Code Playgroud)

.现在我想在Tensorflow运行时做同样的事情,当时我有key一个String张量.就像是

value_tensor = tf.dict_lookup(string_tensor)
Run Code Online (Sandbox Code Playgroud)

会好的.

Sau*_*ang 26

您可能会发现tensorflow.contrib.lookup有用的信息:https: //github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/lookup/lookup_ops.py

https://www.tensorflow.org/api_docs/python/tf/contrib/lookup/HashTable

特别是,您可以这样做:

table = tf.contrib.lookup.HashTable(
  tf.contrib.lookup.KeyValueTensorInitializer(keys, values), -1
)
out = table.lookup(input_tensor)
table.init.run()
print out.eval()
Run Code Online (Sandbox Code Playgroud)

  • https://www.tensorflow.org/api_docs/python/tf/contrib/lookup/HashTable (4认同)

Pra*_*rni 6

如果要使用新的TF 2.0代码运行此程序,并且默认情况下启用急切执行。以下是快速代码段。

import tensorflow as tf

# build a lookup table
table = tf.lookup.StaticHashTable(
    initializer=tf.lookup.KeyValueTensorInitializer(
        keys=tf.constant([0, 1, 2, 3]),
        values=tf.constant([10, 11, 12, 13]),
    ),
    default_value=tf.constant(-1),
    name="class_weight"
)

# now let us do a lookup
input_tensor = tf.constant([0, 0, 1, 1, 2, 2, 3, 3])
out = table.lookup(input_tensor)
print(out)
Run Code Online (Sandbox Code Playgroud)

输出:

tf.Tensor([10 10 11 11 12 12 13 13], shape=(8,), dtype=int32)
Run Code Online (Sandbox Code Playgroud)

  • 对于字符串,使用 `keys=['a', 'b', 'c']` 并将 `input_tensor` 更改为类似 `tf.constant(['a', 'a', 'c', 'b' '])`。 (2认同)

小智 -12

TensorFlow 是一种数据流语言,不支持张量以外的数据结构。没有地图或字典类型。但是,根据您的需要,当您使用 Python 包装器时,可以在驱动程序进程中维护一个字典(该字典在 Python 中执行),并使用它与 TensorFlow 图执行进行交互。例如,您可以在会话中执行 TensorFlow 图的一个步骤,将字符串值返回到 Python 驱动程序,将其用作驱动程序中字典的键,然后使用检索到的值来确定要请求的下一个计算从会议中。如果这些字典查找的速度对性能至关重要,那么这可能不是一个好的解决方案。