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

Python 使用字符串张量查找Tensorflow字典,python,dictionary,lookup,tensorflow,Python,Dictionary,Lookup,Tensorflow,有没有办法根据Tensorflow中的字符串张量执行字典查找 在普通Python中,我会执行以下操作 value = dictionary[key] value_tensor = tf.dict_lookup(string_tensor) 。现在我想在Tensorflow运行时做同样的事情,当我将键作为字符串张量时。差不多 value = dictionary[key] value_tensor = tf.dict_lookup(string_tensor) 很好。TensorFlow是

有没有办法根据Tensorflow中的字符串张量执行字典查找

在普通Python中,我会执行以下操作

value = dictionary[key]
value_tensor = tf.dict_lookup(string_tensor)
。现在我想在Tensorflow运行时做同样的事情,当我将
键作为字符串张量时。差不多

value = dictionary[key]
value_tensor = tf.dict_lookup(string_tensor)

很好。

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

您可能会发现
tensorflow.contrib.lookup
很有帮助:

特别是,您可以执行以下操作:

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

如果您希望在默认情况下启用“急切执行”的新TF 2.x代码中运行此操作。下面是快速代码片段

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)
输出:

tf.Tensor([10 10 11 11 12 12 13 13], shape=(8,), dtype=int32)

gather可以帮助您,但它只获取list的值。您可以将字典转换为键和值列表,然后应用tf.gather。例如:

# Your dict
dict_ = {'a': 1.12, 'b': 5.86, 'c': 68.}
# concrete query
query_list = ['a', 'c']

# unpack key and value lists
key, value = list(zip(*dict_.items()))
# map query list to list -> [0, 2]
query_list = [i for i, s in enumerate(key) if s in query_list]

# query as tensor
query = tf.placeholder(tf.int32, shape=[None])
# convert value list to tensor
vl_tf = tf.constant(value)
# get value
my_vl = tf.gather(vl_tf, query)

# session run
sess = tf.InteractiveSession()
sess.run(my_vl, feed_dict={query:query_list})

对于字符串,使用
键=['a','b','c']
并将
输入张量更改为类似
tf.constant(['a','a','c','b'])
。关于如何将值用作数组,有什么想法吗?比如
values=tf.constant([0.1,0.2,0.3],[0.2,0.5,0.7],[0.3,0.4,0.5]]
。我想将字符串键映射到数组值。提前感谢您的讲解!